rename: prefix gateway projects/namespaces with ZB.MOM.WW + sln→slnx

Apply the ZB.MOM.WW. prefix to all gateway-side projects, folders,
.csproj/.sln contents, C# namespaces, using directives, generated proto
C# (csharp_namespace + checked-in generated files), InternalsVisibleTo
attributes, project-name string literals (LoadProject, .sln lookups,
worker exe paths, staticwebassets manifest), and the install/script/doc
references that point at any of the above. Migrate the solution from
.sln to .slnx via `dotnet sln migrate` and delete the old file.

External-runtime identifiers are intentionally NOT prefixed so external
configuration keeps working:
- GatewayMetrics.cs MeterName ("MxGateway.Server")
- DashboardAuthenticationDefaults Scheme/Policy ("MxGateway.Dashboard")
- GatewayRequestLoggingMiddleware logger category ("MxGateway.Request")
- StaRuntime thread name ("MxGateway.Worker.STA")
- appsettings.json root section "MxGateway" + env-var prefix
  MxGateway__... and secret-name MxGateway:ApiKeyPepper
- C:\ProgramData\MxGateway\ data dir paths

Also fixes two tests that were not rename-related but became visible
while validating the rename:

- WorkerLiveMxAccessSmokeTests.ShutDownAsync: cancellation that the
  gateway service correctly maps to RpcException(Cancelled) per gRPC
  convention was being misclassified as a stream fault. Added a sibling
  catch on RpcException with StatusCode.Cancelled.

- IntegrationTestEnvironment.ResolveRepositoryRoot: extracted IsRepositoryRoot
  and made it accept either a .git marker OR a .sln/.slnx next to src/
  so the worker-exe walker works in non-git working copies.

clients/proto/proto-inputs.json's protoRoot updated to point at
src/ZB.MOM.WW.MxGateway.Contracts/Protos.

