summaryrefslogtreecommitdiff
path: root/modules/mono/editor/GodotTools/GodotTools.IdeMessaging/Peer.cs
blob: 10d7e1898e93ffea8b39758da0d60d3bdee25894 (plain)
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GodotTools.IdeMessaging.Requests;
using GodotTools.IdeMessaging.Utils;

namespace GodotTools.IdeMessaging
{
    public sealed class Peer : IDisposable
    {
        /// <summary>
        /// Major version.
        /// There is no forward nor backward compatibility between different major versions.
        /// Connection is refused if client and server have different major versions.
        /// </summary>
        public static readonly int ProtocolVersionMajor = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Major;

        /// <summary>
        /// Minor version, which clients must be backward compatible with.
        /// Connection is refused if the client's minor version is lower than the server's.
        /// </summary>
        public static readonly int ProtocolVersionMinor = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Minor;

        /// <summary>
        /// Revision, which doesn't affect compatibility.
        /// </summary>
        public static readonly int ProtocolVersionRevision = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Revision;

        public const string ClientHandshakeName = "GodotIdeClient";
        public const string ServerHandshakeName = "GodotIdeServer";

        private const int ClientWriteTimeout = 8000;

        public delegate Task<Response> RequestHandler(Peer peer, MessageContent content);

        private readonly TcpClient tcpClient;

        private readonly TextReader clientReader;
        private readonly TextWriter clientWriter;

        private readonly SemaphoreSlim writeSem = new SemaphoreSlim(1);

        private string remoteIdentity = string.Empty;
        public string RemoteIdentity => remoteIdentity;

        public event Action Connected;
        public event Action Disconnected;

        private ILogger Logger { get; }

        public bool IsDisposed { get; private set; }

        public bool IsTcpClientConnected => tcpClient.Client != null && tcpClient.Client.Connected;

        private bool IsConnected { get; set; }

        private readonly IHandshake handshake;
        private readonly IMessageHandler messageHandler;

        private readonly Dictionary<string, Queue<ResponseAwaiter>> requestAwaiterQueues = new Dictionary<string, Queue<ResponseAwaiter>>();
        private readonly SemaphoreSlim requestsSem = new SemaphoreSlim(1);

        public Peer(TcpClient tcpClient, IHandshake handshake, IMessageHandler messageHandler, ILogger logger)
        {
            this.tcpClient = tcpClient;
            this.handshake = handshake;
            this.messageHandler = messageHandler;

            Logger = logger;

            NetworkStream clientStream = tcpClient.GetStream();
            clientStream.WriteTimeout = ClientWriteTimeout;

            clientReader = new StreamReader(clientStream, Encoding.UTF8);
            clientWriter = new StreamWriter(clientStream, Encoding.UTF8) {NewLine = "\n"};
        }

