diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs new file mode 100644 index 000000000..21476a2a8 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ImportedConditionMethods.cs @@ -0,0 +1,351 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Microsoft.Extensions.Logging; +using Opc.Ua; +using Opc.Ua.Server; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer; + +/// +/// A3b (plan §5.6 step 2): where an authorized remote condition method goes — the placement the origin resolves (one the +/// caller passed the mapping gate on, primary order first) and that mapping's ConditionMethodTimeoutMilliseconds. +/// +/// The placement to dispatch through. +/// The mapping's method ceiling (default 5 s). +public sealed record ImportedConditionMethodRoute(ImportedConditionPlacement Placement, TimeSpan Timeout); + +/// +/// A3b (plan §5.6 step 4): one remote condition method the consumer's node manager hands to its condition runtime. Never +/// carries the local caller's credentials: the origin sees the connection's service principal; is +/// audit text only. +/// +/// The connection the condition was imported over. +/// The origin's opaque key (diagnostics only; the origin resolves ). +/// The placement to address the origin with. +/// Exactly one method. +/// The marker of the latest applied record (T3). +/// The Part 9 comment, or null. +/// A fresh id per dispatched call (the origin joins duplicates of it, never retried here). +/// min(request deadline, the mapping's method ceiling) minus what was already spent. +/// The local caller's principal, for the origin's audit log. +public sealed record ImportedConditionMethodCall(string ConnectionId, string ConditionKey, ImportedConditionPlacement Placement, + DataConditionMethods Method, DataActivationMarker ExpectedActivation, string? Comment, string OperationId, TimeSpan RemainingBudget, + string? OnBehalfOf); + +/// +/// A3b (plan §5.6): the consumer condition runtime's method port. SDK-free apart from the identity type. +/// +public interface IProjectedConditionMethods +{ + /// + /// The per-caller gate (re-evaluated for every local caller — the stream itself runs under the connection's service + /// principal): the caller's AlarmAcknowledge (Acknowledge, AddComment) or AlarmConfirm (Confirm) grant on + /// the placement's folder scope, on a current, condition-bearing mapping that itself grants the method's bit, with a + /// usable key (#563). Regardless of Security:Acl:Enabled. Null = denied. + /// + ImportedConditionMethodRoute? AuthorizeMethod(RoleCarryingUserIdentity? caller, IReadOnlyList placements, + DataConditionMethods method); + + /// One remote call. Answers, never throws for a remote failure; never retried. + Task CallAsync(ImportedConditionMethodCall call, CancellationToken cancellationToken); +} + +/// +/// A3b (plan §5.6 step 1): the Call service's interception point for imported conditions. The SDK's +/// AsyncNodeManagerAdapter forwards CallAsync to a wrapped manager only when it implements +/// ; otherwise it runs the synchronous Call, which takes Lock per request. +/// +public sealed partial class OtOpcUaNodeManager : ICallAsyncNodeManager +{ + /// Most remote condition methods in flight on this node (§5.6: bounds upstream load, not threads). + internal const int DefaultImportedMethodConcurrency = 8; + + /// How long past the call's own budget the node manager waits for the port before answering BadTimeout. + internal static readonly TimeSpan ImportedMethodGrace = TimeSpan.FromMilliseconds(250); + + private readonly SemaphoreSlim _importedMethodSlots = new(DefaultImportedMethodConcurrency, DefaultImportedMethodConcurrency); + private readonly ConcurrentDictionary> _importedMethodsInFlight = new(StringComparer.Ordinal); + private long _importedMethodsDispatched, _importedMethodsJoined, _importedMethodsRefused; + + /// A3b: the consumer's remote condition method port (null ⇒ every imported method is BadNotSupported). + public IProjectedConditionMethods? ProjectedConditionMethods { get; set; } + + /// Remote condition methods handed to the port (test/diagnostic observation). + internal long ImportedMethodsDispatched => Interlocked.Read(ref _importedMethodsDispatched); + + /// Calls that joined an identical call already in flight instead of dispatching again. + internal long ImportedMethodsJoined => Interlocked.Read(ref _importedMethodsJoined); + + /// Imported-condition calls refused locally (nothing sent). + internal long ImportedMethodsRefused => Interlocked.Read(ref _importedMethodsRefused); + + /// + /// §5.6 step 1: (a) claim every unprocessed request whose ObjectId is in mapped/conditions — a namespace-index + /// test, no lock; (b) the unchanged synchronous base.Call for everything else (it skips claimed requests), run + /// and completed before any remote await; (c) the claimed calls concurrently, bounded by the per-node semaphore. + /// No Lock is held by this method at any point. + /// + public override async ValueTask CallAsync(OperationContext context, ArrayOf methodsToCall, + IList results, IList errors, CancellationToken cancellationToken = default) + { + List? claimed = null; + for (var i = 0; i < methodsToCall.Count; i++) + { + var request = methodsToCall[i]; + if (request is null || request.Processed || !IsImportedConditionId(request.ObjectId)) continue; + request.Processed = true; + (claimed ??= []).Add(i); + } + + base.Call(context, methodsToCall, results, errors); + if (claimed is null) return; + + var caller = context.UserIdentity as RoleCarryingUserIdentity; + var deadline = context.OperationDeadline; + using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, context.CancellationToken); + var calls = new Task[claimed.Count]; + for (var k = 0; k < claimed.Count; k++) + { + results[claimed[k]] = new CallMethodResult(); + calls[k] = CallImportedAsync(caller, methodsToCall[claimed[k]], deadline, linked.Token); + } + var outcomes = await Task.WhenAll(calls).ConfigureAwait(false); + for (var k = 0; k < claimed.Count; k++) errors[claimed[k]] = outcomes[k]; + } + + /// + /// §5.6 steps 2–5 for one claimed request. Every refusal returns before anything is sent; nothing here changes local + /// condition state — the origin applies, reports and streams, and the record's arrival changes the node (§5.3). + /// + private async Task CallImportedAsync(RoleCarryingUserIdentity? caller, CallMethodRequest request, DateTime deadline, + CancellationToken cancellationToken) + { + var started = Stopwatch.GetTimestamp(); + try + { + if (!request.ObjectId.TryGetValue(out string objectIdentifier) + || !ImportedConditionIds.TryParse(objectIdentifier, out var conditionIdentifier, out _, out _, out _) + || _importedConditions.Find(new NodeId(conditionIdentifier, request.ObjectId.NamespaceIndex)) is not { } condition) + return Refuse(StatusCodes.BadNodeIdUnknown); + var method = ImportedMethodOf(request.MethodId, conditionIdentifier); + if (method == DataConditionMethods.None) return Refuse(StatusCodes.BadNotSupported); // shelve, enable/disable, … + if (ProjectedConditionMethods is not { } port) return Refuse(StatusCodes.BadNotSupported); + + // Step 2 local checks (no I/O, no Lock). The mapping gate first: an unauthorized caller learns nothing else. + var placements = condition.Placements; + var route = port.AuthorizeMethod(caller, placements, method); + if (route is null || caller is null) return Refuse(StatusCodes.BadUserAccessDenied); + if (method == DataConditionMethods.Confirm && condition.IsNative) return Refuse(StatusCodes.BadNotSupported); + if (condition.SupportedMethods is { } supported && (supported & (uint)method) == 0) return Refuse(StatusCodes.BadNotSupported); + if (_standby.RefusesMutations) { Interlocked.Increment(ref _importedMethodsRefused); return WarmStandbyState.StandbyRefusal($"call {DataConditionMethodSets.Part9Name(method)}"); } + if (!TryReadMethodArguments(request.InputArguments, out var eventId, out var comment, out var argumentError)) + return Refuse(argumentError); + + // EventId: minted by this consumer for this condition under the SAME marker as the latest applied record (N6/T3). + DataActivationMarker? expected = null; + lock (condition.MethodGate) + { + foreach (var (id, activation) in condition.RecentEvents) + { + if (id != eventId) continue; + if (activation is not null && activation == condition.Activation) expected = activation; + break; + } + } + if (expected is null) return Refuse(StatusCodes.BadEventIdUnknown); + + // An identical call already in flight (same caller, condition, EventId, method, comment) joins it: one dispatch. + var key = string.Join('\n', caller.Principal, condition.Alarm.NodeId.ToString(), Convert.ToHexString(eventId.Span), + ((uint)method).ToString(System.Globalization.CultureInfo.InvariantCulture), comment ?? "\u0001"); + var mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var existing = _importedMethodsInFlight.GetOrAdd(key, mine.Task); + if (!ReferenceEquals(existing, mine.Task)) + { + Interlocked.Increment(ref _importedMethodsJoined); + return await existing.ConfigureAwait(false); + } + try + { + var result = await DispatchImportedAsync(port, condition, route, method, expected, comment, caller, deadline, started, + cancellationToken).ConfigureAwait(false); + mine.TrySetResult(result); + return result; + } + catch (Exception ex) + { + var unknown = new ServiceResult(StatusCodes.BadCommunicationError, new LocalizedText("OutcomeUnknown: " + ex.GetType().Name)); + mine.TrySetResult(unknown); + return unknown; + } + finally + { + _importedMethodsInFlight.TryRemove(new KeyValuePair>(key, mine.Task)); + } + } + catch (Exception ex) when (ex is ArgumentException or FormatException) + { + return Refuse(StatusCodes.BadInvalidArgument); + } + } + + private async Task DispatchImportedAsync(IProjectedConditionMethods port, ImportedCondition condition, + ImportedConditionMethodRoute route, DataConditionMethods method, DataActivationMarker expected, string? comment, + RoleCarryingUserIdentity caller, DateTime deadline, long started, CancellationToken cancellationToken) + { + // Step 4: timeout = min(request deadline, ConditionMethodTimeout). + var budget = route.Timeout; + if (deadline != DateTime.MaxValue && deadline > DateTime.MinValue) + { + var left = deadline - DateTime.UtcNow; + if (left < budget) budget = left; + } + budget -= Stopwatch.GetElapsedTime(started); + if (budget <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout); + + if (!await _importedMethodSlots.WaitAsync(budget, cancellationToken).ConfigureAwait(false)) + return Refuse(StatusCodes.BadTooManyOperations); + try + { + var remaining = budget - Stopwatch.GetElapsedTime(started); + if (remaining <= TimeSpan.Zero) return Refuse(StatusCodes.BadTimeout); + var call = new ImportedConditionMethodCall(condition.ConnectionId, condition.ConditionKey, route.Placement, method, expected, + comment, "a3-" + Guid.NewGuid().ToString("N"), remaining, caller.Principal); + using var bounded = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + bounded.CancelAfter(remaining + ImportedMethodGrace); + Interlocked.Increment(ref _importedMethodsDispatched); + DataConditionMethodResult result; + try + { + result = await port.CallAsync(call, bounded.Token).WaitAsync(remaining + ImportedMethodGrace, CancellationToken.None) + .ConfigureAwait(false); + } + catch (TimeoutException) + { + // The port did not answer inside the budget: it may have reached the origin — OutcomeUnknown, never retried. + return Unknown(StatusCodes.BadTimeout, "OutcomeUnknown: no answer within the condition method timeout."); + } + catch (OperationCanceledException) when (bounded.IsCancellationRequested) + { + return Unknown(cancellationToken.IsCancellationRequested ? StatusCodes.BadCommunicationError : StatusCodes.BadTimeout, + "OutcomeUnknown: the call was cancelled after dispatch."); + } + return MapOutcome(result, Stopwatch.GetElapsedTime(started) >= budget); + } + finally + { + _importedMethodSlots.Release(); + } + } + + /// + /// §5.6 step 5 outcome mapping. Applied (scripted DriverConfirmedSuccess) and accepted (native + /// AcceptedUnconfirmed) ⇒ Good — the confirming record arrives on the stream; RejectedBeforeDispatch ⇒ the + /// origin's status; OutcomeUnknown ⇒ BadTimeout when the budget ran out, else BadCommunicationError + /// — always Bad (the client must not read it as done), with "OutcomeUnknown" in the diagnostic. + /// + internal ServiceResult MapOutcome(DataConditionMethodResult result, bool budgetElapsed) + { + switch (result.State) + { + case DataWriteState.DriverConfirmedSuccess: + case DataWriteState.AcceptedUnconfirmed: + return StatusCode.IsBad(new StatusCode(result.StatusCode)) ? new ServiceResult(new StatusCode(result.StatusCode)) : ServiceResult.Good; + case DataWriteState.RejectedBeforeDispatch: + var refused = new StatusCode(result.StatusCode); + if (!StatusCode.IsBad(refused)) refused = StatusCodes.BadInternalError; + return result.Diagnostic is { Length: > 0 } text ? new ServiceResult(refused, new LocalizedText(text)) : new ServiceResult(refused); + default: + return Unknown(budgetElapsed ? StatusCodes.BadTimeout : StatusCodes.BadCommunicationError, + "OutcomeUnknown: " + (result.Diagnostic ?? "the origin's outcome is unknown.")); + } + } + + private ServiceResult Unknown(StatusCode status, string diagnostic) + { + _logger.LogWarning("OtOpcUaNodeManager: imported condition method outcome unknown ({Status}): {Diagnostic}", status, diagnostic); + return new ServiceResult(status, new LocalizedText(diagnostic)); + } + + private ServiceResult Refuse(StatusCode status) + { + Interlocked.Increment(ref _importedMethodsRefused); + return new ServiceResult(status); + } + + /// The Part 9 method a MethodId names: the type's declaration or this condition's instance child. + private static DataConditionMethods ImportedMethodOf(NodeId methodId, string conditionIdentifier) + { + if (methodId == MethodIds.AcknowledgeableConditionType_Acknowledge) return DataConditionMethods.Acknowledge; + if (methodId == MethodIds.AcknowledgeableConditionType_Confirm) return DataConditionMethods.Confirm; + if (methodId == MethodIds.ConditionType_AddComment) return DataConditionMethods.AddComment; + if (!methodId.TryGetValue(out string identifier) + || !ImportedConditionIds.TryParse(identifier, out var owner, out _, out _, out var path) + || !string.Equals(owner, conditionIdentifier, StringComparison.Ordinal)) return DataConditionMethods.None; + return path switch + { + "Acknowledge" => DataConditionMethods.Acknowledge, + "Confirm" => DataConditionMethods.Confirm, + "AddComment" => DataConditionMethods.AddComment, + _ => DataConditionMethods.None, + }; + } + + /// Acknowledge / Confirm / AddComment all take (EventId ByteString, Comment LocalizedText). + private static bool TryReadMethodArguments(ArrayOf arguments, out ByteString eventId, out string? comment, out StatusCode error) + { + eventId = default; comment = null; error = StatusCodes.Good; + if (arguments.Count < 2) { error = StatusCodes.BadArgumentsMissing; return false; } + if (arguments.Count > 2) { error = StatusCodes.BadTooManyArguments; return false; } + if (!arguments[0].TryGetValue(out eventId) || eventId.IsEmpty) { error = StatusCodes.BadTypeMismatch; return false; } + if (arguments[1].IsNull) return true; + if (!arguments[1].TryGetValue(out LocalizedText text)) { error = StatusCodes.BadTypeMismatch; return false; } + comment = string.IsNullOrEmpty(text.Text) ? null : text.Text; + if (comment is { Length: > DataConditionMethodRequest.MaxCommentLength }) { error = StatusCodes.BadInvalidArgument; return false; } + return true; + } + + /// + /// N6 (§5.6 step 3) after a record that changed no state. A moved marker re-binds the retained EventIds only when the + /// record's time equals the one they were bound under (F6); otherwise a fresh EventId is bound to the new marker + /// (so a ConditionRefresh returns an ackable one) and the caller queues RefreshRequired. A condition with no bound + /// EventId yet (its first record reported nothing) gets one. Under Lock (the apply path). + /// + /// True when retained EventIds were invalidated (RefreshRequired). + private bool RebindImportedEventIds(ImportedCondition condition, DataActivationMarker? previous, DateTimeOffset? previousTime, + DataConditionState state) + { + var current = state.Activation; + lock (condition.MethodGate) + { + if (condition.RecentEvents.Count == 0) + { + MintImportedEventId(condition, current); + return false; + } + if (previous is null || current is null || previous == current) return false; + if (state.TimeUtc is { } time && previousTime == time) + { + var node = condition.RecentEvents.First; + while (node is not null) + { + if (node.Value.Activation == previous) node.Value = (node.Value.EventId, current); + node = node.Next; + } + return false; + } + MintImportedEventId(condition, current); + return true; + } + } + + private static void MintImportedEventId(ImportedCondition condition, DataActivationMarker? activation) + { + if (condition.Alarm.EventId is not { } field) return; + var eventId = ByteString.From(Guid.NewGuid().ToByteArray()); + field.Value = eventId; + condition.RecentEvents.AddFirst((eventId, activation)); + while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index 31236feca..d701e278a 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -23,9 +23,18 @@ internal sealed class ImportedCondition(AlarmConditionState alarm, string connec public HashSet Folders { get; } = new(ReferenceEqualityComparer.Instance); /// The last origin record applied (state known), re-applied with another Quality on staleness. public AlarmConditionSnapshot? Last { get; set; } + /// The marker of the latest applied record. Written under (A3b reads it without Lock). public DataActivationMarker? Activation { get; set; } - /// N6: consumer-minted EventIds of this condition's recent events → the activation marker each described. + /// N6: consumer-minted EventIds of this condition's recent events → the activation marker each described. + /// Mutated and read under . public LinkedList<(ByteString EventId, DataActivationMarker? Activation)> RecentEvents { get; } = new(); + /// A3b (§5.6 step 2): the small EventId registry's own lock — a remote method resolves its EventId and the current + /// marker under it, never under the node manager's Lock. + public object MethodGate { get; } = new(); + /// The origin's supported_methods for the service principal (null until a listing carried it). + public uint? SupportedMethods { get; set; } + /// The time of the latest applied record (N6/F6: re-binding requires it unchanged). + public DateTimeOffset? LastTime { get; set; } /// Bumped on every placement change (verdict caches key on it). public long PlacementVersion { get; set; } /// Native (driver-fed) at the origin: Confirm / shelve / enable have no upstream path. @@ -216,9 +225,9 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink public bool TryResolveImportedEvent(NodeId conditionId, ByteString eventId, out ImportedConditionBinding? binding) { binding = null; - lock (Lock) + if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false; + lock (c.MethodGate) { - if (_importedConditions.Find(conditionId) is not { Placements.Count: > 0 } c) return false; foreach (var (id, activation) in c.RecentEvents) { if (id != eventId) continue; @@ -238,6 +247,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink { ArgumentNullException.ThrowIfNull(updates); EnsureAddressSpaceCreated(); + var refresh = new HashSet(StringComparer.OrdinalIgnoreCase); for (var start = 0; start < updates.Count; start += ImportedApplyChunk) { lock (Lock) @@ -246,7 +256,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink var index = ProjectedFolderIndex(); for (var i = start; i < Math.Min(updates.Count, start + ImportedApplyChunk); i++) { - try { ApplyImported(updates[i], index); } + try { if (ApplyImported(updates[i], index)) refresh.Add(updates[i].ConnectionId); } catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or ServiceResultException) { _logger.LogWarning(ex, "OtOpcUaNodeManager: imported condition update refused (connection {Connection})", @@ -255,6 +265,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink } } } + // N6 (G4 step 3): a resync that left retained EventIds un-re-bindable ⇒ RefreshRequired, outside Lock. + foreach (var connectionId in refresh) RequireRefresh(connectionId); } /// @@ -323,7 +335,8 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink // Materialise / apply / remove (under Lock) // --------------------------------------------------------------------------------------------------------------------- - private void ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders) + /// True when a resync left retained EventIds un-re-bindable (the caller queues RefreshRequired). + private bool ApplyImported(ImportedConditionUpdate update, Dictionary<(string, string), FolderState> folders) { var state = update.State; if (update.Placements.Count == 0) throw new ArgumentException("An imported condition needs a placement.", nameof(update)); @@ -331,7 +344,7 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink if (state.Removed) { if (_importedConditions.Find(id) is { } gone) RemoveImported(gone); - return; + return false; } var condition = _importedConditions.Find(id); @@ -364,9 +377,10 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink UpdatePlacements(condition, update.Placements, folders); if (condition.Alarm.SourceName is { } sourceName) sourceName.Value = update.SourceName; // display only; rides the next event + if ((update.Info ?? state.Info) is { } listed) condition.SupportedMethods = listed.SupportedMethods; // §5.1 T2: a record with state_known = false never changes the consumer's last state. - if (!state.StateKnown) return; + if (!state.StateKnown) return false; var snapshot = new AlarmConditionSnapshot(state.Active, state.Acknowledged, state.Confirmed, state.Enabled, Enum.IsDefined(typeof(AlarmShelvingKind), state.Shelving) ? (AlarmShelvingKind)state.Shelving : AlarmShelvingKind.Unshelved, (ushort)Math.Clamp(state.Severity, 1u, 1000u), state.Message ?? "", state.Quality, @@ -375,9 +389,17 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink var ts = state.TimeUtc?.UtcDateTime ?? UtcNow; if (condition.Alarm.Comment is { } comment && state.Comment is not null) comment.Value = new LocalizedText(state.Comment); if (condition.Alarm.ClientUserId is { } user && state.ClientUserId is not null) user.Value = state.ClientUserId; - condition.Activation = state.Activation; + var previous = condition.Activation; + var previousTime = condition.LastTime; + lock (condition.MethodGate) condition.Activation = state.Activation; condition.Last = snapshot; - if (ApplyConditionState(condition.Alarm, snapshot, ts)) ReportImported(condition, ts); + condition.LastTime = state.TimeUtc; + if (ApplyConditionState(condition.Alarm, snapshot, ts)) + { + ReportImported(condition, ts); + return false; + } + return RebindImportedEventIds(condition, previous, previousTime, state); } /// Reports one imported event (stamping a consumer-minted EventId, N6) through the shared reporter. @@ -387,8 +409,11 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink Interlocked.Increment(ref _importedEventsReported); if (condition.Alarm.EventId?.Value is { } eventId) { - condition.RecentEvents.AddFirst((eventId, condition.Activation)); - while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast(); + lock (condition.MethodGate) + { + condition.RecentEvents.AddFirst((eventId, condition.Activation)); + while (condition.RecentEvents.Count > ProjectedConditionRegistry.RecentEventIds) condition.RecentEvents.RemoveLast(); + } } }