~ruther/NosSmooth

ref: 197af02c063ffa7944c1a60a816bbf52277a0d4f NosSmooth/Core/NosSmooth.Core/Commands/CommandProcessor.cs -rw-r--r-- 6.3 KiB
197af02c — Rutherther fix(core): cancel control command cancellation token every time 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
//
//  CommandProcessor.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.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using NosSmooth.Core.Client;
using NosSmooth.Core.Errors;
using NosSmooth.Core.Packets;
using NosSmooth.Packets;
using Remora.Results;

namespace NosSmooth.Core.Commands;

/// <summary>
/// Calls <see cref="ICommandHandler"/> for the executing command
/// by using <see cref="IServiceProvider"/> dependency injection.
/// </summary>
public class CommandProcessor
{
    private readonly IServiceProvider _provider;

    /// <summary>
    /// Initializes a new instance of the <see cref="CommandProcessor"/> class.
    /// </summary>
    /// <param name="provider">The dependency injection provider.</param>
    public CommandProcessor(IServiceProvider provider)
    {
        _provider = provider;
    }

    /// <summary>
    /// Processes the given command, calling its handler or returning error.
    /// </summary>
    /// <param name="client">The NosTale client.</param>
    /// <param name="command">The command to process.</param>
    /// <param name="ct">The cancellation token for cancelling the operation.</param>
    /// <returns>A result that may or may not have succeeded.</returns>
    /// <exception cref="InvalidOperationException">Thrown on critical error.</exception>
    public Task<Result> ProcessCommand(INostaleClient client, ICommand command, CancellationToken ct = default)
    {
        var processMethod = GetType().GetMethod
        (
            nameof(DispatchCommandHandler),
            BindingFlags.NonPublic | BindingFlags.Instance
        );

        if (processMethod is null)
        {
            throw new InvalidOperationException("Could not find process command generic method in command processor.");
        }

        var boundProcessMethod = processMethod.MakeGenericMethod(command.GetType());

        return (Task<Result>)boundProcessMethod.Invoke(this, new object[] { client, command, ct })!;
    }

    private async Task<Result> DispatchCommandHandler<TCommand>
    (
        INostaleClient client,
        TCommand command,
        CancellationToken ct = default
    )
        where TCommand : class, ICommand
    {
        using var scope = _provider.CreateScope();
        var beforeResult = await ExecuteBeforeExecutionAsync(scope.ServiceProvider, client, command, ct);
        if (!beforeResult.IsSuccess)
        {
            return beforeResult;
        }

        var commandHandler = scope.ServiceProvider.GetService<ICommandHandler<TCommand>>();
        if (commandHandler is null)
        {
            var result = Result.FromError(new CommandHandlerNotFound(command.GetType()));
            var afterExecutionResult = await ExecuteAfterExecutionAsync
            (
                scope.ServiceProvider,
                client,
                command,
                result,
                ct
            );
            if (!afterExecutionResult.IsSuccess)
            {
                return new AggregateError(result, afterExecutionResult);
            }

            return result;
        }

        Result handlerResult;
        try
        {
            handlerResult = await commandHandler.HandleCommand(command, ct);
        }
        catch (Exception e)
        {
            handlerResult = e;
        }

        var afterResult = await ExecuteAfterExecutionAsync
        (
            scope.ServiceProvider,
            client,
            command,
            handlerResult,
            ct
        );

        if (!afterResult.IsSuccess && !handlerResult.IsSuccess)
        {
            return new AggregateError(handlerResult, afterResult);
        }

        if (!handlerResult.IsSuccess)
        {
            return handlerResult;
        }

        return afterResult;
    }

    private async Task<Result> ExecuteBeforeExecutionAsync<TCommand>
    (
        IServiceProvider services,
        INostaleClient client,
        TCommand command,
        CancellationToken ct
    )
        where TCommand : ICommand
    {
        try
        {
            var results = await Task.WhenAll
            (
                services.GetServices<IPreCommandExecutionEvent>()
                    .Select(x => x.ExecuteBeforeCommandAsync(client, command, ct))
            );

            var errorResults = new List<Result>();
            foreach (var result in results)
            {
                if (!result.IsSuccess)
                {
                    errorResults.Add(result);
                }
            }

            return errorResults.Count switch
            {
                1 => errorResults[0],
                0 => Result.FromSuccess(),
                _ => new AggregateError(errorResults.Cast<IResult>().ToArray())
            };
        }
        catch (Exception e)
        {
            return e;
        }
    }

    private async Task<Result> ExecuteAfterExecutionAsync<TCommand>
    (
        IServiceProvider services,
        INostaleClient client,
        TCommand command,
        Result handlerResult,
        CancellationToken ct
    )
        where TCommand : ICommand
    {
        try
        {
            var results = await Task.WhenAll
            (
                services.GetServices<IPostCommandExecutionEvent>()
                    .Select(x => x.ExecuteAfterCommandAsync(client, command, handlerResult, ct))
            );

            var errorResults = new List<Result>();
            foreach (var result in results)
            {
                if (!result.IsSuccess)
                {
                    errorResults.Add(result);
                }
            }

            return errorResults.Count switch
            {
                1 => errorResults[0],
                0 => Result.FromSuccess(),
                _ => new AggregateError(errorResults.Cast<IResult>().ToArray())
            };
        }
        catch (Exception e)
        {
            return e;
        }
    }
}
Do not follow this link