Verified by `dotnet build` and a full `dotnet test` of the .slnx with
MXGATEWAY_RUN_LIVE_{MXACCESS,LDAP,GALAXY}_TESTS=1:
  Tests: 472/472 pass
  Worker.Tests: 280/280 pass (4 dev-rig [Fact(Skip=...)] skipped)
  IntegrationTests: 18/18 pass

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-05-23 16:22:23 -04:00
parent 867bf18116
commit dc9c0c950c
491 changed files with 32854 additions and 8414 deletions
@@ -0,0 +1,268 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Google.Protobuf.WellKnownTypes;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.MxGateway.Worker.Ipc;
using ZB.MOM.WW.MxGateway.Worker.MxAccess;
using ZB.MOM.WW.MxGateway.Worker.Sta;
namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;
/// <summary>
/// Single configurable <see cref="IWorkerRuntimeSession"/> test double shared by
/// the IPC tests. Replaces the two independent (and previously diverged)
/// <c>FakeRuntimeSession</c> copies in WorkerPipeSessionTests and
/// WorkerPipeClientTests: one supported dispatch blocking and event enqueue, the
/// other did not. This consolidated double supports every configuration both
/// call sites needed, so a minimal caller simply leaves the options unset.
/// </summary>
internal sealed class FakeRuntimeSession : IWorkerRuntimeSession
{
private readonly ManualResetEventSlim releaseDispatch = new(false);
private readonly object gate = new();
private readonly Queue<WorkerEvent> events = new();
private readonly List<string> cancelledCorrelationIds = new();
private WorkerRuntimeHeartbeatSnapshot snapshot = new(
DateTimeOffset.UtcNow,
pendingCommandCount: 0,
outboundEventQueueDepth: 0,
lastEventSequence: 0,
currentCommandCorrelationId: string.Empty);
/// <summary>Gets the event signaled when dispatch begins.</summary>
public ManualResetEventSlim DispatchStarted { get; } = new(false);
/// <summary>Blocks dispatch execution until explicitly released.</summary>
public bool BlockDispatch { get; set; }
/// <summary>Gets or sets whether to throw an exception after dispatch is released.</summary>
public bool ThrowAfterDispatchReleased { get; set; }
/// <summary>Gets or sets whether ShutdownGracefullyAsync throws a TimeoutException.</summary>
public bool ThrowTimeoutOnShutdown { get; set; }
/// <summary>Gets a value indicating whether Dispose was called.</summary>
public bool Disposed { get; private set; }
/// <summary>Starts the worker session with the given session ID and process ID.</summary>
/// <param name="sessionId">The session identifier.</param>
/// <param name="workerProcessId">The worker process ID.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Worker ready response.</returns>
public Task<WorkerReady> StartAsync(
string sessionId,
int workerProcessId,
CancellationToken cancellationToken = default)
{
return Task.FromResult(new WorkerReady
{
WorkerProcessId = workerProcessId,
MxaccessProgid = MxAccessInteropInfo.ProgId,
MxaccessClsid = MxAccessInteropInfo.Clsid,
ReadyTimestamp = Timestamp.FromDateTimeOffset(DateTimeOffset.UtcNow),
});
}
/// <summary>Dispatches a command to the STA thread.</summary>
/// <param name="command">The command to dispatch.</param>
/// <returns>The command reply.</returns>
public Task<MxCommandReply> DispatchAsync(StaCommand command)
{
return Task.Run(
() =>
{
SetSnapshot(new WorkerRuntimeHeartbeatSnapshot(
DateTimeOffset.UtcNow,
pendingCommandCount: 0,
outboundEventQueueDepth: 0,
lastEventSequence: 0,
command.CorrelationId));
DispatchStarted.Set();
if (BlockDispatch)
{
releaseDispatch.Wait(TimeSpan.FromSeconds(5));
}
SetSnapshot(new WorkerRuntimeHeartbeatSnapshot(
DateTimeOffset.UtcNow,
pendingCommandCount: 0,
outboundEventQueueDepth: 0,
lastEventSequence: 0,
currentCommandCorrelationId: string.Empty));
if (ThrowAfterDispatchReleased)
{
throw new InvalidOperationException("Command failed after shutdown started.");
}
return new MxCommandReply
{
SessionId = command.SessionId,
CorrelationId = command.CorrelationId,
Kind = command.Kind,
ProtocolStatus = new ProtocolStatus
{
Code = ProtocolStatusCode.Ok,
Message = "OK",
},
};
});
}
/// <summary>Captures current heartbeat snapshot.</summary>
/// <returns>Current runtime heartbeat snapshot.</returns>
public WorkerRuntimeHeartbeatSnapshot CaptureHeartbeat()
{
lock (gate)
{
return snapshot;
}
}
/// <summary>Drains queued events up to the specified limit.</summary>
/// <param name="maxEvents">Maximum events to drain; 0 drains all.</param>
/// <returns>The drained events.</returns>
public IReadOnlyList<WorkerEvent> DrainEvents(uint maxEvents)
{
lock (gate)
{
int drainCount = maxEvents == 0
? events.Count
: Math.Min(events.Count, checked((int)Math.Min(maxEvents, int.MaxValue)));
List<WorkerEvent> drained = new(drainCount);
for (int index = 0; index < drainCount; index++)
{
drained.Add(events.Dequeue());
}
return drained;
}
}
/// <summary>Drains a pending fault if any.</summary>
/// <returns>Pending fault or null.</returns>
public WorkerFault? DrainFault()
{
return null;
}
/// <summary>
/// Gets a snapshot of every correlation id passed to
/// <see cref="CancelCommand"/>. Recording lets the IPC tests
/// assert that a <c>WorkerCancel</c> envelope dispatched on the
/// gateway side reaches the runtime session — see Worker.Tests-017.
/// </summary>
public IReadOnlyList<string> CancelledCorrelationIds
{
get
{
lock (gate)
{
return new List<string>(cancelledCorrelationIds);
}
}
}
private bool cancelCommandReturnValue;
/// <summary>
/// Optional return value yielded by <see cref="CancelCommand"/>.
/// Defaults to <c>false</c> (the runtime had no matching in-flight
/// command), matching the previous test-double behaviour. Mutated
/// and read under <c>lock(gate)</c> to match the locking convention
/// the rest of this fake uses for <c>cancelledCorrelationIds</c>,
/// <c>snapshot</c>, and <c>events</c> (Worker.Tests-027).
/// </summary>
public bool CancelCommandReturnValue
{
get
{
lock (gate)
{
return cancelCommandReturnValue;
}
}
set
{
lock (gate)
{
cancelCommandReturnValue = value;
}
}
}
/// <summary>Cancels command by correlation ID.</summary>
/// <param name="correlationId">The command correlation ID.</param>
/// <returns>True if cancelled; false otherwise.</returns>
public bool CancelCommand(string correlationId)
{
lock (gate)
{
cancelledCorrelationIds.Add(correlationId);
return cancelCommandReturnValue;
}
}
/// <summary>Requests graceful shutdown.</summary>
public void RequestShutdown()
{
releaseDispatch.Set();
}
/// <summary>Shuts down gracefully within the specified timeout.</summary>
/// <param name="timeout">Shutdown timeout period.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Shutdown result.</returns>
public Task<MxAccessShutdownResult> ShutdownGracefullyAsync(
TimeSpan timeout,
CancellationToken cancellationToken = default)
{
releaseDispatch.Set();
if (ThrowTimeoutOnShutdown)
{
return Task.FromException<MxAccessShutdownResult>(
new TimeoutException("Simulated graceful shutdown timeout."));
}
return Task.FromResult(new MxAccessShutdownResult(Array.Empty<MxAccessShutdownFailure>()));
}
/// <summary>Releases a blocked dispatch.</summary>
public void ReleaseDispatch()
{
releaseDispatch.Set();
}
/// <summary>Sets the current heartbeat snapshot.</summary>
/// <param name="value">The snapshot to set.</param>
public void SetSnapshot(WorkerRuntimeHeartbeatSnapshot value)
{
lock (gate)
{
snapshot = value;
}
}
/// <summary>Enqueues a worker event to be drained.</summary>
/// <param name="workerEvent">The event to enqueue.</param>
public void EnqueueEvent(WorkerEvent workerEvent)
{
lock (gate)
{
events.Enqueue(workerEvent);
}
}
/// <summary>Disposes resources.</summary>
public void Dispose()
{
Disposed = true;
releaseDispatch.Set();
releaseDispatch.Dispose();
DispatchStarted.Dispose();
}
}
@@ -0,0 +1,39 @@
using System;
using ZB.MOM.WW.MxGateway.Contracts;
namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;
/// <summary>
/// Marks an xUnit test as requiring installed MXAccess COM and live
/// provider state. When the opt-in environment variable named by
/// <see cref="GatewayContractInfo.LiveMxAccessOptInVariableName"/> is
/// not set to <c>1</c>, the test is reported as <c>Skipped</c> by
/// xUnit rather than silently returning early (which xUnit would
/// otherwise report as <c>Passed</c>). Mirrors
/// <c>ZB.MOM.WW.MxGateway.IntegrationTests.LiveMxAccessFactAttribute</c>; both
/// copies bind to the same <c>GatewayContractInfo</c> constant so the
/// env-var name has a single literal source of truth (Worker.Tests-025).
/// </summary>
public sealed class LiveMxAccessFactAttribute : FactAttribute
{
/// <summary>
/// The environment variable that opts the suite into running live
/// MXAccess COM tests. Must be set to <c>1</c> on a machine with the
/// installed MXAccess runtime and a reachable Galaxy provider.
/// Sourced from <see cref="GatewayContractInfo.LiveMxAccessOptInVariableName"/>
/// so a single constant gates both Worker.Tests and IntegrationTests.
/// </summary>
public const string LiveMxAccessVariableName = GatewayContractInfo.LiveMxAccessOptInVariableName;
/// <summary>Initializes the attribute, skipping the test unless the env var is set.</summary>
public LiveMxAccessFactAttribute()
{
if (!string.Equals(
Environment.GetEnvironmentVariable(LiveMxAccessVariableName),
"1",
StringComparison.Ordinal))
{
Skip = $"Set {LiveMxAccessVariableName}=1 to run live MXAccess tests.";
}
}
}
@@ -0,0 +1,22 @@
using ZB.MOM.WW.MxGateway.Worker.Sta;
namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;
/// <summary>
/// Shared no-operation <see cref="IStaComApartmentInitializer"/> for tests that
/// construct an <see cref="StaRuntime"/> without a real COM apartment. Replaces
/// the per-file copies that were previously defined independently in
/// StaCommandDispatcherTests, MxAccessStaSessionTests, and MxAccessCommandExecutorTests.
/// </summary>
internal sealed class NoopComApartmentInitializer : IStaComApartmentInitializer
{
/// <inheritdoc />
public void Initialize()
{
}
/// <inheritdoc />
public void Uninitialize()
{
}
}
@@ -0,0 +1,23 @@
using ZB.MOM.WW.MxGateway.Worker.MxAccess;
namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;
/// <summary>
/// Shared no-operation <see cref="IMxAccessEventSink"/> for tests that construct
/// an <see cref="MxAccessStaSession"/> but do not exercise the event sink.
/// Replaces the per-file <c>NoopEventSink</c>/<c>NullEventSink</c> copies that
/// were previously defined independently in MxAccessCommandExecutorTests and
/// AlarmCommandExecutorTests.
/// </summary>
internal sealed class NoopEventSink : IMxAccessEventSink
{
/// <inheritdoc />
public void Attach(object mxAccessComObject, string sessionId)
{
}
/// <inheritdoc />
public void Detach()
{
}
}
@@ -0,0 +1,92 @@
using ZB.MOM.WW.MxGateway.Worker.MxAccess;
namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;
/// <summary>
/// Shared no-operation <see cref="IMxAccessServer"/> for tests that need to
/// construct an <see cref="MxAccessSession"/> via
/// <see cref="MxAccessSession.CreateForTesting"/> but do not exercise any
/// MXAccess COM call. Replaces the per-file <c>NullMxAccessServer</c> copy
/// that previously lived inside <c>AlarmCommandExecutorTests</c> and was
/// constructed via reflection — see Worker.Tests-016 for the rationale.
/// </summary>
internal sealed class NoopMxAccessServer : IMxAccessServer
{
/// <inheritdoc />
public int Register(string clientName) => 0;
/// <inheritdoc />
public void Unregister(int serverHandle)
{
}
/// <inheritdoc />
public int AddItem(int serverHandle, string itemDefinition) => 0;
/// <inheritdoc />
public int AddItem2(int serverHandle, string itemDefinition, string itemContext) => 0;
/// <inheritdoc />
public void RemoveItem(int serverHandle, int itemHandle)
{
}
/// <inheritdoc />
public void Advise(int serverHandle, int itemHandle)
{
}
/// <inheritdoc />
public void UnAdvise(int serverHandle, int itemHandle)
{
}
/// <inheritdoc />
public void AdviseSupervisory(int serverHandle, int itemHandle)
{
}
/// <inheritdoc />
public int AddBufferedItem(int serverHandle, string itemDefinition, string itemContext) => 0;
/// <inheritdoc />
public void SetBufferedUpdateInterval(int serverHandle, int updateIntervalMilliseconds)
{
}
/// <inheritdoc />
public void Suspend(int serverHandle, int itemHandle)
{
}
/// <inheritdoc />
public void Activate(int serverHandle, int itemHandle)
{
}
/// <inheritdoc />
public void Write(int serverHandle, int itemHandle, object? value, int userId)
{
}
/// <inheritdoc />
public void Write2(int serverHandle, int itemHandle, object? value, object? timestampValue, int userId)
{
}
/// <inheritdoc />
public void WriteSecured(int serverHandle, int itemHandle, int currentUserId, int verifierUserId, object? value)
{
}
/// <inheritdoc />
public void WriteSecured2(int serverHandle, int itemHandle, int currentUserId, int verifierUserId, object? value, object? timestampValue)
{
}
/// <inheritdoc />
public int AuthenticateUser(string userName, string password) => 0;
/// <inheritdoc />
public int ArchestrAUserToId(string userName) => 0;
}
@@ -0,0 +1,43 @@
using Google.Protobuf;
namespace ZB.MOM.WW.MxGateway.Worker.Tests.TestSupport;
/// <summary>
/// Shared helpers for building raw length-prefixed worker frames in tests.
/// Replaces the per-file <c>CreateFrame</c>/<c>WriteUInt32LittleEndian</c> copies
/// that were previously defined independently in WorkerFrameProtocolTests and
/// WorkerPipeSessionTests.
/// </summary>
internal static class WorkerFrameTestHelpers
{
/// <summary>Builds a length-prefixed frame from a protobuf message.</summary>
/// <param name="message">Message to serialize into the frame payload.</param>
public static byte[] CreateFrame(IMessage message)
{
return CreateFrame(message.ToByteArray());
}
/// <summary>Builds a length-prefixed frame from a raw payload.</summary>
/// <param name="payload">Payload bytes to wrap in a frame.</param>
public static byte[] CreateFrame(byte[] payload)
{
byte[] frame = new byte[sizeof(uint) + payload.Length];
WriteUInt32LittleEndian(frame, (uint)payload.Length);
payload.CopyTo(frame, sizeof(uint));
return frame;
}
/// <summary>Writes a little-endian unsigned 32-bit integer to the buffer head.</summary>
/// <param name="buffer">Buffer to write into; must have at least four bytes.</param>
/// <param name="value">Value to encode.</param>
public static void WriteUInt32LittleEndian(
byte[] buffer,
uint value)
{
buffer[0] = (byte)value;
buffer[1] = (byte)(value >> 8);
buffer[2] = (byte)(value >> 16);
buffer[3] = (byte)(value >> 24);
}
}