using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Resgrid.Relay.Engine;
using Resgrid.Relay.Engine.Configuration;
using Resgrid.Relay.Engine.Services;
using Serilog;
namespace Resgrid.Audio.Relay.Services
{
///
/// Owns the set of running instances for the desktop app and
/// exposes a button-friendly start/stop lifecycle. Each started mode runs its long-lived
/// on a tracked background task with its own
/// ; stopping cancels, awaits, disposes and removes it.
///
/// All mutations are marshalled onto the WPF UI thread via
/// 's dispatcher so the collection can be bound directly.
///
public sealed class RelayController
{
private readonly ILogger _logger;
private readonly object _gate = new object();
private readonly Dictionary _entries = new Dictionary();
private readonly Dictionary _lastErrors = new Dictionary(StringComparer.OrdinalIgnoreCase);
public RelayController(ILogger logger)
{
_logger = logger ?? Log.Logger;
}
/// The currently running relay services. Bind UI lists against this.
public ObservableCollection RunningServices { get; } = new ObservableCollection();
/// Raised after changes or a service changes state.
public event EventHandler OverallStateChanged;
///
/// Worst-of the running services' states, used to drive the shell traffic-light:
/// Faulted > Starting/Stopping > Running > Stopped. Returns
/// when nothing is running.
///
public RelayServiceState OverallState
{
get
{
lock (_gate)
{
if (_entries.Count == 0)
return RelayServiceState.Stopped;
var states = _entries.Keys.Select(s => s.State).ToList();
if (states.Any(s => s == RelayServiceState.Faulted))
return RelayServiceState.Faulted;
if (states.Any(s => s == RelayServiceState.Starting || s == RelayServiceState.Stopping))
return RelayServiceState.Starting;
if (states.Any(s => s == RelayServiceState.Running))
return RelayServiceState.Running;
return RelayServiceState.Stopped;
}
}
}
/// True when at least one service is being tracked.
public bool IsRunning
{
get
{
lock (_gate)
{
return _entries.Count > 0;
}
}
}
///
/// True when a service for is currently tracked. Reads the
/// authoritative _entries set under _gate — not the UI-marshalled
/// collection — so a just-started mode is seen immediately,
/// independent of when the collection update is dispatched to the UI thread.
///
public bool IsModeRunning(string mode)
{
lock (_gate)
{
foreach (var service in _entries.Keys)
{
if (string.Equals(service.Mode, mode, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
}
///
/// Creates the configured mode via , adds it to the
/// running set and launches its background run loop. Returns the created service.
///
public IRelayService Start(RelayHostOptions options)
{
if (options == null)
throw new ArgumentNullException(nameof(options));
var service = RelayServiceFactory.Create(options, _logger);
lock (_gate)
{
_lastErrors.Remove(service.Mode);
}
var cts = new CancellationTokenSource();
var entry = new RunningEntry(service, cts);
service.StateChanged += OnServiceStateChanged;
// Fully initialise the entry (including RunTask) BEFORE publishing it to _entries, so a
// concurrent StopAsync/StopAllAsync never observes a partially-built entry (RunTask == null).
entry.RunTask = Task.Run(async () =>
{
try
{
await service.StartAsync(cts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
// Normal on Stop.
}
catch (Exception ex)
{
_logger?.Error(ex, "Relay mode '{Mode}' terminated unexpectedly.", service.Mode);
}
});
lock (_gate)
{
_entries[service] = entry;
}
Post(() => RunningServices.Add(service));
RaiseOverallStateChanged();
return service;
}
/// Stops, disposes and removes a single running service.
public async Task StopAsync(IRelayService service)
{
if (service == null)
return;
RunningEntry entry;
lock (_gate)
{
if (!_entries.TryGetValue(service, out entry))
return;
_entries.Remove(service);
}
service.StateChanged -= OnServiceStateChanged;
try
{
entry.Cts.Cancel();
try { await service.StopAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger?.Warning(ex, "Error stopping relay mode '{Mode}'.", service.Mode); }
if (entry.RunTask != null)
{
try { await entry.RunTask.ConfigureAwait(false); }
catch { /* already logged in run loop */ }
}
}
finally
{
try { await service.DisposeAsync().ConfigureAwait(false); }
catch (Exception ex) { _logger?.Warning(ex, "Error disposing relay mode '{Mode}'.", service.Mode); }
entry.Cts.Dispose();
Post(() => RunningServices.Remove(service));
RaiseOverallStateChanged();
}
}
/// Stops every running service. Safe to call on shutdown.
public async Task StopAllAsync()
{
IRelayService[] running;
lock (_gate)
{
running = _entries.Keys.ToArray();
}
foreach (var service in running)
await StopAsync(service).ConfigureAwait(false);
}
/// The fault message from the last time faulted, or null.
public string GetLastError(string mode)
{
if (string.IsNullOrEmpty(mode))
return null;
lock (_gate)
{
return _lastErrors.TryGetValue(mode, out var error) ? error : null;
}
}
/// Raised (on the UI thread) when a running service faults, with its mode and fault message.
public event EventHandler ServiceFaulted;
private void OnServiceStateChanged(object sender, RelayStateChangedEventArgs e)
{
if (e.NewState == RelayServiceState.Faulted && sender is IRelayService service)
{
var message = string.IsNullOrWhiteSpace(e.Error) ? "The service faulted." : e.Error;
lock (_gate)
{
_lastErrors[service.Mode] = message;
}
Post(() => ServiceFaulted?.Invoke(this, new RelayFaultEventArgs(service.Mode, message)));
}
RaiseOverallStateChanged();
}
private void RaiseOverallStateChanged()
{
Post(() => OverallStateChanged?.Invoke(this, EventArgs.Empty));
}
private void Post(Action action)
{
// Resolve the UI dispatcher at call time (not construction) so updates always land on the
// WPF UI thread even if no SynchronizationContext was current when the controller was built.
var dispatcher = Application.Current?.Dispatcher;
if (dispatcher == null || dispatcher.CheckAccess())
action();
else
dispatcher.BeginInvoke(action);
}
/// The current tracked service for , or null.
public IRelayService Find(string mode)
{
lock (_gate)
{
return _entries.Keys.FirstOrDefault(s => string.Equals(s.Mode, mode, StringComparison.OrdinalIgnoreCase));
}
}
/// When the tracked service for was started (UTC), or null.
public DateTime? StartedAtUtc(string mode)
{
lock (_gate)
{
foreach (var pair in _entries)
{
if (string.Equals(pair.Key.Mode, mode, StringComparison.OrdinalIgnoreCase))
return pair.Value.StartedAtUtc;
}
return null;
}
}
private sealed class RunningEntry
{
public RunningEntry(IRelayService service, CancellationTokenSource cts)
{
Service = service;
Cts = cts;
}
public IRelayService Service { get; }
public CancellationTokenSource Cts { get; }
public Task RunTask { get; set; }
public DateTime StartedAtUtc { get; } = DateTime.UtcNow;
}
}
/// A relay mode fault, raised by .
public sealed class RelayFaultEventArgs : EventArgs
{
public RelayFaultEventArgs(string mode, string error)
{
Mode = mode;
Error = error;
}
public string Mode { get; }
public string Error { get; }
}
}