aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Common/ManagedState.cs
blob: fa9653ef9d2f2fcb247303cab35d97326392a1d4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// <copyright file="ManagedState.cs" company="JP Dillingham">
//           ▄▄▄▄     ▄▄▄▄     ▄▄▄▄
//     ▄▄▄▄▄▄█  █▄▄▄▄▄█  █▄▄▄▄▄█  █
//     █__ --█  █__ --█    ◄█  -  █
//     █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█
//   ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━  ━┉   ┉     ┉
//   │ 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
//   ╰───────────────────────────────────────────╶──── ─ ─── ─  ── ──┈  ┈
// </copyright>

namespace slskd
{
    using System;
    using System.Text.Json;
    using Microsoft.Extensions.DependencyInjection;

    /// <summary>
    ///     Provides observable read access for state objects.
    /// </summary>
    /// <typeparam name="T">The type of the tracked state object.</typeparam>
    public interface IStateMonitor<T>
    {
        /// <summary>
        ///     Gets the current state.
        /// </summary>
        T CurrentValue { get; }

        /// <summary>
        ///     Registers a listener to be called whenever the tracked state changes.
        /// </summary>
        /// <param name="listener">Registers a listener to be called whenever state changes.</param>
        /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns>
        IDisposable OnChange(Action<(T Previous, T Current)> listener);
    }

    /// <summary>
    ///     Provides write access for state objects.
    /// </summary>
    /// <typeparam name="T">The type of the tracked state object.</typeparam>
    public interface IStateMutator<T>
    {
        /// <summary>
        ///     Replaces the current state with the value resolved by the <paramref name="setter"/>.
        /// </summary>
        /// <param name="setter">Given the current state, resolves a new state value.</param>
        /// <returns>The updated state.</returns>
        T SetValue(Func<T, T> setter);
    }

    /// <summary>
    ///     Provides point-in-time read access for state objects.
    /// </summary>
    /// <typeparam name="T">The type of the tracked state object.</typeparam>
    public interface IStateSnapshot<out T>
    {
        /// <summary>
        ///     Gets the snapshotted state.
        /// </summary>
        T Value { get; }
    }

    /// <summary>
    ///     Provides observable management of state objects.
    /// </summary>
    /// <typeparam name="T">The type of the tracked state object.</typeparam>
    public interface IManagedState<T> : IStateMonitor<T>, IStateMutator<T>
    {
        /// <summary>
        ///     Gets a point-in-time snapshot of the current state.
        /// </summary>
        IStateSnapshot<T> Snapshot { get; }
    }

    /// <summary>
    ///     ManagedState extension methods.
    /// </summary>
    public static class ManagedStateExtensions
    {
        /// <summary>
        ///     <para>
        ///         Adds managed state of an object of the specified <typeparamref name="T"/> to the specified <see cref="IServiceCollection"/>.
        ///     </para>
        ///     <para>
        ///         <list type="bullet">
        ///             <item>A singleton instance of <see cref="IManagedState{T}"/> to be used by instances requiring full control over the state</item>
        ///             <item>A singleton instance of <see cref="IStateMutator{T}"/> to be used by instances requiring the ability to mutate the state</item>
        ///             <item>A singleton instance of <see cref="IStateMonitor{T}"/> to be used by instances requiring observable read access to the state</item>
        ///             <item>A transient instance of <see cref="IStateSnapshot{T}"/> to be used by scoped or transient instances requiring the current state</item>
        ///         </list>
        ///     </para>
        /// </summary>
        /// <typeparam name="T">The type of the managed state object.</typeparam>
        /// <param name="services">The IServiceCollection to which the managed state is to be added.</param>
        /// <param name="setter">An optional anonymous function used to apply an initial state mutation.</param>
        /// <returns>The IServiceCollection with managed state added.</returns>
        public static IServiceCollection AddManagedState<T>(this IServiceCollection services, Func<T, T> setter = null)
            where T : class
        {
            services.AddSingleton<IManagedState<T>, ManagedState<T>>();
            services.AddSingleton(services =>
            {
                var monitor = (IStateMutator<T>)services.GetRequiredService<IManagedState<T>>();

                if (setter != null)
                {
                    monitor.SetValue(setter);
                }

                return monitor;
            });
            services.AddSingleton(services => (IStateMonitor<T>)services.GetRequiredService<IManagedState<T>>());
            services.AddTransient(services => services.GetRequiredService<IManagedState<T>>().Snapshot);

            return services;
        }
    }

    /// <summary>
    ///     Provides a point-in-time snapshot of state objects.
    /// </summary>
    /// <typeparam name="T">The type of the tracked state object.</typeparam>
    public class StateSnapshot<T> : IStateSnapshot<T>
    {
        /// <summary>
        ///     Initializes a new instance of the <see cref="StateSnapshot{T}"/> class.
        /// </summary>
        /// <param name="value">The current value of the state.</param>
        public StateSnapshot(T value)
        {
            Value = value.ToJson().FromJson<T>();
        }

        /// <summary>
        ///     Gets a snapshot of the current application state.
        /// </summary>
        public T Value { get; }
    }

    /// <summary>
    ///     Provides observable management of state objects.
    /// </summary>
    /// <typeparam name="T">The type of the tracked state object.</typeparam>
    public class ManagedState<T> : IManagedState<T>
    {
        private event Action<(T, T)> Changed;

        /// <summary>
        ///     Gets the current application state.
        /// </summary>
        public T CurrentValue { get; private set; } = (T)Activator.CreateInstance(typeof(T));

        /// <summary>
        ///     Gets a point-in-time snapshot of the current state.
        /// </summary>
        public IStateSnapshot<T> Snapshot => new StateSnapshot<T>(CurrentValue);

        private object Lock { get; } = new object();

        /// <summary>
        ///     Registers a listener to be called whenever the tracked state changes.
        /// </summary>
        /// <param name="listener">Registers a listener to be called whenever state changes.</param>
        /// <returns>An <see cref="IDisposable"/> which should be disposed to stop listening for changes.</returns>
        public IDisposable OnChange(Action<(T Previous, T Current)> listener)
        {
            var disposable = new ManagedStateDisposable<T>(this, listener);
            Changed += disposable.OnChange;
            return disposable;
        }

        /// <summary>
        ///     Replaces the current state with the value resolved by the <paramref name="setter"/>.
        /// </summary>
        /// <param name="setter">Given the current state, resolves a new state value.</param>
        /// <returns>The updated state.</returns>
        public T SetValue(Func<T, T> setter)
        {
            lock (Lock)
            {
                var previous = CurrentValue.ToJson().FromJson<T>();
                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<T> : 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<T> 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<T> 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;
                }
            }
        }
    }
}