-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathClientSessionLifetimeTests.cs
More file actions
809 lines (682 loc) · 29.8 KB
/
Copy pathClientSessionLifetimeTests.cs
File metadata and controls
809 lines (682 loc) · 29.8 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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------------------------------------------*/
#if NET8_0_OR_GREATER
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using Xunit;
namespace GitHub.Copilot.Test.Unit;
public sealed class ClientSessionLifetimeTests
{
private sealed record RpcRequestRecord(string Method, JsonElement Params);
[Fact]
public async Task StopAsync_Requests_Runtime_Shutdown_For_Owned_Process()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
await client.StartAsync();
using var process = StartExitedProcess();
await ReplaceConnectionCliProcessAsync(client, process);
await client.StopAsync();
Assert.Equal(1, server.RuntimeShutdownCount);
}
[Fact]
public async Task DisposeAsync_Requests_Runtime_Shutdown_For_Owned_Process()
{
await using var server = await FakeCopilotServer.StartAsync();
var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
await client.StartAsync();
using var process = StartExitedProcess();
await ReplaceConnectionCliProcessAsync(client, process);
await client.DisposeAsync();
Assert.Equal(1, server.RuntimeShutdownCount);
}
[Fact]
public async Task StopAsync_Does_Not_Throw_When_Runtime_Shutdown_Fails()
{
await using var server = await FakeCopilotServer.StartAsync();
server.FailRuntimeShutdown();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
await client.StartAsync();
using var process = StartExitedProcess();
await ReplaceConnectionCliProcessAsync(client, process);
await client.StopAsync();
Assert.Equal(1, server.RuntimeShutdownCount);
}
[Fact]
public async Task ForceStopAsync_And_External_Stop_Do_Not_Request_Runtime_Shutdown()
{
await using var forceServer = await FakeCopilotServer.StartAsync();
await using var forceClient = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(forceServer.Url) });
await forceClient.StartAsync();
using var process = StartExitedProcess();
await ReplaceConnectionCliProcessAsync(forceClient, process);
await forceClient.ForceStopAsync();
Assert.Equal(0, forceServer.RuntimeShutdownCount);
await using var externalServer = await FakeCopilotServer.StartAsync();
await using var externalClient = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(externalServer.Url) });
await externalClient.StartAsync();
await externalClient.StopAsync();
Assert.Equal(0, externalServer.RuntimeShutdownCount);
}
[Fact]
public async Task Dropped_Session_Remains_Rooted_By_Client()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
var weakSession = await CreateDroppedSessionAsync(client);
ForceCollect();
Assert.True(
weakSession.TryGetTarget(out _),
"CopilotClient should root created sessions until they are explicitly disposed or the client stops.");
AssertSessionCount(client, sessions: 1);
GC.KeepAlive(client);
}
[Fact]
public async Task Disposed_Session_Is_Removed_From_Client()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll
});
AssertSessionCount(client, sessions: 1);
await session.DisposeAsync();
AssertSessionCount(client, sessions: 0);
}
[Fact]
public async Task Disposing_Session_Remains_Rooted_Until_Destroy_Completes()
{
await using var server = await FakeCopilotServer.StartAsync();
server.DelayDestroy();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll
});
AssertSessionCount(client, sessions: 1);
var disposeTask = session.DisposeAsync().AsTask();
await server.DestroyStarted;
AssertSessionCount(client, sessions: 1);
server.CompleteDestroy();
await disposeTask;
AssertSessionCount(client, sessions: 0);
}
[Fact]
public async Task StopAsync_Removes_Rooted_Sessions()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
_ = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll
});
AssertSessionCount(client, sessions: 1);
await client.StopAsync();
AssertSessionCount(client, sessions: 0);
}
[Fact]
public async Task StopAsync_Keeps_Session_Rooted_Until_Destroy_Completes()
{
await using var server = await FakeCopilotServer.StartAsync();
server.DelayDestroy();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
_ = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll
});
AssertSessionCount(client, sessions: 1);
var stopTask = client.StopAsync();
await server.DestroyStarted;
AssertSessionCount(client, sessions: 1);
server.CompleteDestroy();
await stopTask;
AssertSessionCount(client, sessions: 0);
}
[Fact]
public async Task ResumeSessionAsync_Throws_When_Same_Client_Already_Tracks_Session()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
var sessionId = "same-session-id";
await using var session = await client.CreateSessionAsync(new SessionConfig
{
SessionId = sessionId,
OnPermissionRequest = PermissionHandler.ApproveAll
});
AssertSessionCount(client, sessions: 1);
var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => client.ResumeSessionAsync(sessionId, new ResumeSessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll
}));
Assert.Contains(sessionId, exception.Message);
AssertSessionCount(client, sessions: 1);
}
[Fact]
public async Task CreateSessionAsync_Registers_McpAuth_Interest_Only_When_Handler_Configured()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
await using var withoutAuth = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
OnEvent = _ => { }
});
Assert.DoesNotContain(server.Requests, request =>
request.Method == "session.eventLog.registerInterest"
&& request.Params.GetProperty("eventType").GetString() == "mcp.oauth_required");
Assert.Contains(server.Requests, request =>
request.Method == "session.create"
&& request.Params.GetProperty("requestPermission").GetBoolean());
server.ClearRequests();
await using var withAuth = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
OnMcpAuthRequest = _ => Task.FromResult<McpAuthResult?>(McpAuthResult.Cancel())
});
Assert.Collection(
server.Requests.Take(2),
request => Assert.Equal("session.create", request.Method),
request =>
{
Assert.Equal("session.eventLog.registerInterest", request.Method);
Assert.Equal("mcp.oauth_required", request.Params.GetProperty("eventType").GetString());
});
}
[Fact]
public async Task CreateSessionAsync_Registers_McpAuth_Interest_After_Cloud_Create_When_Handler_Configured()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
var cloud = new CloudSessionOptions
{
Repository = new CloudSessionRepository
{
Owner = "github",
Name = "copilot-sdk",
Branch = "main"
}
};
await using var withoutAuth = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
Cloud = cloud
});
Assert.DoesNotContain(server.Requests, request =>
request.Method == "session.eventLog.registerInterest"
&& request.Params.GetProperty("eventType").GetString() == "mcp.oauth_required");
server.ClearRequests();
await using var withAuth = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
OnMcpAuthRequest = _ => Task.FromResult<McpAuthResult?>(McpAuthResult.Cancel()),
Cloud = cloud
});
Assert.Collection(
server.Requests.Take(2),
request => Assert.Equal("session.create", request.Method),
request =>
{
Assert.Equal("session.eventLog.registerInterest", request.Method);
Assert.Equal("mcp.oauth_required", request.Params.GetProperty("eventType").GetString());
});
}
[Fact]
public async Task ResumeSessionAsync_Registers_McpAuth_Interest_Only_When_Handler_Configured()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
await using var withoutAuth = await client.ResumeSessionAsync("session-without-auth", new ResumeSessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
OnEvent = _ => { }
});
Assert.DoesNotContain(server.Requests, request =>
request.Method == "session.eventLog.registerInterest"
&& request.Params.GetProperty("eventType").GetString() == "mcp.oauth_required");
Assert.Contains(server.Requests, request =>
request.Method == "session.resume"
&& request.Params.GetProperty("requestPermission").GetBoolean());
server.ClearRequests();
await using var withAuth = await client.ResumeSessionAsync("session-with-auth", new ResumeSessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
OnMcpAuthRequest = _ => Task.FromResult<McpAuthResult?>(McpAuthResult.Cancel())
});
Assert.Collection(
server.Requests.Take(2),
request => Assert.Equal("session.resume", request.Method),
request =>
{
Assert.Equal("session.eventLog.registerInterest", request.Method);
Assert.Equal("mcp.oauth_required", request.Params.GetProperty("eventType").GetString());
});
}
[Fact]
public async Task McpAuth_Handler_Exception_Cancels_Pending_Request()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
await using var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll,
OnMcpAuthRequest = _ => throw new ApplicationException("boom")
});
DispatchEvent(session, new McpOauthRequiredEvent
{
Data = new McpOauthRequiredData
{
RequestId = "mcp-auth-request-1",
ServerName = "oauth-mcp",
ServerUrl = "http://localhost/mcp",
Reason = McpOauthRequestReason.Initial
}
});
var request = await WaitForRequestAsync(server, "session.mcp.oauth.handlePendingRequest");
Assert.Equal("mcp-auth-request-1", request.Params.GetProperty("requestId").GetString());
Assert.Equal("cancelled", request.Params.GetProperty("result").GetProperty("kind").GetString());
}
[Fact]
public async Task Generated_Session_Rpc_Throws_When_Session_Disposed()
{
await using var server = await FakeCopilotServer.StartAsync();
await using var client = new CopilotClient(new CopilotClientOptions { Connection = RuntimeConnection.ForUri(server.Url) });
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll
});
await session.DisposeAsync();
await Assert.ThrowsAsync<ObjectDisposedException>(() => session.Rpc.Model.GetCurrentAsync());
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static async Task<WeakReference<CopilotSession>> CreateDroppedSessionAsync(CopilotClient client)
{
var session = await client.CreateSessionAsync(new SessionConfig
{
OnPermissionRequest = PermissionHandler.ApproveAll
});
return new WeakReference<CopilotSession>(session);
}
private static void ForceCollect()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
private static void AssertSessionCount(CopilotClient client, int sessions)
{
Assert.Equal(sessions, GetPrivateDictionaryCount(client, "_sessions"));
}
private static int GetPrivateDictionaryCount(CopilotClient client, string fieldName)
{
var field = typeof(CopilotClient).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException($"Field '{fieldName}' was not found.");
var dictionary = field.GetValue(client)
?? throw new InvalidOperationException($"Field '{fieldName}' was null.");
var count = dictionary.GetType().GetProperty("Count")
?? throw new InvalidOperationException($"Field '{fieldName}' does not expose Count.");
return (int)count.GetValue(dictionary)!;
}
private static void DispatchEvent(CopilotSession session, SessionEvent evt)
{
var method = typeof(CopilotSession).GetMethod("DispatchEvent", BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException("DispatchEvent method was not found.");
method.Invoke(session, [evt]);
}
private static async Task<RpcRequestRecord> WaitForRequestAsync(FakeCopilotServer server, string method)
{
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
while (!timeout.IsCancellationRequested)
{
var request = server.Requests.FirstOrDefault(request => request.Method == method);
if (request is not null)
{
return request;
}
await Task.Delay(20, CancellationToken.None);
}
throw new TimeoutException($"Timed out waiting for RPC method '{method}'.");
}
private static async Task ReplaceConnectionCliProcessAsync(CopilotClient client, Process process)
{
var field = typeof(CopilotClient).GetField("_connectionTask", BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException("_connectionTask field was not found.");
var connectionTask = (Task)field.GetValue(client)!;
await connectionTask;
var resultProperty = connectionTask.GetType().GetProperty(nameof(Task<object>.Result))
?? throw new InvalidOperationException("Connection task result property was not found.");
var connection = resultProperty.GetValue(connectionTask)!;
var connectionType = connection.GetType();
var rpc = connectionType.GetProperty("Rpc")!.GetValue(connection);
var networkStream = connectionType.GetProperty("NetworkStream")!.GetValue(connection);
var constructor = connectionType.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).Single();
var updatedConnection = constructor.Invoke([rpc, process, networkStream, null, null]);
var fromResult = typeof(Task).GetMethod(nameof(Task.FromResult))!.MakeGenericMethod(connectionType);
field.SetValue(client, fromResult.Invoke(null, [updatedConnection]));
}
private static Process StartExitedProcess()
{
var startInfo = OperatingSystem.IsWindows()
? new ProcessStartInfo(Environment.GetEnvironmentVariable("COMSPEC") ?? "cmd.exe", "/c exit 0")
: new ProcessStartInfo("/bin/sh", "-c \"exit 0\"");
startInfo.UseShellExecute = false;
var process = Process.Start(startInfo)
?? throw new InvalidOperationException("Failed to start test process.");
process.WaitForExit();
return process;
}
private sealed class FakeCopilotServer : IAsyncDisposable
{
private readonly TcpListener _listener;
private readonly CancellationTokenSource _cts = new();
private readonly SemaphoreSlim _writeLock = new(1, 1);
private readonly TaskCompletionSource _destroyStarted = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource _allowDestroy = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly Task _serverTask;
private readonly List<RpcRequestRecord> _requests = [];
private readonly object _requestsLock = new();
private string? _lastSessionId;
private bool _delayDestroy;
private bool _failRuntimeShutdown;
private FakeCopilotServer(TcpListener listener)
{
_listener = listener;
_serverTask = RunAsync();
}
public string Url
{
get
{
var endpoint = (IPEndPoint)_listener.LocalEndpoint;
return $"http://127.0.0.1:{endpoint.Port}";
}
}
public static Task<FakeCopilotServer> StartAsync()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
return Task.FromResult(new FakeCopilotServer(listener));
}
public Task DestroyStarted => _destroyStarted.Task;
public int RuntimeShutdownCount { get; private set; }
public IReadOnlyList<RpcRequestRecord> Requests
{
get
{
lock (_requestsLock)
{
return _requests.ToArray();
}
}
}
public void ClearRequests()
{
lock (_requestsLock)
{
_requests.Clear();
}
}
public void DelayDestroy()
{
_delayDestroy = true;
}
public void CompleteDestroy()
{
_allowDestroy.TrySetResult();
}
public void FailRuntimeShutdown()
{
_failRuntimeShutdown = true;
}
public async ValueTask DisposeAsync()
{
_allowDestroy.TrySetResult();
_cts.Cancel();
_listener.Stop();
try
{
await _serverTask;
}
catch (Exception ex) when (ex is OperationCanceledException or ObjectDisposedException or IOException or SocketException)
{
}
_cts.Dispose();
_writeLock.Dispose();
}
private async Task RunAsync()
{
using var tcpClient = await _listener.AcceptTcpClientAsync(_cts.Token);
using var stream = tcpClient.GetStream();
while (!_cts.Token.IsCancellationRequested)
{
using var request = await ReadMessageAsync(stream, _cts.Token);
if (request is null)
{
return;
}
await HandleRequestAsync(stream, request.RootElement, _cts.Token);
}
}
private async Task HandleRequestAsync(Stream stream, JsonElement request, CancellationToken cancellationToken)
{
if (!request.TryGetProperty("id", out var idElement))
{
return;
}
var id = idElement.Clone();
var method = request.GetProperty("method").GetString();
if (method == "runtime.shutdown" && _failRuntimeShutdown)
{
RuntimeShutdownCount++;
await WriteMessageAsync(stream, new Dictionary<string, object?>
{
["jsonrpc"] = "2.0",
["id"] = id,
["error"] = new Dictionary<string, object?>
{
["code"] = -32000,
["message"] = "runtime shutdown failed"
}
}, cancellationToken);
return;
}
var paramsElement = request.TryGetProperty("params", out var rawParams)
? rawParams.Clone()
: JsonDocument.Parse("{}").RootElement.Clone();
lock (_requestsLock)
{
_requests.Add(new RpcRequestRecord(method!, paramsElement));
}
object? result = method switch
{
"connect" => new Dictionary<string, object?>
{
["ok"] = true,
["protocolVersion"] = 3,
["version"] = "test"
},
"session.create" => CreateSessionResult(request),
"session.resume" => CreateSessionResult(request),
"session.eventLog.registerInterest" => new Dictionary<string, object?>
{
["id"] = "interest-1"
},
"session.send" => new Dictionary<string, object?>
{
["messageId"] = "message-1"
},
"session.mcp.oauth.handlePendingRequest" => new Dictionary<string, object?>
{
["success"] = true
},
"session.delete" => new Dictionary<string, object?>
{
["success"] = true
},
"session.destroy" => await DestroySessionAsync(cancellationToken),
"runtime.shutdown" => HandleRuntimeShutdown(),
_ => throw new InvalidOperationException($"Unexpected RPC method '{method}'.")
};
await WriteMessageAsync(stream, new Dictionary<string, object?>
{
["jsonrpc"] = "2.0",
["id"] = id,
["result"] = result
}, cancellationToken);
}
private Dictionary<string, object?> CreateSessionResult(JsonElement request)
{
string? sessionId = null;
if (request.TryGetProperty("params", out var paramsProp)
&& paramsProp.ValueKind == JsonValueKind.Object
&& paramsProp.TryGetProperty("sessionId", out var sidProp)
&& sidProp.ValueKind == JsonValueKind.String)
{
sessionId = sidProp.GetString();
}
if (string.IsNullOrEmpty(sessionId))
{
sessionId = Guid.NewGuid().ToString();
}
_lastSessionId = sessionId;
return new Dictionary<string, object?>
{
["sessionId"] = _lastSessionId,
["workspacePath"] = null,
["capabilities"] = null
};
}
private async Task<Dictionary<string, object?>> DestroySessionAsync(CancellationToken cancellationToken)
{
if (_delayDestroy)
{
_destroyStarted.TrySetResult();
await _allowDestroy.Task.WaitAsync(cancellationToken);
}
return [];
}
private Dictionary<string, object?> HandleRuntimeShutdown()
{
RuntimeShutdownCount++;
return [];
}
private async Task WriteMessageAsync(Stream stream, object payload, CancellationToken cancellationToken)
{
using var bodyStream = new MemoryStream();
using (var writer = new Utf8JsonWriter(bodyStream))
{
WriteJsonValue(writer, payload);
}
var body = bodyStream.ToArray();
var header = Encoding.ASCII.GetBytes($"Content-Length: {body.Length}\r\n\r\n");
await _writeLock.WaitAsync(cancellationToken);
try
{
await stream.WriteAsync(header, cancellationToken);
await stream.WriteAsync(body, cancellationToken);
await stream.FlushAsync(cancellationToken);
}
finally
{
_writeLock.Release();
}
}
private static void WriteJsonValue(Utf8JsonWriter writer, object? value)
{
switch (value)
{
case null:
writer.WriteNullValue();
break;
case string stringValue:
writer.WriteStringValue(stringValue);
break;
case bool boolValue:
writer.WriteBooleanValue(boolValue);
break;
case int intValue:
writer.WriteNumberValue(intValue);
break;
case long longValue:
writer.WriteNumberValue(longValue);
break;
case JsonElement jsonElement:
jsonElement.WriteTo(writer);
break;
case Dictionary<string, object?> dictionary:
writer.WriteStartObject();
foreach (var (propertyName, propertyValue) in dictionary)
{
writer.WritePropertyName(propertyName);
WriteJsonValue(writer, propertyValue);
}
writer.WriteEndObject();
break;
case object?[] array:
writer.WriteStartArray();
foreach (var item in array)
{
WriteJsonValue(writer, item);
}
writer.WriteEndArray();
break;
default:
throw new InvalidOperationException($"Unexpected JSON value type '{value.GetType().Name}'.");
}
}
private static async Task<JsonDocument?> ReadMessageAsync(Stream stream, CancellationToken cancellationToken)
{
var headerBytes = new List<byte>();
while (true)
{
var value = await ReadByteAsync(stream, cancellationToken);
if (value < 0)
{
return null;
}
headerBytes.Add((byte)value);
var count = headerBytes.Count;
if (count >= 4 &&
headerBytes[count - 4] == '\r' &&
headerBytes[count - 3] == '\n' &&
headerBytes[count - 2] == '\r' &&
headerBytes[count - 1] == '\n')
{
break;
}
}
var header = Encoding.ASCII.GetString([.. headerBytes]);
var contentLength = header
.Split(["\r\n"], StringSplitOptions.RemoveEmptyEntries)
.Select(line => line.Split(':', 2))
.Where(parts => parts.Length == 2 && parts[0].Equals("Content-Length", StringComparison.OrdinalIgnoreCase))
.Select(parts => int.Parse(parts[1].Trim(), System.Globalization.CultureInfo.InvariantCulture))
.Single();
var body = new byte[contentLength];
var offset = 0;
while (offset < body.Length)
{
var read = await stream.ReadAsync(body.AsMemory(offset, body.Length - offset), cancellationToken);
if (read == 0)
{
return null;
}
offset += read;
}
return JsonDocument.Parse(body);
}
private static async Task<int> ReadByteAsync(Stream stream, CancellationToken cancellationToken)
{
var buffer = new byte[1];
var read = await stream.ReadAsync(buffer, cancellationToken);
return read == 0 ? -1 : buffer[0];
}
}
}
#endif