diff --git a/docs/MxAccessWorkerInstanceDesign.md b/docs/MxAccessWorkerInstanceDesign.md index 3f7f836d..c3e866c8 100644 --- a/docs/MxAccessWorkerInstanceDesign.md +++ b/docs/MxAccessWorkerInstanceDesign.md @@ -228,7 +228,10 @@ Shutdown: 1. Mark the command queue as completing. 2. Drain or reject pending commands according to shutdown mode. -3. Optionally issue MXAccess cleanup calls for active handles. +3. Issue MXAccess cleanup: `Unregister` every tracked server handle first (MXAccess removes + its items and advise subscriptions with it). Only for a server whose `Unregister` failed, + fall back to `UnAdvise` then `RemoveItem` over its remaining handles. Each step is + guarded (a failure is recorded, never skips the rest) and logged at Debug (R21-K10, #175). 4. Detach event handlers. 5. Release COM references. 6. Uninitialize COM. diff --git a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessCommandExecutorTests.cs b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessCommandExecutorTests.cs index e8725a66..5ee79648 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessCommandExecutorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker.Tests/MxAccess/MxAccessCommandExecutorTests.cs @@ -822,10 +822,10 @@ public sealed class MxAccessCommandExecutorTests fakeComObject.OperationNames); } - /// Verifies that ShutdownGracefullyAsync cleans up handles in advice, item, server order. + /// Verifies that ShutdownGracefullyAsync unregisters first and skips the redundant per-item calls (R21-K10). /// A task that represents the asynchronous operation. [Fact] - public async Task ShutdownGracefullyAsync_CleansHandlesInAdviceItemServerOrder() + public async Task ShutdownGracefullyAsync_UnregistersFirstAndSkipsPerItemCleanup() { FakeMxAccessComObject fakeComObject = new( registerHandle: 58, @@ -843,11 +843,58 @@ public sealed class MxAccessCommandExecutorTests Assert.True(result.Succeeded); Assert.Equal( - new[] { "UnAdvise:58:510", "RemoveItem:58:510", "Unregister:58" }, + new[] { "Unregister:58" }, fakeComObject.OperationNames.Where(name => name.StartsWith("Un", StringComparison.Ordinal) || name.StartsWith("Remove", StringComparison.Ordinal))); } + /// Verifies that a failed Unregister falls back to UnAdvise then RemoveItem, in that order after Unregister. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ShutdownGracefullyAsync_UnregisterFailure_FallsBackToUnAdviseThenRemoveItem() + { + FakeMxAccessComObject fakeComObject = new( + registerHandle: 62, + addItemHandle: 514, + unregisterException: new COMException("Invalid handle.", unchecked((int)0x80070057))); + FakeMxAccessComObjectFactory factory = new(fakeComObject); + using StaRuntime runtime = CreateRuntime(); + using MxAccessStaSession session = new(runtime, factory, new NoopEventSink()); + await session.StartAsync(workerProcessId: 1234); + await session.DispatchAsync(CreateRegisterCommand("register-fallback", "client-a")); + await session.DispatchAsync(CreateAddItemCommand("add-fallback", 62, "Galaxy.Tag.Value")); + await session.DispatchAsync(CreateAdviseCommand("advise-fallback", 62, 514)); + + MxAccessShutdownResult result = await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2)); + + Assert.Equal(new[] { "Unregister" }, result.Failures.Select(failure => failure.Operation)); + Assert.Equal( + new[] { "Unregister:62", "UnAdvise:62:514", "RemoveItem:62:514" }, + fakeComObject.OperationNames.Where(name => name.StartsWith("Un", StringComparison.Ordinal) + || name.StartsWith("Remove", StringComparison.Ordinal))); + } + + /// Verifies that a second ShutdownGracefullyAsync is a no-op and issues no further COM calls. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ShutdownGracefullyAsync_CalledTwice_IsIdempotent() + { + FakeMxAccessComObject fakeComObject = new(registerHandle: 63, addItemHandle: 515); + FakeMxAccessComObjectFactory factory = new(fakeComObject); + using StaRuntime runtime = CreateRuntime(); + using MxAccessStaSession session = new(runtime, factory, new NoopEventSink()); + await session.StartAsync(workerProcessId: 1234); + await session.DispatchAsync(CreateRegisterCommand("register-twice", "client-a")); + + await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2)); + int callsAfterFirst = fakeComObject.OperationNames.Count(); + MxAccessShutdownResult second = await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2)); + + Assert.True(second.Succeeded); + Assert.Equal(callsAfterFirst, fakeComObject.OperationNames.Count()); + Assert.Single(fakeComObject.OperationNames, name => name == "Unregister:63"); + } + /// Verifies that ShutdownGracefullyAsync records cleanup failures and continues. /// A task that represents the asynchronous operation. [Fact] @@ -872,7 +919,7 @@ public sealed class MxAccessCommandExecutorTests MxAccessShutdownResult result = await session.ShutdownGracefullyAsync(TimeSpan.FromSeconds(2)); Assert.False(result.Succeeded); - Assert.Equal(new[] { "UnAdvise", "RemoveItem", "Unregister" }, result.Failures.Select(failure => failure.Operation)); + Assert.Equal(new[] { "Unregister", "UnAdvise", "RemoveItem" }, result.Failures.Select(failure => failure.Operation)); Assert.All(result.Failures, failure => Assert.Equal(hresult, failure.HResult)); Assert.Contains("Unregister:59", fakeComObject.OperationNames); } diff --git a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs index 860f4ade..31576d8c 100644 --- a/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs +++ b/src/ZB.MOM.WW.MxGateway.Worker/MxAccess/MxAccessSession.cs @@ -1304,7 +1304,20 @@ public sealed class MxAccessSession : IDisposable }; } - /// Gracefully shuts down the session, cleaning up all handles. + /// + /// Optional sink for per-step shutdown diagnostics (Debug level). Defaults to + /// . Tests substitute a collector. + /// + internal Action? ShutdownStepSink { get; set; } + + /// + /// Gracefully shuts down the session. Unregister runs first (R21-K10): MXAccess + /// removes a server's items and advise subscriptions with it, so a successful + /// Unregister makes the per-item UnAdvise/RemoveItem calls redundant for that server. + /// Only for a server whose Unregister FAILED does the fallback UnAdvise then + /// RemoveItem sweep run over its remaining handles. Every step is guarded so one + /// failure never skips the rest; calling it again after completion is a no-op. + /// /// The shutdown result, including any per-handle cleanup failures. public MxAccessShutdownResult ShutdownGracefully() { @@ -1315,14 +1328,37 @@ public sealed class MxAccessSession : IDisposable List failures = new(); - CleanupAdviceHandles(failures); - CleanupItemHandles(failures); - CleanupServerHandles(failures); + HashSet unregisteredFailed = CleanupServerHandles(failures); + if (unregisteredFailed.Count > 0) + { + CleanupAdviceHandles(failures, unregisteredFailed); + CleanupItemHandles(failures, unregisteredFailed); + } + DisposeCore(failures); return new MxAccessShutdownResult(failures); } + private void LogShutdownStep(string message) + { + try + { + if (ShutdownStepSink is { } sink) + { + sink(message); + } + else + { + System.Diagnostics.Debug.WriteLine("MxAccessSession shutdown: " + message); + } + } + catch + { + // Diagnostics must never break cleanup. + } + } + /// public void Dispose() { @@ -1334,11 +1370,18 @@ public sealed class MxAccessSession : IDisposable DisposeCore(failures: null); } - private void CleanupAdviceHandles(ICollection failures) + private void CleanupAdviceHandles( + ICollection failures, + HashSet serverHandles) { HashSet cleanedPairs = new(); foreach (RegisteredAdviceHandle adviceHandle in handleRegistry.AdviceHandles) { + if (!serverHandles.Contains(adviceHandle.ServerHandle)) + { + continue; + } + long key = CreateItemKey(adviceHandle.ServerHandle, adviceHandle.ItemHandle); if (!cleanedPairs.Add(key)) { @@ -1349,9 +1392,11 @@ public sealed class MxAccessSession : IDisposable { mxAccessServer.UnAdvise(adviceHandle.ServerHandle, adviceHandle.ItemHandle); handleRegistry.RemoveAdviceHandles(adviceHandle.ServerHandle, adviceHandle.ItemHandle); + LogShutdownStep($"UnAdvise server={adviceHandle.ServerHandle} item={adviceHandle.ItemHandle} ok (fallback)"); } catch (Exception exception) { + LogShutdownStep($"UnAdvise server={adviceHandle.ServerHandle} item={adviceHandle.ItemHandle} failed: {exception.GetType().Name}"); failures.Add(new MxAccessShutdownFailure( nameof(UnAdvise), adviceHandle.ServerHandle, @@ -1361,17 +1406,26 @@ public sealed class MxAccessSession : IDisposable } } - private void CleanupItemHandles(ICollection failures) + private void CleanupItemHandles( + ICollection failures, + HashSet serverHandles) { foreach (RegisteredItemHandle itemHandle in handleRegistry.ItemHandles) { + if (!serverHandles.Contains(itemHandle.ServerHandle)) + { + continue; + } + try { mxAccessServer.RemoveItem(itemHandle.ServerHandle, itemHandle.ItemHandle); handleRegistry.RemoveItemHandle(itemHandle.ServerHandle, itemHandle.ItemHandle); + LogShutdownStep($"RemoveItem server={itemHandle.ServerHandle} item={itemHandle.ItemHandle} ok (fallback)"); } catch (Exception exception) { + LogShutdownStep($"RemoveItem server={itemHandle.ServerHandle} item={itemHandle.ItemHandle} failed: {exception.GetType().Name}"); failures.Add(new MxAccessShutdownFailure( nameof(RemoveItem), itemHandle.ServerHandle, @@ -1381,17 +1435,22 @@ public sealed class MxAccessSession : IDisposable } } - private void CleanupServerHandles(ICollection failures) + /// Unregisters every tracked server first; returns the handles whose Unregister failed. + private HashSet CleanupServerHandles(ICollection failures) { + HashSet failed = new(); foreach (RegisteredServerHandle serverHandle in handleRegistry.ServerHandles) { try { mxAccessServer.Unregister(serverHandle.ServerHandle); handleRegistry.UnregisterServerHandle(serverHandle.ServerHandle); + LogShutdownStep($"Unregister server={serverHandle.ServerHandle} ok"); } catch (Exception exception) { + failed.Add(serverHandle.ServerHandle); + LogShutdownStep($"Unregister server={serverHandle.ServerHandle} failed: {exception.GetType().Name}"); failures.Add(new MxAccessShutdownFailure( nameof(Unregister), serverHandle.ServerHandle, @@ -1399,6 +1458,8 @@ public sealed class MxAccessSession : IDisposable exception)); } } + + return failed; } private static long CreateItemKey( @@ -1461,6 +1522,7 @@ public sealed class MxAccessSession : IDisposable try { eventSink.Detach(); + LogShutdownStep("DetachEvents ok"); } catch (Exception exception) { @@ -1477,6 +1539,7 @@ public sealed class MxAccessSession : IDisposable if (Marshal.IsComObject(mxAccessComObject)) { Marshal.FinalReleaseComObject(mxAccessComObject); + LogShutdownStep("ReleaseComObject ok"); } } catch (Exception exception) when (failures is not null)