#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 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(); } public sealed class ShrinkAppServices { private readonly Dictionary _services = new(); public void Register(T service) where T : class => _services[typeof(T)] = service ?? throw new ArgumentNullException(nameof(service)); public bool TryGet(out T? service) where T : class { service = _services.TryGetValue(typeof(T), out var value) ? value as T : null; return service != null; } public T GetRequired() where T : class => TryGet(out var value) ? value! : throw new InvalidOperationException($"Required service is not registered: {typeof(T).FullName}"); public bool TryUnregister(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 _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 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 CreateInstallers() => ShrinkAppInstallers.GetDiscoveredInstallerTypes().Select(type => Activator.CreateInstance(type) as IShrinkAppModuleInstaller ?? throw new InvalidOperationException($"Failed to create installer: {type.FullName}")) .ToArray(); private static IReadOnlyList Sort(IEnumerable source, IEnumerable disabledIds) { var disabled = new HashSet(disabledIds ?? Array.Empty(), StringComparer.OrdinalIgnoreCase); var byId = source.Where(item => !disabled.Contains(item.ModuleId)).ToDictionary(item => item.ModuleId, StringComparer.OrdinalIgnoreCase); var states = new Dictionary(StringComparer.OrdinalIgnoreCase); var result = new List(); 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 byId, IDictionary states, ICollection 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()) { 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); } }