-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRpcController.cs
310 lines (271 loc) · 10.4 KB
/
RpcController.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
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
using System;
using System.Diagnostics;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using Coder.Desktop.App.Models;
using Coder.Desktop.Vpn;
using Coder.Desktop.Vpn.Proto;
using Coder.Desktop.Vpn.Utilities;
namespace Coder.Desktop.App.Services;
public class RpcOperationException : Exception
{
public RpcOperationException(string message, Exception innerException) : base(message, innerException)
{
}
public RpcOperationException(string message) : base(message)
{
}
}
public class VpnLifecycleException : Exception
{
public VpnLifecycleException(string message, Exception innerException) : base(message, innerException)
{
}
public VpnLifecycleException(string message) : base(message)
{
}
}
public interface IRpcController
{
public event EventHandler<RpcModel> StateChanged;
/// <summary>
/// Get the current state of the RpcController and the latest state received from the service.
/// </summary>
public RpcModel GetState();
/// <summary>
/// Disconnect from and reconnect to the RPC server.
/// </summary>
/// <exception cref="InvalidOperationException">Another operation is in progress</exception>
/// <exception>Throws an exception if reconnection fails. Exceptions from disconnection are ignored.</exception>
public Task Reconnect(CancellationToken ct = default);
/// <summary>
/// Start the VPN using the stored credentials in the ICredentialManager. If the VPN is already running, this
/// may have no effect.
/// </summary>
/// <exception cref="InvalidOperationException">Another operation is in progress</exception>
/// <exception cref="RpcOperationException">If the sending of the start command fails</exception>
/// <exception cref="VpnLifecycleException">If the service reports that the VPN failed to start</exception>
public Task StartVpn(CancellationToken ct = default);
/// <summary>
/// Stop the VPN. If the VPN is already not running, this may have no effect.
/// </summary>
/// <exception cref="InvalidOperationException">Another operation is in progress</exception>
/// <exception cref="RpcOperationException">If the sending of the stop command fails</exception>
/// <exception cref="VpnLifecycleException">If the service reports that the VPN failed to stop</exception>
public Task StopVpn(CancellationToken ct = default);
}
public class RpcController : IRpcController
{
private readonly ICredentialManager _credentialManager;
private readonly RaiiSemaphoreSlim _operationLock = new(1, 1);
private Speaker<ClientMessage, ServiceMessage>? _speaker;
private readonly RaiiSemaphoreSlim _stateLock = new(1, 1);
private readonly RpcModel _state = new();
public RpcController(ICredentialManager credentialManager)
{
_credentialManager = credentialManager;
}
public event EventHandler<RpcModel>? StateChanged;
public RpcModel GetState()
{
using var _ = _stateLock.Lock();
return _state.Clone();
}
public async Task Reconnect(CancellationToken ct = default)
{
using var _ = await AcquireOperationLockNowAsync();
MutateState(state =>
{
state.RpcLifecycle = RpcLifecycle.Connecting;
state.VpnLifecycle = VpnLifecycle.Stopped;
state.Workspaces.Clear();
state.Agents.Clear();
});
if (_speaker != null)
try
{
await DisposeSpeaker();
}
catch (Exception e)
{
// TODO: log/notify?
Debug.WriteLine($"Error disposing existing Speaker: {e}");
}
try
{
var client =
new NamedPipeClientStream(".", "Coder.Desktop.Vpn", PipeDirection.InOut, PipeOptions.Asynchronous);
await client.ConnectAsync(ct);
_speaker = new Speaker<ClientMessage, ServiceMessage>(client);
_speaker.Receive += SpeakerOnReceive;
_speaker.Error += SpeakerOnError;
await _speaker.StartAsync(ct);
}
catch (Exception e)
{
MutateState(state =>
{
state.RpcLifecycle = RpcLifecycle.Disconnected;
state.VpnLifecycle = VpnLifecycle.Unknown;
state.Workspaces.Clear();
state.Agents.Clear();
});
throw new RpcOperationException("Failed to reconnect to the RPC server", e);
}
MutateState(state =>
{
state.RpcLifecycle = RpcLifecycle.Connected;
state.VpnLifecycle = VpnLifecycle.Unknown;
state.Workspaces.Clear();
state.Agents.Clear();
});
var statusReply = await _speaker.SendRequestAwaitReply(new ClientMessage
{
Status = new StatusRequest(),
}, ct);
if (statusReply.MsgCase != ServiceMessage.MsgOneofCase.Status)
throw new InvalidOperationException($"Unexpected reply message type: {statusReply.MsgCase}");
ApplyStatusUpdate(statusReply.Status);
}
public async Task StartVpn(CancellationToken ct = default)
{
using var _ = await AcquireOperationLockNowAsync();
AssertRpcConnected();
var credentials = _credentialManager.GetCredentials();
if (credentials.State != CredentialState.Valid)
throw new RpcOperationException("Cannot start VPN without valid credentials");
MutateState(state => { state.VpnLifecycle = VpnLifecycle.Starting; });
ServiceMessage reply;
try
{
reply = await _speaker!.SendRequestAwaitReply(new ClientMessage
{
Start = new StartRequest
{
CoderUrl = credentials.CoderUrl,
ApiToken = credentials.ApiToken,
},
}, ct);
if (reply.MsgCase != ServiceMessage.MsgOneofCase.Start)
throw new InvalidOperationException($"Unexpected reply message type: {reply.MsgCase}");
}
catch (Exception e)
{
MutateState(state => { state.VpnLifecycle = VpnLifecycle.Stopped; });
throw new RpcOperationException("Failed to send start command to service", e);
}
if (!reply.Start.Success)
{
MutateState(state => { state.VpnLifecycle = VpnLifecycle.Stopped; });
throw new VpnLifecycleException("Failed to start VPN",
new InvalidOperationException($"Service reported failure: {reply.Start.ErrorMessage}"));
}
MutateState(state => { state.VpnLifecycle = VpnLifecycle.Started; });
}
public async Task StopVpn(CancellationToken ct = default)
{
using var _ = await AcquireOperationLockNowAsync();
AssertRpcConnected();
MutateState(state => { state.VpnLifecycle = VpnLifecycle.Stopping; });
ServiceMessage reply;
try
{
reply = await _speaker!.SendRequestAwaitReply(new ClientMessage
{
Stop = new StopRequest(),
}, ct);
}
catch (Exception e)
{
throw new RpcOperationException("Failed to send stop command to service", e);
}
finally
{
// Technically the state is unknown now.
MutateState(state => { state.VpnLifecycle = VpnLifecycle.Stopped; });
}
if (reply.MsgCase != ServiceMessage.MsgOneofCase.Stop)
throw new VpnLifecycleException("Failed to stop VPN",
new InvalidOperationException($"Unexpected reply message type: {reply.MsgCase}"));
if (!reply.Stop.Success)
throw new VpnLifecycleException("Failed to stop VPN",
new InvalidOperationException($"Service reported failure: {reply.Stop.ErrorMessage}"));
}
private void MutateState(Action<RpcModel> mutator)
{
RpcModel newState;
using (_stateLock.Lock())
{
mutator(_state);
newState = _state.Clone();
}
StateChanged?.Invoke(this, newState);
}
private async Task<IDisposable> AcquireOperationLockNowAsync()
{
var locker = await _operationLock.LockAsync(TimeSpan.Zero);
if (locker == null)
throw new InvalidOperationException("Cannot perform operation while another operation is in progress");
return locker;
}
private void ApplyStatusUpdate(Status status)
{
MutateState(state =>
{
state.VpnLifecycle = status.Lifecycle switch
{
Status.Types.Lifecycle.Unknown => VpnLifecycle.Unknown,
Status.Types.Lifecycle.Starting => VpnLifecycle.Starting,
Status.Types.Lifecycle.Started => VpnLifecycle.Started,
Status.Types.Lifecycle.Stopping => VpnLifecycle.Stopping,
Status.Types.Lifecycle.Stopped => VpnLifecycle.Stopped,
_ => VpnLifecycle.Stopped,
};
state.Workspaces.Clear();
state.Workspaces.AddRange(status.PeerUpdate.UpsertedWorkspaces);
state.Agents.Clear();
state.Agents.AddRange(status.PeerUpdate.UpsertedAgents);
});
}
private void SpeakerOnReceive(ReplyableRpcMessage<ClientMessage, ServiceMessage> message)
{
switch (message.Message.MsgCase)
{
case ServiceMessage.MsgOneofCase.Status:
ApplyStatusUpdate(message.Message.Status);
break;
case ServiceMessage.MsgOneofCase.Start:
case ServiceMessage.MsgOneofCase.Stop:
case ServiceMessage.MsgOneofCase.None:
default:
// TODO: log unexpected message
break;
}
}
private async Task DisposeSpeaker()
{
if (_speaker == null) return;
_speaker.Receive -= SpeakerOnReceive;
_speaker.Error -= SpeakerOnError;
await _speaker.DisposeAsync();
_speaker = null;
}
private void SpeakerOnError(Exception e)
{
Debug.WriteLine($"Error: {e}");
try
{
Reconnect(CancellationToken.None).Wait();
}
catch
{
// best effort to immediately reconnect
}
}
private void AssertRpcConnected()
{
if (_speaker == null)
throw new InvalidOperationException("Not connected to the RPC server");
}
}