This repository was archived by the owner on Dec 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathConnection.cs
218 lines (203 loc) · 8.12 KB
/
Connection.cs
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
using LanguageServer.Json;
using LanguageServer.Parameters.General;
using Matarillo.IO;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LanguageServer
{
public class Connection
{
private ProtocolReader input;
private const byte CR = (byte)13;
private const byte LF = (byte)10;
private readonly byte[] separator = { CR, LF };
private Stream output;
private readonly object outputLock = new object();
public RequestHandlerCollection RequestHandlers { get; } = new RequestHandlerCollection();
public NotificationHandlerCollection NotificationHandlers { get; } = new NotificationHandlerCollection();
private ResponseHandlerCollection ResponseHandlers { get; } = new ResponseHandlerCollection();
private CancellationHandlerCollection CancellationHandlers { get; } = new CancellationHandlerCollection();
public Connection(Stream input, Stream output)
{
this.input = new ProtocolReader(input);
this.output = output;
}
public async Task Listen()
{
while (true)
{
try
{
var success = await ReadAndHandle();
if (!success)
{
break;
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
}
public async Task<bool> ReadAndHandle()
{
var json = await Read();
var messageTest = (MessageTest)Serializer.Instance.Deserialize(typeof(MessageTest), json);
if (messageTest == null)
{
return false;
}
if (messageTest.IsRequest)
{
HandleRequest(messageTest.method, messageTest.id, json);
}
else if (messageTest.IsResponse)
{
HandleResponse(messageTest.id, json);
}
else if (messageTest.IsCancellation)
{
HandleCancellation(json);
}
else if (messageTest.IsNotification)
{
HandleNotification(messageTest.method, json);
}
return true;
}
private void HandleRequest(string method, NumberOrString id, string json)
{
if (RequestHandlers.TryGetRequestHandler(method, out var handler))
{
try
{
var tokenSource = new CancellationTokenSource();
CancellationHandlers.AddCancellationTokenSource(id, tokenSource);
var request = Serializer.Instance.Deserialize(handler.RequestType, json);
var requestResponse = (ResponseMessageBase)handler.Handle(request, this, tokenSource.Token);
CancellationHandlers.RemoveCancellationTokenSource(id);
requestResponse.id = id;
SendMessage(requestResponse);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
var requestErrorResponse = Reflector.CreateErrorResponse(handler.ResponseType, ex.ToString());
SendMessage(requestErrorResponse);
}
}
else
{
Console.Error.WriteLine("WARN: server does not support a request '" + method + "'");
}
}
private void HandleResponse(NumberOrString id, string json)
{
if (ResponseHandlers.TryRemoveResponseHandler(id, out var handler))
{
var response = Serializer.Instance.Deserialize(handler.ResponseType, json);
handler.Handle(response);
}
else
{
var idString = (id.IsLeft) ? id.Left.ToString() : id.Right;
Console.Error.WriteLine("WARN: server does not expect a response to '" + idString + "'");
}
}
private void HandleCancellation(string json)
{
var cancellation = (NotificationMessage<CancelParams>)Serializer.Instance.Deserialize(typeof(NotificationMessage<CancelParams>), json);
var id = cancellation.@params.id;
if (CancellationHandlers.TryRemoveCancellationTokenSource(id, out var tokenSource))
{
tokenSource.Cancel();
}
else
{
var idString = (id.IsLeft) ? id.Left.ToString() : id.Right;
Console.Error.WriteLine("WARN: server can not cancel a procedure '" + idString + "'");
}
}
private void HandleNotification(string method, string json)
{
if (NotificationHandlers.TryGetNotificationHandler(method, out var handler))
{
var notification = Serializer.Instance.Deserialize(handler.NotificationType, json);
handler.Handle(notification, this);
}
else
{
Console.Error.WriteLine("WARN: server does not support a notification '" + method + "'");
}
}
public void SendRequest<TRequest, TResponse>(TRequest request, Action<TResponse> responseHandler)
where TRequest : RequestMessageBase
where TResponse : ResponseMessageBase
{
var handler = new ResponseHandler(request.id, typeof(TResponse), o => responseHandler((TResponse)o));
ResponseHandlers.AddResponseHandler(handler);
SendMessage(request);
}
public void SendNotification<TNotification>(TNotification notification)
where TNotification : NotificationMessageBase
{
SendMessage(notification);
}
public void SendCancellation(NumberOrString id)
{
var message = new NotificationMessage<CancelParams> { method = "$/cancelRequest", @params = new CancelParams { id = id } };
SendMessage(message);
}
private void SendMessage(MessageBase message)
{
Write(Serializer.Instance.Serialize(typeof(MessageBase), message));
}
private void Write(string json)
{
var utf8 = Encoding.UTF8.GetBytes(json);
lock (outputLock)
{
using (var writer = new StreamWriter(output, Encoding.ASCII, 1024, true))
{
writer.Write($"Content-Length: {utf8.Length}\r\n");
writer.Write("\r\n");
writer.Flush();
}
output.Write(utf8, 0, utf8.Length);
output.Flush();
}
}
private async Task<string> Read()
{
var contentLength = 0;
var headerBytes = await input.ReadToSeparatorAsync(separator);
while (headerBytes.Length != 0)
{
var headerLine = Encoding.ASCII.GetString(headerBytes);
var position = headerLine.IndexOf(": ", StringComparison.Ordinal);
if (position >= 0)
{
var name = headerLine.Substring(0, position);
var value = headerLine.Substring(position + 2);
if (string.Equals(name, "Content-Length", StringComparison.Ordinal))
{
int.TryParse(value, out contentLength);
}
}
headerBytes = await input.ReadToSeparatorAsync(separator);
}
if (contentLength == 0)
{
return "";
}
var contentBytes = await input.ReadBytesAsync(contentLength);
return Encoding.UTF8.GetString(contentBytes);
}
}
}