acdream/src/AcDream.UI.Abstractions/LiveCommandBus.cs

71 lines
2.7 KiB
C#

using System;
using System.Collections.Generic;
namespace AcDream.UI.Abstractions;
/// <summary>
/// Real <see cref="ICommandBus"/> implementation — single-handler-per-type
/// dispatch keyed by <c>typeof(T)</c>. Replaces <see cref="NullCommandBus"/>
/// in live sessions; <see cref="NullCommandBus"/> persists for tests and
/// non-live UI scenarios where no command flow is wanted.
///
/// <para>
/// <b>Threading.</b> Both <see cref="Register{T}"/> and <see cref="Publish{T}"/>
/// run on the render thread today (panels render on the render thread, and
/// host wiring happens at startup). The internal handler dictionary is
/// not synchronized — register all handlers during host setup before the
/// panel host starts rendering.
/// </para>
///
/// <para>
/// Phase I.3 of the chat/UI consolidation plan
/// (<c>~/.claude/plans/ticklish-conjuring-cake.md</c>): primary client of
/// the bus is the <see cref="SendChatCmd"/> handler wired by GameWindow
/// against <c>WorldSession.SendTalk/SendTell/SendChannel</c> + the local
/// <c>ChatLog</c> echo.
/// </para>
/// </summary>
public sealed class LiveCommandBus : ICommandBus
{
private readonly Dictionary<Type, Delegate> _handlers = new();
/// <summary>
/// Register a single handler for commands of type <typeparamref name="T"/>.
/// Throws <see cref="InvalidOperationException"/> if a handler is already
/// registered for this type — single-handler-per-type is intentional so
/// command routing is unambiguous.
/// </summary>
public void Register<T>(Action<T> handler) where T : notnull
{
ArgumentNullException.ThrowIfNull(handler);
if (_handlers.ContainsKey(typeof(T)))
throw new InvalidOperationException(
$"A handler for command type {typeof(T).FullName} is already registered.");
_handlers[typeof(T)] = handler;
}
/// <inheritdoc />
public void Publish<T>(T command) where T : notnull
{
ArgumentNullException.ThrowIfNull(command);
if (_handlers.TryGetValue(typeof(T), out var handler))
{
((Action<T>)handler).Invoke(command);
}
else
{
// Soft-warn: command published with no registered handler.
// Don't throw — the host may publish optional commands a non-
// live build doesn't wire (e.g. inventory pre-Phase I.7).
Console.WriteLine(
$"[LiveCommandBus] no handler registered for {typeof(T).FullName}; dropping.");
}
}
/// <summary>
/// Release every registered handler. Session-scoped owners call this
/// during teardown so a retained bus cannot keep an obsolete transport or
/// host object graph alive.
/// </summary>
public void Clear() => _handlers.Clear();
}