~ruther/NosSmooth

ref: 6528818bbd996abf31849e916aba6c391c155be5 NosSmooth/Core/NosSmooth.Core/Commands/Control/ControlCommands.cs -rw-r--r-- 10.8 KiB
6528818b — Rutherther chore(core): update version 3 years ago
                                                                                
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//
//  ControlCommands.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using NosSmooth.Core.Errors;
using Remora.Results;

namespace NosSmooth.Core.Commands.Control;

/// <summary>
/// The state of <see cref="TakeControlCommand"/>.
/// </summary>
public class ControlCommands
{
    /// <summary>
    /// The group representing every group.
    /// </summary>
    /// <remarks>
    /// This will cancel all ongoing control operations
    /// upon registration.
    ///
    /// This will also be cancelled if any operation tries
    /// to take control.
    /// </remarks>
    public const string AllGroup = "__all";

    private ConcurrentDictionary<string, CommandData> _data;
    private ConcurrentDictionary<string, SemaphoreSlim> _addSemaphores;
    private ConcurrentDictionary<string, SemaphoreSlim> _removeSemaphores;

    /// <summary>
    /// Initializes a new instance of the <see cref="ControlCommands"/> class.
    /// </summary>
    public ControlCommands()
    {
        _data = new ConcurrentDictionary<string, CommandData>();
        _addSemaphores = new ConcurrentDictionary<string, SemaphoreSlim>();
        _removeSemaphores = new ConcurrentDictionary<string, SemaphoreSlim>();
    }

    /// <summary>
    /// Gets whether user actions are currently allowed.
    /// </summary>
    public bool AllowUserActions { get; private set; } = true;

    /// <summary>
    /// Register the given command.
    /// </summary>
    /// <remarks>
    /// The command will grant control if the result is successful.
    /// After execution the command should call CancelAsync.
    /// </remarks>
    /// <param name="command">The command data.</param>
    /// <param name="cancellationTokenSource">The cancellation token source that will be cancelled.</param>
    /// <param name="ct">The cancellation token for cancelling the operation.</param>
    /// <returns>The cancellation token that will symbolize the operation should be cancelled.</returns>
    public async Task<Result> RegisterAsync
        (TakeControlCommand command, CancellationTokenSource cancellationTokenSource, CancellationToken ct = default)
    {
        var semaphore = _addSemaphores.GetOrAdd(command.Group, _ => new SemaphoreSlim(1, 1));
        var removeSempahore = _removeSemaphores.GetOrAdd(command.Group, _ => new SemaphoreSlim(1, 1));
        await semaphore.WaitAsync(ct);

        var matchingCommands = FindMatchingCommands(command.Group);
        var cancelOperations = new List<Task<Result>>();
        foreach (var matchingCommand in matchingCommands)
        {
            cancelOperations.Add
                (CancelCommandAsync(matchingCommand, command.WaitForCancellation, ControlCommandsFilter.None, ct));
        }

        if (command.WaitForCancellation && cancelOperations.Count > 0)
        {
            semaphore.Release();
        }

        var results = await Task.WhenAll(cancelOperations);
        var errorResults = results.Where(x => !x.IsSuccess).ToArray();

        if (errorResults.Length > 0)
        {
            return errorResults.Length switch
            {
                1 => errorResults[0],
                _ => new AggregateError(errorResults.Cast<IResult>().ToList())
            };
        }

        if (command.WaitForCancellation && cancelOperations.Count > 0)
        {
            // There could be a new take of control already.
            return await RegisterAsync(command, cancellationTokenSource, ct);
        }

        await removeSempahore.WaitAsync(ct); // Should be right away
        _data.TryAdd(command.Group, new CommandData(command, cancellationTokenSource));
        cancellationTokenSource.Token.Register
        (
            () =>
            {
                _data.TryRemove(command.Group, out _);
                removeSempahore.Release();
            }
        );
        semaphore.Release();
        if (!command.AllowUserCancel)
        {
            AllowUserActions = false;
        }

        return Result.FromSuccess();
    }

    /// <summary>
    /// Finish command from the given group gracefully.
    /// </summary>
    /// <param name="group">The group to finish.</param>
    /// <returns>A result that may or may not have succeeded.</returns>
    public Task<Result> FinishAsync(string group)
    {
        var commandsToFinish = FindMatchingCommands(group);
        return FinishCommandsAsync(commandsToFinish);
    }

    /// <summary>
    /// Cancel the given group command.
    /// </summary>
    /// <param name="group">The name of the group to cancel the command.</param>
    /// <param name="waitForCancellation">Whether to wait if the ongoing operation is not cancellable.</param>
    /// <param name="ct">The cancellation token for cancelling the operation.</param>
    /// <returns>A result that may or may not have succeeded.</returns>
    public Task<Result> CancelAsync(string group, bool waitForCancellation = true, CancellationToken ct = default)
    {
        var commandsToCancel = FindMatchingCommands(group);
        return CancelCommandsAsync(commandsToCancel, waitForCancellation, ct: ct);
    }

