~ruther/NosSmooth.Comms

ref: 8a197a09502eae1c7335ff552b207eec96714188 NosSmooth.Comms/src/Core/NosSmooth.Comms.Core/ServerManager.cs -rw-r--r-- 5.1 KiB
8a197a09 — František Boháček feat: add tcp implementation 2 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
//
//  ServerManager.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 Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NosSmooth.Comms.Data;
using NosSmooth.Comms.Data.Messages;
using NosSmooth.Core.Extensions;
using Remora.Results;

namespace NosSmooth.Comms.Core;

/// <summary>
/// Manages a server, awaits connections, handles messages.
/// </summary>
public class ServerManager
{
    private readonly IServer _server;
    private readonly MessageHandler _messageHandler;
    private readonly IOptions<NosSmoothMessageSerializerOptions> _options;
    private readonly ILogger<ServerManager> _logger;
    private readonly ILogger<ConnectionHandler> _handlerLogger;
    private readonly List<ConnectionHandler> _connectionHandlers;
    private Task<Result>? _task;
    private CancellationTokenSource? _ctSource;

    /// <summary>
    /// Initializes a new instance of the <see cref="ServerManager"/> class.
    /// </summary>
    /// <param name="server">The server to manage.</param>
    /// <param name="messageHandler">The message handler.</param>
    /// <param name="options">The options.</param>
    /// <param name="logger">The logger.</param>
    /// <param name="handlerLogger">The logger for message handler.</param>
    public ServerManager
    (
        IServer server,
        MessageHandler messageHandler,
        IOptions<NosSmoothMessageSerializerOptions> options,
        ILogger<ServerManager> logger,
        ILogger<ConnectionHandler> handlerLogger
    )
    {
        _server = server;
        _connectionHandlers = new List<ConnectionHandler>();
        _messageHandler = messageHandler;
        _options = options;
        _logger = logger;
        _handlerLogger = handlerLogger;
    }

    /// <summary>
    /// Run the manager and await the task.
    /// </summary>
    /// <param name="stopToken">The token used for stopping the handler and disconnecting the connection.</param>
    /// <returns>A result that may or may not have succeeded.</returns>
    public Task<Result> RunManagerAsync(CancellationToken stopToken)
    {
        StartManager(stopToken);
        return _task!;
    }

    /// <summary>
    /// Broadcast the given message to all clients.
    /// </summary>
    /// <param name="message">The message to broadcast.</param>
    /// <param name="ct">The cancellation token used for cancelling the operation.</param>
    /// <typeparam name="TMessage">The type of the message.</typeparam>
    /// <returns>A result that may or may not have succeeded.</returns>
    public async Task<Result> BroadcastAsync<TMessage>(TMessage message, CancellationToken ct = default)
    {
        var errors = new List<IResult>();
        foreach (var handler in _connectionHandlers)
        {
            var result = await handler.SendMessageAsync<TMessage>(message, ct);
            if (!result.IsSuccess)
            {
                errors.Add(Result.FromError(result));
            }
        }

        return errors.Count switch
        {
            0 => Result.FromSuccess(),
            1 => (Result)errors[0],
            _ => new AggregateError(errors)
        };
    }

    /// <summary>
    /// Run the handler without awaiting the task.
    /// </summary>
    /// <param name="stopToken">The token used for stopping the handler and disconnecting the connection.</param>
    public void StartManager(CancellationToken stopToken = default)
    {
        if (_task is not null)
        {
            return;
        }

        _ctSource = CancellationTokenSource.CreateLinkedTokenSource(stopToken);
        _task = ManagerTask();
    }

    /// <summary>
    /// Request stop the server.
    /// </summary>
    public void RequestStop()
    {
        _ctSource?.Cancel();
    }

    private async Task<Result> ManagerTask()
    {
        if (_ctSource is null)
        {
            throw new InvalidOperationException("The ct source is not initialized.");
        }

        await _server.ListenAsync(_ctSource!.Token);

        while (!_ctSource.IsCancellationRequested)
        {
            var connectionResult = await _server.WaitForConnectionAsync(_ctSource.Token);
            if (!connectionResult.IsDefined(out var connection))
            {
                _logger.LogResultError(connectionResult);
                continue;
            }

            var handler = new ConnectionHandler(null, connection, _messageHandler, _options, _handlerLogger);
            _connectionHandlers.Add(handler);

            handler.StartHandler(_ctSource.Token);
        }

        List<IResult> errors = new List<IResult>();
        foreach (var handler in _connectionHandlers)
        {
            var handlerResult = await handler.RunHandlerAsync(_ctSource.Token);

            if (!handlerResult.IsSuccess)
            {
                errors.Add(handlerResult);
            }
        }

        _server.Close();
        return errors.Count switch
        {
            0 => Result.FromSuccess(),
            1 => (Result)errors[0],
            _ => new AggregateError(errors)
        };
    }
}
Do not follow this link