fix(commons): resolve Commons-001..004 — stale-fire race, JsonDocument lifetime, GetNullable strictness, registry symmetry

This commit is contained in:
Joseph Doherty
2026-05-16 20:58:03 -04:00
parent dba1a1b25f
commit 3e7a3d7e31
9 changed files with 501 additions and 37 deletions
@@ -2,21 +2,56 @@ using System.Collections.Frozen;
namespace ScadaLink.Commons.Messages.Management;
/// <summary>
/// Bidirectional name registry for management command records. The registry contains
/// exactly the non-abstract <c>*Command</c> types declared in the
/// <c>ScadaLink.Commons.Messages.Management</c> namespace; these are the commands that
/// travel over the HTTP / ClusterClient management boundary.
/// </summary>
/// <remarks>
/// <see cref="Resolve"/> and <see cref="GetCommandName"/> are symmetric:
/// <c>Resolve(GetCommandName(t))</c> returns <c>t</c> for every type
/// <see cref="GetCommandName"/> accepts. <see cref="GetCommandName"/> rejects any type
/// the registry does not contain rather than computing an unresolvable name.
/// </remarks>
public static class ManagementCommandRegistry
{
private static readonly FrozenDictionary<string, Type> Commands = BuildRegistry();
/// <summary>
/// Names keyed by command type, for the reverse lookup. Keeps
/// <see cref="GetCommandName"/> in lock-step with the forward registry.
/// </summary>
private static readonly FrozenDictionary<Type, string> NamesByType =
Commands.ToFrozenDictionary(kv => kv.Value, kv => kv.Key);
public static Type? Resolve(string commandName)
{
return Commands.GetValueOrDefault(commandName);
}
/// <summary>
/// Returns the registered wire name for a management command type.
/// </summary>
/// <exception cref="ArgumentException">
/// Thrown when <paramref name="commandType"/> is not a registered management
/// command — i.e. not a non-abstract <c>*Command</c> type in the
/// <c>ScadaLink.Commons.Messages.Management</c> namespace. This keeps the method
/// symmetric with <see cref="Resolve"/>: it never yields a name that
/// <see cref="Resolve"/> cannot turn back into the same type.
/// </exception>
public static string GetCommandName(Type commandType)
{
var name = commandType.Name;
return name.EndsWith("Command", StringComparison.Ordinal)
? name[..^"Command".Length]
: name;
ArgumentNullException.ThrowIfNull(commandType);
if (NamesByType.TryGetValue(commandType, out var name))
return name;
throw new ArgumentException(
$"'{commandType.FullName}' is not a registered management command. " +
$"Management commands must be non-abstract '*Command' records declared in " +
$"the '{typeof(ManagementEnvelope).Namespace}' namespace.",
nameof(commandType));
}
private static FrozenDictionary<string, Type> BuildRegistry()