    /// <summary>
    /// Cancel the given commands.
    /// </summary>
    /// <param name="filter">The filter to apply.</param>
    /// <param name="waitForCancellation">Whether to wait for cancellation of non cancellable commands.</param>
    /// <param name="ct">The cancellation token for cancelling the operation.</param>
    /// <returns>A result that may or may not have succeeded.</returns>
    public async Task<Result> CancelAsync
        (ControlCommandsFilter filter, bool waitForCancellation = true, CancellationToken ct = default)
    {
        bool cancelUser = filter.HasFlag(ControlCommandsFilter.UserCancellable);
        bool cancelMapChanged = filter.HasFlag(ControlCommandsFilter.MapChangeCancellable);
        bool cancelAll = !cancelUser && !cancelMapChanged;

        var commandsToCancel = _data.Values.Where
        (
            x => cancelAll || (cancelUser && x.Command.AllowUserCancel)
                || (cancelMapChanged && x.Command.CancelOnMapChange)
        );

        return await CancelCommandsAsync(commandsToCancel, waitForCancellation, filter, ct);
    }

    private async Task<Result> FinishCommandsAsync(IEnumerable<CommandData> commandsToFinish)
    {
        var tasks = commandsToFinish.Select(x => FinishCommandAsync(x, null));
        var results = await Task.WhenAll(tasks);
        var errorResults = results.Where(x => !x.IsSuccess).ToArray();

        return errorResults.Length switch
        {
            0 => Result.FromSuccess(),
            1 => errorResults[0],
            _ => new AggregateError(errorResults.Cast<IResult>().ToList())
        };
    }

    private async Task<Result> FinishCommandAsync(CommandData data, ControlCancelReason? cancelReason)
    {
        Result cancelledResult = Result.FromSuccess();
        if (cancelReason is not null)
        {
            try
            {
                 cancelledResult = await data.Command.CancelledCallback((ControlCancelReason)cancelReason);
            }
            catch (Exception e)
            {
                cancelledResult = e;
            }
        }

        try
        {
            if (!data.CancellationTokenSource.IsCancellationRequested)
            {
                data.CancellationTokenSource.Cancel();
            }
        }
        catch
        {
            // Don't handle
        }

        if (!AllowUserActions && !data.Command.AllowUserCancel)
        {
            AllowUserActions = _data.Values.All(x => x.Command.AllowUserCancel);
        }

        return cancelledResult;
    }

    private async Task<Result> CancelCommandsAsync
    (
        IEnumerable<CommandData> data,
        bool waitForCancellation = true,
        ControlCommandsFilter filter = ControlCommandsFilter.None,
        CancellationToken ct = default
    )
    {
        var commands = data.ToArray();
        if (commands.Length == 0)
        {
            return Result.FromSuccess();
        }

        if (commands.Length == 1)
        {
            return await CancelCommandAsync(commands[0], waitForCancellation, filter, ct);
        }

        var tasks = new List<Task<Result>>();
        foreach (var command in commands)
        {
            tasks.Add(CancelCommandAsync(command, waitForCancellation, filter, ct));
        }

        var results = await Task.WhenAll(tasks);
        var errorResults = results.Where(x => !x.IsSuccess).ToArray();
        return errorResults.Length switch
        {
            1 => errorResults[0],
            _ => new AggregateError(errorResults.Cast<IResult>().ToArray())
        };
    }

    private async Task<Result> CancelCommandAsync
    (
        CommandData data,
        bool waitForCancellation = true,
        ControlCommandsFilter filter = ControlCommandsFilter.None,
        CancellationToken ct = default
    )
    {
        if (!data.Command.CanBeCancelledByAnother && !filter.HasFlag(ControlCommandsFilter.UserCancellable))
        {
            if (!waitForCancellation)
            {
                return Result.FromError(new CouldNotGainControlError(data.Command.Group, "would wait"));
            }

            // Wait for the successful finish.
            var found = _removeSemaphores.TryGetValue(data.Command.Group, out var semaphore);
            if (!found || semaphore is null)
            {
                return Result.FromError
                    (new CouldNotGainControlError(data.Command.Group, "did not find remove semaphore. Bug?"));
            }

            await semaphore.WaitAsync(ct);
            semaphore.Release();
        }

        var cancelReason = filter switch
        {
            ControlCommandsFilter.UserCancellable => ControlCancelReason.UserAction,
            ControlCommandsFilter.MapChangeCancellable => ControlCancelReason.MapChanged,
            _ => ControlCancelReason.AnotherTask
        };

        return await FinishCommandAsync
        (
            data,
            cancelReason
        );
    }

    private IEnumerable<CommandData> FindMatchingCommands(string group)
    {
        if (group == AllGroup)
        {
            return _data.Values.ToArray();
        }

        if (!_data.ContainsKey(group))
        {
            return Array.Empty<CommandData>();
        }

        return new[] { _data[group] };
    }

    private struct CommandData
    {
        public CommandData(TakeControlCommand command, CancellationTokenSource cancellationTokenSource)
        {
            Command = command;
            CancellationTokenSource = cancellationTokenSource;
        }

        public TakeControlCommand Command { get; }

        public CancellationTokenSource CancellationTokenSource { get; }
    }
}
Do not follow this link