138 lines
5.7 KiB
C#
138 lines
5.7 KiB
C#
#nullable enable
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using Cysharp.Threading.Tasks;
|
|
|
|
namespace ShrinkApp;
|
|
|
|
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
|
|
public sealed class ShrinkAppModuleInstallerAttribute : Attribute { }
|
|
|
|
public interface IShrinkAppModuleInstaller
|
|
{
|
|
string ModuleId { get; }
|
|
int Order { get; }
|
|
IReadOnlyList<string> DependsOn { get; }
|
|
void RegisterServices(ShrinkAppContext context);
|
|
UniTask InitializeAsync(ShrinkAppContext context);
|
|
}
|
|
|
|
public interface IShrinkAppModuleShutdown
|
|
{
|
|
UniTask ShutdownAsync(ShrinkAppContext context);
|
|
}
|
|
|
|
public sealed class ShrinkAppSettings
|
|
{
|
|
public bool VerboseLogging { get; set; }
|
|
public string[] DisabledModuleIds { get; set; } = Array.Empty<string>();
|
|
}
|
|
|
|
public sealed class ShrinkAppServices
|
|
{
|
|
private readonly Dictionary<Type, object> _services = new();
|
|
public void Register<T>(T service) where T : class => _services[typeof(T)] = service ?? throw new ArgumentNullException(nameof(service));
|
|
public bool TryGet<T>(out T? service) where T : class
|
|
{
|
|
service = _services.TryGetValue(typeof(T), out var value) ? value as T : null;
|
|
return service != null;
|
|
}
|
|
public T GetRequired<T>() where T : class => TryGet<T>(out var value) ? value! : throw new InvalidOperationException($"Required service is not registered: {typeof(T).FullName}");
|
|
public bool TryUnregister<T>(T service) where T : class => _services.TryGetValue(typeof(T), out var value) && ReferenceEquals(value, service) && _services.Remove(typeof(T));
|
|
}
|
|
|
|
public sealed class ShrinkAppContext
|
|
{
|
|
public ShrinkAppContext(object? host, ShrinkAppSettings settings, ShrinkAppServices services)
|
|
{
|
|
Host = host;
|
|
Settings = settings ?? throw new ArgumentNullException(nameof(settings));
|
|
Services = services ?? throw new ArgumentNullException(nameof(services));
|
|
}
|
|
public object? Host { get; }
|
|
public ShrinkAppSettings Settings { get; }
|
|
public ShrinkAppServices Services { get; }
|
|
public static ShrinkAppContext CreateStandalone(ShrinkAppServices services, ShrinkAppSettings? settings = null) => new(null, settings ?? new ShrinkAppSettings(), services);
|
|
}
|
|
|
|
public sealed class ShrinkAppRuntime
|
|
{
|
|
private readonly List<IShrinkAppModuleInstaller> _started = new();
|
|
public ShrinkAppRuntime(object? host = null, ShrinkAppSettings? settings = null, ShrinkAppServices? services = null)
|
|
{
|
|
Context = new ShrinkAppContext(host, settings ?? new ShrinkAppSettings(), services ?? new ShrinkAppServices());
|
|
}
|
|
public ShrinkAppContext Context { get; }
|
|
public bool IsRunning { get; private set; }
|
|
public IReadOnlyList<string> StartedModules => _started.Select(item => item.ModuleId).ToArray();
|
|
|
|
public async UniTask StartAsync()
|
|
{
|
|
if (IsRunning) return;
|
|
var installers = Sort(CreateInstallers(), Context.Settings.DisabledModuleIds);
|
|
try
|
|
{
|
|
foreach (var installer in installers) installer.RegisterServices(Context);
|
|
foreach (var installer in installers)
|
|
{
|
|
await installer.InitializeAsync(Context);
|
|
_started.Add(installer);
|
|
}
|
|
IsRunning = true;
|
|
}
|
|
catch
|
|
{
|
|
await ShutdownStartedAsync();
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public async UniTask ShutdownAsync()
|
|
{
|
|
await ShutdownStartedAsync();
|
|
IsRunning = false;
|
|
}
|
|
|
|
private async UniTask ShutdownStartedAsync()
|
|
{
|
|
for (var index = _started.Count - 1; index >= 0; index--)
|
|
if (_started[index] is IShrinkAppModuleShutdown shutdown) await shutdown.ShutdownAsync(Context);
|
|
_started.Clear();
|
|
}
|
|
|
|
private static IReadOnlyList<IShrinkAppModuleInstaller> CreateInstallers() =>
|
|
ShrinkAppInstallers.GetDiscoveredInstallerTypes().Select(type =>
|
|
Activator.CreateInstance(type) as IShrinkAppModuleInstaller ?? throw new InvalidOperationException($"Failed to create installer: {type.FullName}"))
|
|
.ToArray();
|
|
|
|
private static IReadOnlyList<IShrinkAppModuleInstaller> Sort(IEnumerable<IShrinkAppModuleInstaller> source, IEnumerable<string> disabledIds)
|
|
{
|
|
var disabled = new HashSet<string>(disabledIds ?? Array.Empty<string>(), StringComparer.OrdinalIgnoreCase);
|
|
var byId = source.Where(item => !disabled.Contains(item.ModuleId)).ToDictionary(item => item.ModuleId, StringComparer.OrdinalIgnoreCase);
|
|
var states = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
|
|
var result = new List<IShrinkAppModuleInstaller>();
|
|
foreach (var installer in byId.Values.OrderBy(item => item.Order).ThenBy(item => item.ModuleId, StringComparer.OrdinalIgnoreCase))
|
|
Visit(installer, byId, states, result);
|
|
return result;
|
|
}
|
|
|
|
private static void Visit(IShrinkAppModuleInstaller installer, IReadOnlyDictionary<string, IShrinkAppModuleInstaller> byId,
|
|
IDictionary<string, int> states, ICollection<IShrinkAppModuleInstaller> result)
|
|
{
|
|
var state = states.TryGetValue(installer.ModuleId, out var value) ? value : 0;
|
|
if (state == 2) return;
|
|
if (state == 1) throw new InvalidOperationException($"Circular installer dependency: {installer.ModuleId}");
|
|
states[installer.ModuleId] = 1;
|
|
foreach (var dependencyId in installer.DependsOn ?? Array.Empty<string>())
|
|
{
|
|
if (!byId.TryGetValue(dependencyId, out var dependency))
|
|
throw new InvalidOperationException($"Installer dependency missing. Module={installer.ModuleId}, DependsOn={dependencyId}");
|
|
Visit(dependency, byId, states, result);
|
|
}
|
|
states[installer.ModuleId] = 2;
|
|
result.Add(installer);
|
|
}
|
|
}
|