Files
Marc Schier 5795e50b58 Source-generated, NativeAOT-clean fluent server API with event-source publish (#3765)
* Add async read/write hooks to BaseVariableState and AsyncCustomNodeManager

Introduces an end-to-end async path for variable Value-attribute reads
and writes that does not require holding lock(this) while the user
callback executes:

* New AttributeReadResult, AttributeSimpleReadResult and AttributeWriteResult
  readonly record structs in NodeState carry the typed result of an async
  Value-attribute hook (no ref/out params across await).
* Four new async delegates (NodeValueEventHandlerAsync,
  NodeValueSimpleEventHandlerAsync, NodeValueWriteEventHandlerAsync,
  NodeValueSimpleWriteEventHandlerAsync) sit alongside the existing sync
  hooks.
* NodeState gains virtual ReadAttributeAsync / WriteAttributeAsync methods.
  The default implementation wraps the synchronous call in lock(this) so
  callers that have not opted into async hooks see bit-identical behaviour.
* BaseVariableState exposes OnReadValueAsync, OnSimpleReadValueAsync,
  OnWriteValueAsync and OnSimpleWriteValueAsync slots and overrides the new
  virtuals to dispatch to them WITHOUT holding the lock during the await.
  On simple-read the framework still applies index range, data encoding and
  copy policy; on simple-write the cached value/status/timestamp are
  updated under lock after the hook completes.
* AsyncCustomNodeManager.ReadAsync and WriteAsync now await the new
  ReadAttributeAsync / WriteAttributeAsync entry points instead of taking
  lock(source) around the synchronous call. Existing per-source locking
  semantics are preserved by the default async wrappers.
* The fluent INodeBuilder surface gains four new async OnRead/OnWrite
  overloads that wire to the new BaseVariableState slots, with the same
  ThrowIfSlotOccupied + null-check pattern as the sync overloads.

* Add typed IVariableBuilder<T> fluent surface

Adds typed sub-interfaces and impls so the existing fluent surface

can expose simple Func<T> / Action<T> / Func<CancellationToken,

ValueTask<T>> overloads for variables — without losing the lower-level

Variant-based overloads on INodeBuilder.

* IVariableBuilder<TValue> + VariableBuilder<TValue> derive from

  INodeBuilder<BaseVariableState> / NodeBuilder<BaseVariableState>

  (NodeBuilder<TState> unsealed).

* Marshalling uses Variant.AsBoxedObject(BoxingBehavior.Legacy) for

  reads and Variant(object) for writes; the AOT-unsafe write path is

  scoped-suppressed with a TODO pointing at the planned per-type

  generated walker.

* INodeManagerBuilder gains Variable<T>(string),

  Variable<T>(NodeId), VariableFromTypeId<T>(NodeId),

  VariableFromTypeId<T>(NodeId, QualifiedName).

Server library builds clean across all 6 TFMs.

* Add relative-child traversal API on INodeBuilder

Adds INodeBuilder.Child(QualifiedName), Child<TState>(QualifiedName)

and Variable<TValue>(QualifiedName) so source-generated typed

wrappers can walk one segment at a time without re-resolving from

the manager root. Resolution uses NodeState.FindChild and reuses

NodeManagerBuilder.ToVariableBuilder to keep the typed-variable

marshalling story consistent.

Adds 7 NUnit cases (Fluent category) covering the happy path,

type-mismatch, null/missing browse-name, and non-variable

rejection. All 66 fluent tests pass.

* Mix old + new fluent APIs in MinimalBoilerServer demo

BoilerNodeManager.Configure now exercises five wiring styles:

  (1) browse-path with the legacy ref-Variant callback

  (2) absolute NodeId with the legacy ref-Variant callback

  (3) typed Variable<double>(NodeId) + simple Func<double> sync getter

  (4) typed Variable<double>(NodeId) + Func<CancellationToken, ValueTask<double>>

      async getter — exercises the BaseVariableState.OnReadValueAsync

      slot end-to-end through AsyncCustomNodeManager.ReadAsync

  (5) NodeFromTypeId with OnNodeAdded lifecycle hook

All five styles compose against the same INodeManagerBuilder, with

the typed and async callbacks pulling in the new IVariableBuilder<T>

surface (committed at e557ecdd9) and the BaseVariableState async

path (committed at 2e2efb4ad).

* Add async-hook tests for BaseVariableState

15 NUnit cases covering the new On{Read,Write}ValueAsync and On
Simple{Read,Write}ValueAsync slots plus the
ReadAttributeAsync/WriteAttributeAsync overrides on
BaseVariableState:

* full async slot routes Value reads/writes
* lock(this) is released around the awaited handler
* simple async slot reapplies cached StatusCode and respects index
  ranges (BadIndexRangeInvalid for non-null ranges)
* exceptions and OperationCanceledException from the hook are
  caught and surfaced as BadUnexpectedError, mirroring the sync flow
* CancellationToken propagates to the hook
* cache (m_value, m_statusCode, m_timestamp) is updated on success
  and skipped on Bad return
* fallback to base sync ReadAttribute/WriteAttribute when no async
  slot is set (preserves today's lock(this) semantics)
* non-Value attributes never invoke the async hook
* CurrentRead/CurrentWrite access checks short-circuit before the
  hook runs

All 596 State tests pass on net10.0.

* Add round-trip tests for typed IVariableBuilder<T>

Covers the typed Func<T>/Action<T>/Func<...,ValueTask<T>> overloads
on IVariableBuilder<TValue>: each registers the appropriate hook
slot on the underlying BaseDataVariableState, and driving the
variable through ReadAttribute/WriteAttribute (sync) and
ReadAttributeAsync/WriteAttributeAsync (async) reproduces the
typed values the user supplied.

* Add typed model-traversal source generator

Adds FluentBuilderGenerator that walks the design's predefined-instance tree and emits a typed sibling for every NodeManagerBuilder. Each generated wrapper exposes IntelliSense-friendly accessors for child instances, variables (IVariableBuilder<T>) and methods (sync/async OnCall) so wiring sites become builder.Boilers.Boiler__1.LCX001.Measurement.OnRead(...) instead of a stringly typed browse path. The NodeManager template now also emits a Configure(I{Manager}NodeManagerBuilder) partial alongside the existing Configure(INodeManagerBuilder); both partials run, both are optional, and the typed surface is fully AOT-safe (no dynamic, no MakeGenericType, no reflection).

* Add tests for the typed model-traversal source generator

Adds 9 snapshot tests in Tests/Opc.Ua.SourceGeneration.Core.Tests covering the FluentBuilderGenerator's opt-in flag, typed-manager-interface and proxy emission, internal-sealed visibility, lazy child resolution via Context.NamespaceUris.GetIndexOrAppend, IVariableBuilder<TValue> accessors, sync+async OnCall overloads on method wrappers, and the dual Configure(INodeManagerBuilder)/Configure(I{Manager}NodeManagerBuilder) partial wiring in the NodeManager template. Adds 2 end-to-end AOT tests in Tests/Opc.Ua.Aot.Tests that exercise typed-traversal sync read on LCX001/Measurement and typed-traversal async OnCall on Simulation/Halt through the AOT-compiled MinimalBoilerServer fixture.

* Document the typed model-traversal Configure(I{Manager}NodeManagerBuilder) partial
2026-05-15 07:52:49 +02:00

115 lines
4.9 KiB
XML

<?xml version="1.0" encoding="utf-8"?>
<!--
* Copyright (c) 2005-2025 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
-->
<opc:ModelDesign
xmlns:uax="http://opcfoundation.org/UA/2008/02/Types.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ua="http://opcfoundation.org/UA/"
xmlns:opc="http://opcfoundation.org/UA/ModelDesign.xsd"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://opcfoundation.org/UA/Calc/"
TargetNamespace="http://opcfoundation.org/UA/Calc/"
TargetXmlNamespace="http://opcfoundation.org/UA/Calc/Types.xsd"
TargetVersion="1.00.0"
TargetPublicationDate="2025-01-01T00:00:00Z">
<opc:Namespaces>
<opc:Namespace Name="Calc" Prefix="Calc" XmlNamespace="http://opcfoundation.org/UA/Calc/Types.xsd" XmlPrefix="Calc">http://opcfoundation.org/UA/Calc/</opc:Namespace>
<opc:Namespace Name="OpcUa" Prefix="Opc.Ua" Version="1.05.07" PublicationDate="2025-12-25T00:00:00Z" InternalPrefix="Opc.Ua.Server" XmlNamespace="http://opcfoundation.org/UA/2008/02/Types.xsd" XmlPrefix="OpcUa">http://opcfoundation.org/UA/</opc:Namespace>
</opc:Namespaces>
<!--
Top-level MethodType declarations. The model compiler emits one
typed MethodState subclass per top-level Method (AddMethodState,
MultiplyMethodState, ConcatMethodState) plus the matching typed
OnCall delegate so the source-generated fluent surface can offer
Func<T1, T2, TResult> (sync) and Func<T1, T2, CancellationToken,
ValueTask<TResult>> (async) overloads on each MethodBuilder.
-->
<opc:Method SymbolicName="AddMethodType">
<opc:Description>Returns a + b.</opc:Description>
<opc:InputArguments>
<opc:Argument Name="a" DataType="ua:Int32">
<opc:Description>First addend.</opc:Description>
</opc:Argument>
<opc:Argument Name="b" DataType="ua:Int32">
<opc:Description>Second addend.</opc:Description>
</opc:Argument>
</opc:InputArguments>
<opc:OutputArguments>
<opc:Argument Name="sum" DataType="ua:Int32">
<opc:Description>Computed sum.</opc:Description>
</opc:Argument>
</opc:OutputArguments>
</opc:Method>
<opc:Method SymbolicName="MultiplyMethodType">
<opc:Description>Returns a * b. Wired with the asynchronous typed OnCall overload.</opc:Description>
<opc:InputArguments>
<opc:Argument Name="a" DataType="ua:Double">
<opc:Description>First factor.</opc:Description>
</opc:Argument>
<opc:Argument Name="b" DataType="ua:Double">
<opc:Description>Second factor.</opc:Description>
</opc:Argument>
</opc:InputArguments>
<opc:OutputArguments>
<opc:Argument Name="product" DataType="ua:Double">
<opc:Description>Computed product.</opc:Description>
</opc:Argument>
</opc:OutputArguments>
</opc:Method>
<opc:Method SymbolicName="ConcatMethodType">
<opc:Description>Returns left + right.</opc:Description>
<opc:InputArguments>
<opc:Argument Name="left" DataType="ua:String">
<opc:Description>Left-hand string.</opc:Description>
</opc:Argument>
<opc:Argument Name="right" DataType="ua:String">
<opc:Description>Right-hand string.</opc:Description>
</opc:Argument>
</opc:InputArguments>
<opc:OutputArguments>
<opc:Argument Name="result" DataType="ua:String">
<opc:Description>Concatenated value.</opc:Description>
</opc:Argument>
</opc:OutputArguments>
</opc:Method>
<!--
CalculatorType binds the three method types as Mandatory children so
every CalculatorType instance exposes the Add/Multiply/Concat
methods at fixed browse paths. The predefined Calculator instance
just below uses CalculatorType so users only need to wire one set
of OnCall handlers.
-->
<opc:ObjectType SymbolicName="CalculatorType" BaseType="ua:BaseObjectType">
<opc:Description>An object type that exposes Add/Multiply/Concat methods exercising the typed fluent OnCall surface.</opc:Description>
<opc:Children>
<opc:Method SymbolicName="Add" TypeDefinition="AddMethodType" ModellingRule="Mandatory" />
<opc:Method SymbolicName="Multiply" TypeDefinition="MultiplyMethodType" ModellingRule="Mandatory" />
<opc:Method SymbolicName="Concat" TypeDefinition="ConcatMethodType" ModellingRule="Mandatory" />
</opc:Children>
</opc:ObjectType>
<!--
Predefined Calculator instance. The source generator surfaces it on
the typed fluent root as builder.Calculator, with the three method
children reachable via builder.Calculator.Add/.Multiply/.Concat.
-->
<opc:Object SymbolicName="Calculator" TypeDefinition="CalculatorType">
<opc:Description>A calculator exposing Add, Multiply and Concat under the Objects folder.</opc:Description>
<opc:References>
<opc:Reference IsInverse="true">
<opc:ReferenceType>ua:Organizes</opc:ReferenceType>
<opc:TargetId>ua:ObjectsFolder</opc:TargetId>
</opc:Reference>
</opc:References>
</opc:Object>
</opc:ModelDesign>