~ruther/NosSmooth.Comms

ref: 5164e0aff7ef406c32e42516ce4790920af2ab83 NosSmooth.Comms/src/Core/NosSmooth.Comms.Core/ConnectionHandler.cs -rw-r--r-- 6.3 KiB
5164e0af — František Boháček feat: add abstractions and core of communication 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
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
//
//  ConnectionHandler.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 MessagePack;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NosSmooth.Comms.Data;
using NosSmooth.Comms.Data.Messages;
using NosSmooth.Core.Contracts;
using NosSmooth.Core.Extensions;
using Remora.Results;

namespace NosSmooth.Comms.Core;

/// <summary>
/// Manages a connection, calls message handler when message is received.
/// Serializes and deserializes the messages from the stream.
/// </summary>
public class ConnectionHandler
{
    private readonly Contractor? _contractor;
    private readonly IConnection _connection;
    private readonly MessageHandler _messageHandler;
    private readonly MessagePackSerializerOptions _options;
    private readonly ILogger<ConnectionHandler> _logger;
    private long _messageId = 1;
    private Task<Result>? _task;

    /// <summary>
    /// Initializes a new instance of the <see cref="ConnectionHandler"/> class.
    /// </summary>
    /// <param name="contractor">The contractor.</param>
    /// <param name="connection">The connection.</param>
    /// <param name="messageHandler">The message handler.</param>
    /// <param name="options">The options.</param>
    /// <param name="logger">The logger.</param>
    public ConnectionHandler
    (
        Contractor? contractor,
        IConnection connection,
        MessageHandler messageHandler,
        IOptions<NosSmoothMessageSerializerOptions> options,
        ILogger<ConnectionHandler> logger
    )
    {
        _contractor = contractor;
        _connection = connection;
        _messageHandler = messageHandler;
        _options = options.Value;
        _logger = logger;
    }

    /// <summary>
    /// Gets the connection.
    /// </summary>
    public IConnection Connection => _connection;

    /// <summary>
    /// Run the handler 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> RunHandlerAsync(CancellationToken stopToken)
    {
        StartHandler(stopToken);
        return _task!;
    }

    /// <summary>
    /// Start the connection handler task, do not wait for it.
    /// </summary>
    /// <param name="stopToken">The token used for stopping/disconnecting the connection and handling.</param>
    public void StartHandler(CancellationToken stopToken)
    {
        if (_task is not null)
        {
            return;
        }

        _task = HandlerTask(stopToken);
    }

    private async Task<Result> HandlerTask(CancellationToken ct)
    {
        using var reader = new MessagePackStreamReader(_connection.ReadStream, true);
        while (!ct.IsCancellationRequested)
        {
            try
            {
                var read = await reader.ReadAsync(ct);
                if (!read.HasValue)
                {
                    _logger.LogWarning("Message not read? ...");
                    continue;
                }

                var message = MessagePackSerializer.Typeless.Deserialize
                    (read.Value, _options, ct);
                var result = await _messageHandler.HandleMessageAsync(this, message, ct);

                if (!result.IsSuccess)
                {
                    _logger.LogResultError(result);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "An exception was thrown during deserialization of a message.");
            }
        }

        _connection.Disconnect();
        return Result.FromSuccess();
    }

    /// <summary>
    /// Create a contract for sending a message,
    /// <see cref="ResponseResult"/> will be returned back.
    /// </summary>
    /// <param name="message">The message.</param>
    /// <typeparam name="TMessage">The type of the message.</typeparam>
    /// <returns>A contract representing send message operation.</returns>
    /// <exception cref="InvalidOperationException">Thrown in case contract is created on the server. Clients do not send responses.</exception>
    public IContract<Result, DefaultStates> ContractSendMessage<TMessage>(TMessage message)
    {
        if (_contractor is null)
        {
            throw new InvalidOperationException
            (
                "Contracting is not supported, the other side does not send responses. Only server sends responses back."
            );
        }

        long messageId = 0;
        return new ContractBuilder<Result, DefaultStates, NoErrors>(_contractor, DefaultStates.None)
            .SetMoveAction
            (
                DefaultStates.None,
                async (a, ct) =>
                {
                    var result = await SendMessageAsync(message, ct);
                    if (!result.IsDefined(out messageId))
                    {
                        return Result<bool>.FromError(result);
                    }

                    return true;
                },
                DefaultStates.Requested
            )
            .SetMoveFilter<ResponseResult>
                (DefaultStates.Requested, (r) => r.MessageId == messageId, DefaultStates.ResponseObtained)
            .SetFillData<ResponseResult>(DefaultStates.ResponseObtained, r => r.Result)
            .Build();
    }

    /// <summary>
    /// Send  message to the other end.
    /// </summary>
    /// <param name="message">The message to send. It will be wrapped before sending.</param>
    /// <param name="ct">The cancellation token used for cancelling the operation.</param>
    /// <typeparam name="TMessage">Type of the message to send.</typeparam>
    /// <returns>The id of the message sent or an error.</returns>
    public async Task<Result<long>> SendMessageAsync<TMessage>(TMessage message, CancellationToken ct = default)
    {
        var messageId = _messageId++;
        var messageWrapper = new MessageWrapper<TMessage>(1, messageId, message);

        try
        {
            await MessagePackSerializer.Typeless.SerializeAsync(_connection.WriteStream, messageWrapper, _options, ct);
            await _connection.WriteStream.FlushAsync(ct);
        }
        catch (Exception e)
        {
            return e;
        }

        return messageId;
    }
}
Do not follow this link