-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathJsonRpcTests.cs
More file actions
323 lines (258 loc) · 11.9 KB
/
JsonRpcTests.cs
File metadata and controls
323 lines (258 loc) · 11.9 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
315
316
317
318
319
320
321
322
323
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Xunit;
namespace GitHub.Copilot.Test.Unit;
/// <summary>
/// Behavior tests for the SDK's hand-rolled JSON-RPC transport (params shape, serializer
/// metadata, request/response routing, error propagation). Reflection is used to force
/// every generated <c>JsonSerializable</c> registration on the <see cref="GitHub.Copilot.Rpc.RpcJsonSerializerContext"/>,
/// which guards against regressions in the C# code generator (<c>scripts/codegen/csharp.ts</c>)
/// silently dropping a registration. Functional behavior of individual RPC methods lives
/// in the <c>Rpc*Tests</c> classes; this file owns transport- and serializer-shape concerns.
/// </summary>
public class JsonRpcTests
{
[Fact]
public async Task JsonRpc_Handles_Positional_Named_And_Single_Object_Params()
{
using var pair = JsonRpcReflectionPair.Create();
pair.Server.SetLocalRpcMethod(
"positional",
(Func<string, int, CancellationToken, ValueTask<string>>)HandleNameAndCount);
pair.Server.SetLocalRpcMethod(
"named",
(Func<string, int, CancellationToken, ValueTask<string>>)HandleNameAndCount);
pair.Server.SetLocalRpcMethod(
"single",
(Func<SingleObjectRequest, CancellationToken, ValueTask<SingleObjectResponse>>)HandleSingleObject,
singleObjectParam: true);
pair.StartListening();
Assert.Equal("Mona:2", await pair.Client.InvokeAsync<string>("positional", ["Mona", 2]));
Assert.Equal("Octo:3", await pair.Client.InvokeAsync<string>("named", [new NamedParams { Name = "Octo", Count = 3 }]));
var response = await pair.Client.InvokeAsync<SingleObjectResponse>(
"single",
[new SingleObjectRequest { Value = "value" }]);
Assert.Equal("VALUE", response.Value);
static ValueTask<string> HandleNameAndCount(string name, int count, CancellationToken cancellationToken) =>
ValueTask.FromResult($"{name}:{count}");
static ValueTask<SingleObjectResponse> HandleSingleObject(SingleObjectRequest request, CancellationToken cancellationToken) =>
ValueTask.FromResult(new SingleObjectResponse { Value = request.Value.ToUpperInvariant() });
}
[Fact]
public async Task JsonRpc_Returns_Errors_For_Missing_Method_And_Invalid_Params()
{
using var pair = JsonRpcReflectionPair.Create();
pair.Server.SetLocalRpcMethod(
"single",
(Func<SingleObjectRequest, CancellationToken, ValueTask<SingleObjectResponse>>)HandleSingleObject,
singleObjectParam: true);
pair.StartListening();
var missing = await Assert.ThrowsAnyAsync<Exception>(() =>
pair.Client.InvokeAsync<string>("missing", args: null));
Assert.Contains("Method not found: missing", missing.Message, StringComparison.Ordinal);
Assert.Equal(-32601, GetRemoteErrorCode(missing));
var invalidParams = await Assert.ThrowsAnyAsync<Exception>(() =>
pair.Client.InvokeAsync<SingleObjectResponse>("single", ["not", "an", "object"]));
Assert.Contains("Expected JSON object", invalidParams.Message, StringComparison.Ordinal);
Assert.Equal(-32603, GetRemoteErrorCode(invalidParams));
static ValueTask<SingleObjectResponse> HandleSingleObject(SingleObjectRequest request, CancellationToken cancellationToken) =>
ValueTask.FromResult(new SingleObjectResponse { Value = request.Value });
}
[Fact]
public async Task JsonRpc_Cancels_And_Disposes_Pending_Requests()
{
using var pair = JsonRpcReflectionPair.Create(startServer: false);
using var cts = new CancellationTokenSource();
var canceled = pair.Client.InvokeAsync<string>("never", args: null, cts.Token);
cts.Cancel();
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => canceled);
var pending = pair.Client.InvokeAsync<string>("stillPending", args: null);
pair.Client.Dispose();
await Assert.ThrowsAnyAsync<ObjectDisposedException>(() => pending);
}
private static int GetRemoteErrorCode(Exception exception)
{
var property = exception.GetType().GetProperty("ErrorCode", BindingFlags.Instance | BindingFlags.Public);
Assert.NotNull(property);
return (int)property.GetValue(exception)!;
}
private sealed class NamedParams
{
public string Name { get; set; } = string.Empty;
public int Count { get; set; }
}
private sealed class SingleObjectRequest
{
public string Value { get; set; } = string.Empty;
}
private sealed class SingleObjectResponse
{
public string Value { get; set; } = string.Empty;
}
private sealed class JsonRpcReflectionPair : IDisposable
{
private readonly InMemoryDuplexStream _clientStream;
private readonly InMemoryDuplexStream _serverStream;
private JsonRpcReflectionPair(InMemoryDuplexStream clientStream, InMemoryDuplexStream serverStream)
{
_clientStream = clientStream;
_serverStream = serverStream;
Client = new JsonRpcReflection(clientStream);
Server = new JsonRpcReflection(serverStream);
}
public JsonRpcReflection Client { get; }
public JsonRpcReflection Server { get; }
public static JsonRpcReflectionPair Create(bool startServer = true)
{
var (clientStream, serverStream) = InMemoryDuplexStream.CreatePair();
var pair = new JsonRpcReflectionPair(clientStream, serverStream);
if (startServer)
{
pair.Server.StartListening();
}
return pair;
}
public void StartListening() => Client.StartListening();
public void Dispose()
{
Client.Dispose();
Server.Dispose();
_clientStream.Dispose();
_serverStream.Dispose();
}
}
private sealed class JsonRpcReflection : IDisposable
{
private static readonly Type JsonRpcType =
typeof(CopilotClient).Assembly.GetType("GitHub.Copilot.JsonRpc", throwOnError: true)!;
private static readonly JsonSerializerOptions SerializerOptions = new(JsonSerializerDefaults.Web)
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver(),
};
private readonly object _instance;
public JsonRpcReflection(Stream stream)
{
_instance = Activator.CreateInstance(
JsonRpcType,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
binder: null,
args: [stream, stream, SerializerOptions, null],
culture: null)!;
}
public void StartListening() => JsonRpcType.GetMethod(nameof(StartListening))!.Invoke(_instance, null);
public void SetLocalRpcMethod(string methodName, Delegate handler, bool singleObjectParam = false) =>
JsonRpcType.GetMethod("SetLocalRpcMethod")!.Invoke(_instance, [methodName, handler, singleObjectParam]);
public async Task<T> InvokeAsync<T>(string methodName, object?[]? args, CancellationToken cancellationToken = default)
{
var method = JsonRpcType
.GetMethod("InvokeAsync")!
.MakeGenericMethod(typeof(T));
// Pass null for the optional onResponseInline parameter.
var task = (Task<T>)method.Invoke(_instance, [methodName, args, cancellationToken, null])!;
return await task.ConfigureAwait(false);
}
public void Dispose() => ((IDisposable)_instance).Dispose();
}
private sealed class InMemoryDuplexStream : Stream
{
private readonly Queue<byte> _buffer = new();
private readonly SemaphoreSlim _dataAvailable = new(0);
private readonly object _gate = new();
private InMemoryDuplexStream? _peer;
private bool _completed;
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public static (InMemoryDuplexStream Client, InMemoryDuplexStream Server) CreatePair()
{
var client = new InMemoryDuplexStream();
var server = new InMemoryDuplexStream();
client._peer = server;
server._peer = client;
return (client, server);
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask;
public override int Read(byte[] buffer, int offset, int count) =>
ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
#if NET8_0_OR_GREATER
public override
#else
internal
#endif
async ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default)
{
while (true)
{
lock (_gate)
{
if (_buffer.Count > 0)
{
var bytesRead = Math.Min(destination.Length, _buffer.Count);
var span = destination.Span;
for (var i = 0; i < bytesRead; i++)
{
span[i] = _buffer.Dequeue();
}
return bytesRead;
}
if (_completed)
{
return 0;
}
}
await _dataAvailable.WaitAsync(cancellationToken).ConfigureAwait(false);
}
}
public override void Write(byte[] buffer, int offset, int count) =>
WriteAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult();
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) =>
WriteAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask();
#if NET8_0_OR_GREATER
public override
#else
internal
#endif
ValueTask WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default)
{
var peer = _peer ?? throw new ObjectDisposedException(nameof(InMemoryDuplexStream));
peer.Enqueue(source.Span);
return default;
}
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
protected override void Dispose(bool disposing)
{
if (disposing)
{
lock (_gate)
{
_completed = true;
}
_dataAvailable.Release();
}
base.Dispose(disposing);
}
private void Enqueue(ReadOnlySpan<byte> source)
{
lock (_gate)
{
foreach (var value in source)
{
_buffer.Enqueue(value);
}
}
_dataAvailable.Release();
}
}
}