        public async Task Process()
        {
            try
            {
                var decoder = new MessageDecoder();

                string messageLine;
                while ((messageLine = await ReadLine()) != null)
                {
                    var state = decoder.Decode(messageLine, out var msg);

                    if (state == MessageDecoder.State.Decoding)
                        continue; // Not finished decoding yet

                    if (state == MessageDecoder.State.Errored)
                    {
                        Logger.LogError($"Received message line with invalid format: {messageLine}");
                        continue;
                    }

                    Logger.LogDebug($"Received message: {msg}");

                    try
                    {
                        if (msg.Kind == MessageKind.Request)
                        {
                            var responseContent = await messageHandler.HandleRequest(this, msg.Id, msg.Content, Logger);
                            await WriteMessage(new Message(MessageKind.Response, msg.Id, responseContent));
                        }
                        else if (msg.Kind == MessageKind.Response)
                        {
                            ResponseAwaiter responseAwaiter;

                            using (await requestsSem.UseAsync())
                            {
                                if (!requestAwaiterQueues.TryGetValue(msg.Id, out var queue) || queue.Count <= 0)
                                {
                                    Logger.LogError($"Received unexpected response: {msg.Id}");
                                    return;
                                }

                                responseAwaiter = queue.Dequeue();
                            }

                            responseAwaiter.SetResult(msg.Content);
                        }
                        else
                        {
                            throw new IndexOutOfRangeException($"Invalid message kind {msg.Kind}");
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.LogError($"Message handler for '{msg}' failed with exception", e);
                    }
                }
            }
            catch (Exception e)
            {
                if (!IsDisposed || !(e is SocketException || e.InnerException is SocketException))
                {
                    Logger.LogError("Unhandled exception in the peer loop", e);
                }
            }
        }

        public async Task<bool> DoHandshake(string identity)
        {
            if (!await WriteLine(handshake.GetHandshakeLine(identity)))
            {
                Logger.LogError("Could not write handshake");
                return false;
            }

            var readHandshakeTask = ReadLine();

            if (await Task.WhenAny(readHandshakeTask, Task.Delay(8000)) != readHandshakeTask)
            {
                Logger.LogError("Timeout waiting for the client handshake");
                return false;
            }

            string peerHandshake = await readHandshakeTask;

            if (handshake == null || !handshake.IsValidPeerHandshake(peerHandshake, out remoteIdentity, Logger))
            {
                Logger.LogError("Received invalid handshake: " + peerHandshake);
                return false;
            }

            IsConnected = true;
            Connected?.Invoke();

            Logger.LogInfo("Peer connection started");

            return true;
        }

        private async Task<string> ReadLine()
        {
            try
            {
                return await clientReader.ReadLineAsync();
            }
            catch (Exception e)
            {
                if (IsDisposed)
                {
                    var se = e as SocketException ?? e.InnerException as SocketException;
                    if (se != null && se.SocketErrorCode == SocketError.Interrupted)
                        return null;
                }

                throw;
            }
        }

        private Task<bool> WriteMessage(Message message)
        {
            Logger.LogDebug($"Sending message: {message}");
            int bodyLineCount = message.Content.Body.Count(c => c == '\n');

            bodyLineCount += 1; // Extra line break at the end

            var builder = new StringBuilder();

            builder.AppendLine(message.Kind.ToString());
            builder.AppendLine(message.Id);
            builder.AppendLine(message.Content.Status.ToString());
            builder.AppendLine(bodyLineCount.ToString());
            builder.AppendLine(message.Content.Body);

            return WriteLine(builder.ToString());
        }

        public async Task<TResponse> SendRequest<TResponse>(string id, string body)
            where TResponse : Response, new()
        {
            ResponseAwaiter responseAwaiter;

            using (await requestsSem.UseAsync())
            {
                bool written = await WriteMessage(new Message(MessageKind.Request, id, new MessageContent(body)));

                if (!written)
                    return null;

                if (!requestAwaiterQueues.TryGetValue(id, out var queue))
                {
                    queue = new Queue<ResponseAwaiter>();
                    requestAwaiterQueues.Add(id, queue);
                }

                responseAwaiter = new ResponseAwaiter<TResponse>();
                queue.Enqueue(responseAwaiter);
            }

            return (TResponse)await responseAwaiter;
        }

        private async Task<bool> WriteLine(string text)
        {
            if (clientWriter == null || IsDisposed || !IsTcpClientConnected)
                return false;

            using (await writeSem.UseAsync())
            {
                try
                {
                    await clientWriter.WriteLineAsync(text);
                    await clientWriter.FlushAsync();
                }
                catch (Exception e)
                {
                    if (!IsDisposed)
                    {
                        var se = e as SocketException ?? e.InnerException as SocketException;
                        if (se != null && se.SocketErrorCode == SocketError.Shutdown)
                            Logger.LogInfo("Client disconnected ungracefully");
                        else
                            Logger.LogError("Exception thrown when trying to write to client", e);

                        Dispose();
                    }
                }
            }

            return true;
        }

        // ReSharper disable once UnusedMember.Global
        public void ShutdownSocketSend()
        {
            tcpClient.Client.Shutdown(SocketShutdown.Send);
        }

        public void Dispose()
        {
            if (IsDisposed)
                return;

            IsDisposed = true;

            if (IsTcpClientConnected)
            {
                if (IsConnected)
                    Disconnected?.Invoke();
            }

            clientReader?.Dispose();
            clientWriter?.Dispose();
            ((IDisposable)tcpClient)?.Dispose();
        }
    }
}