Repository navigation
Expand file tree
/
Copy pathRemoteControlClient.cs
More file actions
314 lines (267 loc) · 7.61 KB
/
Copy pathRemoteControlClient.cs
File metadata and controls
314 lines (267 loc) · 7.61 KB
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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#nullable enable
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Uno.Extensions;
using Uno.Foundation;
using Uno.Foundation.Logging;
using Uno.UI.RemoteControl.Helpers;
using Uno.UI.RemoteControl.HotReload;
using Uno.UI.RemoteControl.HotReload.Messages;
using Uno.UI.RemoteControl.Messages;
namespace Uno.UI.RemoteControl
{
public class RemoteControlClient : IRemoteControlClient
{
public static RemoteControlClient? Instance { get; private set; }
public Type AppType { get; }
private readonly (string endpoint, int port)[]? _serverAddresses;
private WebSocket? _webSocket;
private Dictionary<string, IRemoteControlProcessor> _processors = new Dictionary<string, IRemoteControlProcessor>();
private Timer? _keepAliveTimer;
private RemoteControlClient(Type appType)
{
AppType = appType;
if(appType.Assembly.GetCustomAttributes(typeof(ServerEndpointAttribute), false) is ServerEndpointAttribute[] endpoints)
{
IEnumerable<(string endpoint, int port)> GetAddresses()
{
foreach (var endpoint in endpoints)
{
if (endpoint.Port == 0 && !Uri.TryCreate(endpoint.Endpoint, UriKind.Absolute, out _))
{
this.Log().LogError($"Failed to get remote control server port from the IDE for endpoint {endpoint.Endpoint}.");
}
else
{
yield return (endpoint.Endpoint, endpoint.Port);
}
}
}
_serverAddresses = GetAddresses().ToArray();
}
if ((_serverAddresses?.Length ?? 0) == 0)
{
this.Log().LogError("Failed to get any remote control server endpoint from the IDE.");
return;
}
RegisterProcessor(new HotReload.ClientHotReloadProcessor(this));
StartConnection();
}
private void RegisterProcessor(IRemoteControlProcessor processor)
{
_processors[processor.Scope] = processor;
}
private async Task StartConnection()
{
try
{
#if __WASM__
var isHttps = WebAssemblyRuntime.InvokeJS("window.location.protocol == 'https:'").ToLower() == "true";
#else
const bool isHttps = false;
#endif
async Task<(Uri endPoint, WebSocket socket)> Connect(string endpoint, int port, CancellationToken ct)
{
var s = new ClientWebSocket();
Uri BuildServerUri()
{
if (Uri.TryCreate(endpoint, UriKind.Absolute, out var fullUri))
{
var wsScheme = fullUri.Scheme switch
{
"http" => "ws",
"https" => "wss",
_ => throw new InvalidOperationException($"Unsupported remote host scheme ({fullUri})"),
};
return new Uri($"{wsScheme}://{fullUri.Authority}/rc");
}
else if (port == 443)
{
#if __WASM__
if (endpoint.EndsWith("gitpod.io"))
{
var originParts = endpoint.Split('-');
var currentHost = Foundation.WebAssemblyRuntime.InvokeJS("window.location.hostname");
var targetParts = currentHost.Split('-');
endpoint = originParts[0] + '-' + currentHost.Substring(targetParts[0].Length + 1);
}
#endif
return new Uri($"wss://{endpoint}/rc");
}
else
{
var scheme = isHttps ? "wss" : "ws";
return new Uri($"{scheme}://{endpoint}:{port}/rc");
}
}
var serverUri = BuildServerUri();
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"Connecting to [{serverUri}]");
}
await s.ConnectAsync(serverUri, ct);
return (serverUri, s);
}
if (_serverAddresses != null)
{
var connections = _serverAddresses
.Where(adr => adr.port != 0 || Uri.TryCreate(adr.endpoint, UriKind.Absolute, out _))
.Select(s =>
{
var cts = new CancellationTokenSource();
var task = Connect(s.endpoint, s.port, cts.Token);
return (task, cts);
})
.ToArray();
var timeout = Task.Delay(30000);
var completed = await Task.WhenAny(connections.Select(c => c.task).Concat(timeout));
foreach (var connection in connections)
{
if (connection.task == completed)
{
continue;
}
connection.cts.Cancel();
if (connection.task.Status == TaskStatus.RanToCompletion)
{
connection.task.Result.socket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
}
}
if (completed == timeout)
{
if (this.Log().IsEnabled(LogLevel.Error))
{
this.Log().LogError("Failed to connect to the server (timeout).");
}
return;
}
var connected = ((Task<(Uri endPoint, WebSocket socket)>)completed).Result;
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"Connected to {connected.endPoint}");
}
_webSocket = connected.socket;
await ProcessMessages();
}
else
{
if (this.Log().IsEnabled(LogLevel.Warning))
{
this.Log().LogWarning($"No server addresses provided, skipping.");
}
}
}
catch (Exception ex)
{
if (this.Log().IsEnabled(LogLevel.Error))
{
this.Log().LogError($"Failed to connect to the server ({ex})", ex);
}
}
}
private async Task ProcessMessages()
{
InitializeServerProcessors();
foreach(var processor in _processors)
{
await processor.Value.Initialize();
}
StartKeepAliveTimer();
while (await WebSocketHelper.ReadFrame(_webSocket, CancellationToken.None) is HotReload.Messages.Frame frame)
{
if (frame.Scope == "RemoteControlServer")
{
if (frame.Name == KeepAliveMessage.Name)
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"Server Keepalive frame");
}
}
}
else
{
if (_processors.TryGetValue(frame.Scope, out var processor))
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"Received frame [{frame.Scope}/{frame.Name}]");
}
await processor.ProcessFrame(frame);
}
else
{
if (this.Log().IsEnabled(LogLevel.Error))
{
this.Log().LogError($"Unknown Frame scope {frame.Scope}");
}
}
}
}
}
private void StartKeepAliveTimer()
{
KeepAliveMessage keepAlive = new();
_keepAliveTimer = new Timer(_ => {
try
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"Sending Keepalive frame");
}
SendMessage(keepAlive);
}
catch(Exception)
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"Keepalive failed");
}
_keepAliveTimer?.Dispose();
}
});
_keepAliveTimer.Change(TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(30));
}
private async Task InitializeServerProcessors()
{
if (AppType.Assembly.GetCustomAttributes(typeof(ServerProcessorsConfigurationAttribute), false) is ServerProcessorsConfigurationAttribute[] configs)
{
var config = configs.First();
if (this.Log().IsEnabled(LogLevel.Debug))
{
this.Log().LogDebug($"ServerProcessorsConfigurationAttribute ProcessorsPath={config.ProcessorsPath}");
}
await SendMessage(new ProcessorsDiscovery(config.ProcessorsPath));
}
else
{
if (this.Log().IsEnabled(LogLevel.Error))
{
this.Log().LogError("Unable to find ProjectConfigurationAttribute");
}
}
}
public static RemoteControlClient Initialize(Type appType)
=> Instance = new RemoteControlClient(appType);
public async Task SendMessage(IMessage message)
{
await WebSocketHelper.SendFrame(
_webSocket,
HotReload.Messages.Frame.Create(
1,
message.Scope,
message.Name,
message
),
CancellationToken.None);
}
}
}