// // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ // █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ // ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ // │ Copyright (c) JP Dillingham. // │ // │ This program is free software: you can redistribute it and/or modify // │ it under the terms of the GNU Affero General Public License as published // │ by the Free Software Foundation, version 3. // │ // │ This program is distributed in the hope that it will be useful, // │ but WITHOUT ANY WARRANTY; without even the implied warranty of // │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // │ GNU Affero General Public License for more details. // │ // │ You should have received a copy of the GNU Affero General Public License // │ along with this program. If not, see https://www.gnu.org/licenses/. // │ // │ This program is distributed with Additional Terms pursuant to Section 7 // │ of the AGPLv3. See the LICENSE file in the root directory of this // │ project for the complete terms and conditions. // │ // │ https://slskd.org // │ // ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ // │ SPDX-FileCopyrightText: JP Dillingham // │ SPDX-License-Identifier: AGPL-3.0-only // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // namespace slskd { using System; using System.Text.Json; using Microsoft.Extensions.DependencyInjection; /// /// Provides observable read access for state objects. /// /// The type of the tracked state object. public interface IStateMonitor { /// /// Gets the current state. /// T CurrentValue { get; } /// /// Registers a listener to be called whenever the tracked state changes. /// /// Registers a listener to be called whenever state changes. /// An which should be disposed to stop listening for changes. IDisposable OnChange(Action<(T Previous, T Current)> listener); } /// /// Provides write access for state objects. /// /// The type of the tracked state object. public interface IStateMutator { /// /// Replaces the current state with the value resolved by the . /// /// Given the current state, resolves a new state value. /// The updated state. T SetValue(Func setter); } /// /// Provides point-in-time read access for state objects. /// /// The type of the tracked state object. public interface IStateSnapshot { /// /// Gets the snapshotted state. /// T Value { get; } } /// /// Provides observable management of state objects. /// /// The type of the tracked state object. public interface IManagedState : IStateMonitor, IStateMutator { /// /// Gets a point-in-time snapshot of the current state. /// IStateSnapshot Snapshot { get; } } /// /// ManagedState extension methods. /// public static class ManagedStateExtensions { /// /// /// Adds managed state of an object of the specified to the specified . /// /// /// /// A singleton instance of to be used by instances requiring full control over the state /// A singleton instance of to be used by instances requiring the ability to mutate the state /// A singleton instance of to be used by instances requiring observable read access to the state /// A transient instance of to be used by scoped or transient instances requiring the current state /// /// /// /// The type of the managed state object. /// The IServiceCollection to which the managed state is to be added. /// An optional anonymous function used to apply an initial state mutation. /// The IServiceCollection with managed state added. public static IServiceCollection AddManagedState(this IServiceCollection services, Func setter = null) where T : class { services.AddSingleton, ManagedState>(); services.AddSingleton(services => { var monitor = (IStateMutator)services.GetRequiredService>(); if (setter != null) { monitor.SetValue(setter); } return monitor; }); services.AddSingleton(services => (IStateMonitor)services.GetRequiredService>()); services.AddTransient(services => services.GetRequiredService>().Snapshot); return services; } } /// /// Provides a point-in-time snapshot of state objects. /// /// The type of the tracked state object. public class StateSnapshot : IStateSnapshot { /// /// Initializes a new instance of the class. /// /// The current value of the state. public StateSnapshot(T value) { Value = value.ToJson().FromJson(); } /// /// Gets a snapshot of the current application state. /// public T Value { get; } } /// /// Provides observable management of state objects. /// /// The type of the tracked state object. public class ManagedState : IManagedState { private event Action<(T, T)> Changed; /// /// Gets the current application state. /// public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T)); /// /// Gets a point-in-time snapshot of the current state. /// public IStateSnapshot Snapshot => new StateSnapshot(CurrentValue); private object Lock { get; } = new object(); /// /// Registers a listener to be called whenever the tracked state changes. /// /// Registers a listener to be called whenever state changes. /// An which should be disposed to stop listening for changes. public IDisposable OnChange(Action<(T Previous, T Current)> listener) { var disposable = new ManagedStateDisposable(this, listener); Changed += disposable.OnChange; return disposable; } /// /// Replaces the current state with the value resolved by the . /// /// Given the current state, resolves a new state value. /// The updated state. public T SetValue(Func setter) { lock (Lock) { var previous = CurrentValue.ToJson().FromJson(); CurrentValue = setter(CurrentValue); Changed?.Invoke((previous, CurrentValue)); return CurrentValue; } } #pragma warning disable CS0693 // Type parameter has the same name as the type parameter from outer type #pragma warning disable S3260 // Non-derived "private" classes and records should be "sealed" private class ManagedStateDisposable : IDisposable #pragma warning restore S3260 // Non-derived "private" classes and records should be "sealed" #pragma warning restore CS0693 // Type parameter has the same name as the type parameter from outer type { public ManagedStateDisposable(ManagedState stateMonitor, Action<(T Previous, T Current)> listener) { StateMonitor = stateMonitor; Listener = listener; } private bool Disposed { get; set; } private Action<(T Previous, T Current)> Listener { get; } private ManagedState StateMonitor { get; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } public void OnChange((T Previous, T Current) args) => Listener.Invoke(args); protected virtual void Dispose(bool disposing) { if (!Disposed) { if (disposing) { StateMonitor.Changed -= OnChange; } Disposed = true; } } } } }