-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
Copy pathHttpClientHandlerTest.Http3.cs
1834 lines (1501 loc) · 76.8 KB
/
HttpClientHandlerTest.Http3.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
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Quic;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Reflection;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
[Collection(nameof(DisableParallelization))]
[ConditionalClass(typeof(HttpClientHandlerTestBase), nameof(IsQuicSupported))]
public sealed class HttpClientHandlerTest_Http3 : HttpClientHandlerTestBase
{
protected override Version UseVersion => HttpVersion.Version30;
public HttpClientHandlerTest_Http3(ITestOutputHelper output) : base(output)
{
}
private async Task AssertProtocolErrorAsync(long errorCode, Func<Task> task)
{
Exception outerEx = await Assert.ThrowsAnyAsync<Exception>(task);
_output.WriteLine(outerEx.ToString());
Assert.IsType<HttpRequestException>(outerEx);
HttpProtocolException protocolEx = Assert.IsType<HttpProtocolException>(outerEx.InnerException);
Assert.Equal(errorCode, protocolEx.ErrorCode);
}
[Theory]
[InlineData(10, 10240)] // 2 bytes settings value.
[InlineData(100, 102400)] // 4 bytes settings value.
[InlineData(10_000_000, int.MaxValue)] // 8 bytes settings value.
public async Task ClientSettingsReceived_Success(int headerSizeLimit, int expectedHeaderSizeLimitBytes)
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
(Http3LoopbackStream settingsStream, Http3LoopbackStream requestStream) = await connection.AcceptControlAndRequestStreamAsync();
await using (settingsStream)
await using (requestStream)
{
Assert.False(settingsStream.CanWrite, "Expected unidirectional control stream.");
Assert.Equal(expectedHeaderSizeLimitBytes, connection.MaxHeaderListSize);
await requestStream.ReadRequestDataAsync();
await requestStream.SendResponseAsync();
}
});
Task clientTask = Task.Run(async () =>
{
using HttpClientHandler handler = CreateHttpClientHandler();
handler.MaxResponseHeadersLength = headerSizeLimit;
using HttpClient client = CreateHttpClient(handler);
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
using HttpResponseMessage response = await client.SendAsync(request);
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public async Task SendMoreThanStreamLimitRequests_Succeeds(int streamLimit)
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer(new Http3Options() { MaxInboundBidirectionalStreams = streamLimit });
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
for (int i = 0; i < streamLimit + 1; ++i)
{
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
await stream.HandleRequestAsync();
}
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
for (int i = 0; i < streamLimit + 1; ++i)
{
HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
using var response = await client.SendAsync(request).WaitAsync(TimeSpan.FromSeconds(10));
}
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public async Task SendStreamLimitRequestsConcurrently_Succeeds(int streamLimit)
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer(new Http3Options() { MaxInboundBidirectionalStreams = streamLimit });
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
for (int i = 0; i < streamLimit; ++i)
{
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
await stream.HandleRequestAsync();
}
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
var tasks = new Task<HttpResponseMessage>[streamLimit];
Parallel.For(0, streamLimit, i =>
{
HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
tasks[i] = client.SendAsync(request);
});
var responses = await Task.WhenAll(tasks);
foreach (var response in responses)
{
response.Dispose();
}
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Theory]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public async Task SendMoreThanStreamLimitRequestsConcurrently_LastWaits(int streamLimit)
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer(new Http3Options() { MaxInboundBidirectionalStreams = streamLimit });
var lastRequestContentStarted = new TaskCompletionSource();
Task serverTask = Task.Run(async () =>
{
// Read the first streamLimit requests, keep the streams open to make the last one wait.
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
var streams = new Http3LoopbackStream[streamLimit];
for (int i = 0; i < streamLimit; ++i)
{
Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
var body = await stream.ReadRequestDataAsync();
streams[i] = stream;
}
// Make the last request running independently.
var lastRequest = Task.Run(async () =>
{
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
await stream.HandleRequestAsync();
});
// All the initial streamLimit streams are still opened so the last request cannot started yet.
Assert.False(lastRequestContentStarted.Task.IsCompleted);
// Reply to the first streamLimit requests.
for (int i = 0; i < streamLimit; ++i)
{
await streams[i].SendResponseAsync();
await streams[i].DisposeAsync();
// After the first request is fully processed, the last request should unblock and get processed.
if (i == 0)
{
await lastRequestContentStarted.Task;
}
}
await lastRequest;
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
// Fire out the first streamLimit requests in parallel, no waiting for the responses yet.
var countdown = new CountdownEvent(streamLimit);
var tasks = new Task<HttpResponseMessage>[streamLimit];
Parallel.For(0, streamLimit, i =>
{
HttpRequestMessage request = new()
{
Method = HttpMethod.Post,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact,
Content = new StreamContent(new DelegateStream(
canReadFunc: () => true,
readFunc: (buffer, offset, count) =>
{
countdown.Signal();
return 0;
}))
};
tasks[i] = client.SendAsync(request);
});
// Wait for the first streamLimit request to get started.
countdown.Wait();
// Fire out the last request, that should wait until the server fully handles at least one request.
HttpRequestMessage last = new()
{
Method = HttpMethod.Post,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact,
Content = new StreamContent(new DelegateStream(
canReadFunc: () => true,
readFunc: (buffer, offset, count) =>
{
lastRequestContentStarted.SetResult();
return 0;
}))
};
var lastTask = client.SendAsync(last);
// Wait for all requests to finish. Whether the last request was pending is checked on the server side.
var responses = await Task.WhenAll(tasks);
foreach (var response in responses)
{
response.Dispose();
}
await lastTask;
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task ReservedFrameType_Throws()
{
const int ReservedHttp2PriorityFrameId = 0x2;
const long UnexpectedFrameErrorCode = 0x105;
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
QuicException ex = await AssertThrowsQuicExceptionAsync(QuicError.ConnectionAborted, async () =>
{
await stream.SendFrameAsync(ReservedHttp2PriorityFrameId, new byte[8]);
await stream.HandleRequestAsync();
await using Http3LoopbackStream stream2 = await connection.AcceptRequestStreamAsync();
});
Assert.Equal(UnexpectedFrameErrorCode, ex.ApplicationErrorCode);
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
await AssertProtocolErrorAsync(UnexpectedFrameErrorCode, () => client.SendAsync(request));
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task ServerClosesConnection_ThrowsHttpProtocolException()
{
const long GeneralProtocolError = 0x101;
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
await connection.CloseAsync(GeneralProtocolError);
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
await AssertProtocolErrorAsync(GeneralProtocolError, () => client.SendAsync(request));
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task ServerClosesStream_ThrowsHttpProtocolException()
{
// normally, the server should not use this code when resetting the stream, but we should still check if we behave sanely...
const long GeneralProtocolError = 0x101;
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
SemaphoreSlim semaphore = new SemaphoreSlim(0);
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
stream.Abort(GeneralProtocolError);
await semaphore.WaitAsync();
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
await AssertProtocolErrorAsync(GeneralProtocolError, () => client.SendAsync(request));
semaphore.Release();
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task SendAsync_RequestRejected_ClientRetries()
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
Task serverTask = Task.Run(async () =>
{
await using (Http3LoopbackConnection connection1 = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync())
{
await using Http3LoopbackStream stream = await connection1.AcceptRequestStreamAsync();
stream.Abort(0x10B); // H3_REQUEST_REJECTED
await stream.DisposeAsync();
// shutdown the connection gracefully via GOAWAY frame for good measure
await connection1.ShutdownAsync(true);
}
// expect second connection to be established by the client
await using (Http3LoopbackConnection connection2 = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync())
{
await using Http3LoopbackStream stream = await connection2.AcceptRequestStreamAsync();
await stream.HandleRequestAsync();
}
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task ServerClosesConnection_ResponseContentStream_ThrowsHttpProtocolException()
{
const long GeneralProtocolError = 0x101;
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
SemaphoreSlim semaphore = new SemaphoreSlim(0);
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
await stream.ReadRequestBodyAsync();
await stream.SendResponseHeadersAsync();
await stream.SendDataFrameAsync(new byte[1024]);
await semaphore.WaitAsync();
await connection.CloseAsync(GeneralProtocolError);
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var stream = await response.Content.ReadAsStreamAsync();
await stream.ReadAsync(new byte[1024]);
semaphore.Release();
var ex = await Assert.ThrowsAsync<HttpProtocolException>(async () => await stream.ReadAsync(new byte[1024]));
Assert.Equal(GeneralProtocolError, ex.ErrorCode);
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task RequestSentResponseDisposed_ThrowsOnServer()
{
byte[] data = Encoding.UTF8.GetBytes(new string('a', 1024));
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
HttpRequestData request = await stream.ReadRequestDataAsync();
await stream.SendResponseHeadersAsync();
Stopwatch sw = Stopwatch.StartNew();
bool hasFailed = false;
while (sw.Elapsed < TimeSpan.FromSeconds(15))
{
try
{
await stream.SendResponseBodyAsync(data, isFinal: false);
}
catch (QuicException ex) when (ex.QuicError == QuicError.StreamAborted)
{
hasFailed = true;
break;
}
}
Assert.True(hasFailed, $"Expected {nameof(QuicException)} with {nameof(QuicError.StreamAborted)}, instead ran successfully for {sw.Elapsed}");
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var stream = await response.Content.ReadAsStreamAsync();
byte[] buffer = new byte[512];
for (int i = 0; i < 5; ++i)
{
var count = await stream.ReadAsync(buffer);
}
// We haven't finished reading the whole respose, but we're disposing it, which should turn into an exception on the server-side.
response.Dispose();
await serverTask;
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task RequestSendingResponseDisposed_ThrowsOnServer()
{
byte[] data = Encoding.UTF8.GetBytes(new string('a', 1024));
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
HttpRequestData request = await stream.ReadRequestDataAsync(false);
await stream.SendResponseHeadersAsync();
Stopwatch sw = Stopwatch.StartNew();
bool hasFailed = false;
while (sw.Elapsed < TimeSpan.FromSeconds(15))
{
try
{
var (frameType, payload) = await stream.ReadFrameAsync();
Assert.Equal(Http3LoopbackStream.DataFrame, frameType);
}
catch (QuicException ex) when (ex.QuicError == QuicError.StreamAborted)
{
hasFailed = true;
break;
}
}
Assert.True(hasFailed, $"Expected {nameof(QuicException)} with {nameof(QuicError.StreamAborted)}, instead ran successfully for {sw.Elapsed}");
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact,
Content = new ByteAtATimeContent(60 * 4, Task.CompletedTask, new TaskCompletionSource<bool>(), 250)
};
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var stream = await response.Content.ReadAsStreamAsync();
// We haven't finished sending the whole request, but we're disposing the response, which should turn into an exception on the server-side.
response.Dispose();
await serverTask;
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task ServerCertificateCustomValidationCallback_Succeeds()
{
HttpRequestMessage? callbackRequest = null;
int invocationCount = 0;
var httpClientHandler = CreateHttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (request, _, _, _) =>
{
callbackRequest = request;
++invocationCount;
return true;
};
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
using HttpClient client = CreateHttpClient(httpClientHandler);
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
await stream.HandleRequestAsync();
await using Http3LoopbackStream stream2 = await connection.AcceptRequestStreamAsync();
await stream2.HandleRequestAsync();
});
var request = new HttpRequestMessage(HttpMethod.Get, server.Address);
request.Version = HttpVersion.Version30;
request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpVersion.Version30, response.Version);
Assert.Same(request, callbackRequest);
Assert.Equal(1, invocationCount);
// Second request, the callback shouldn't be hit at all.
callbackRequest = null;
request = new HttpRequestMessage(HttpMethod.Get, server.Address);
request.Version = HttpVersion.Version30;
request.VersionPolicy = HttpVersionPolicy.RequestVersionExact;
response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Assert.Equal(HttpVersion.Version30, response.Version);
Assert.Null(callbackRequest);
Assert.Equal(1, invocationCount);
await serverTask;
}
[Fact]
public async Task EmptyCustomContent_FlushHeaders()
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
TaskCompletionSource headersReceived = new TaskCompletionSource();
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
// Receive headers and unblock the client.
await stream.ReadRequestDataAsync(false);
headersReceived.SetResult();
await stream.ReadRequestBodyAsync();
await stream.SendResponseAsync();
});
Task clientTask = Task.Run(async () =>
{
StreamingHttpContent requestContent = new StreamingHttpContent();
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Post,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact,
Content = requestContent
};
Task<HttpResponseMessage> responseTask = client.SendAsync(request);
Stream requestStream = await requestContent.GetStreamAsync();
await requestStream.FlushAsync();
await headersReceived.Task;
requestContent.CompleteStream();
using HttpResponseMessage response = await responseTask;
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task DisposeHttpClient_Http3ConnectionIsClosed()
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
HttpRequestData request = await connection.ReadRequestDataAsync();
await connection.SendResponseAsync();
await connection.WaitForClientDisconnectAsync(refuseNewRequests: false);
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
using HttpResponseMessage response = await client.SendAsync(request);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Return and let the HttpClient be disposed
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[OuterLoop]
[Theory]
[MemberData(nameof(InteropUris))]
public async Task Public_Interop_ExactVersion_Success(string uri)
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(uri, UriKind.Absolute),
Version = HttpVersion.Version30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
using HttpResponseMessage response = await client.SendAsync(request).WaitAsync(TimeSpan.FromSeconds(20));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(3, response.Version.Major);
}
[OuterLoop]
[Theory]
[MemberData(nameof(InteropUrisWithContent))]
public async Task Public_Interop_ExactVersion_BufferContent_Success(string uri)
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(uri, UriKind.Absolute),
Version = HttpVersion.Version30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
using HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseContentRead).WaitAsync(TimeSpan.FromSeconds(20));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(3, response.Version.Major);
var content = await response.Content.ReadAsStringAsync();
Assert.NotEmpty(content);
}
[Theory]
[OuterLoop]
[MemberData(nameof(InteropUris))]
public Task Public_Interop_Upgrade_Request3OrLower_Success(string uri)
{
return Public_Interop_Upgrade_Core(uri, HttpVersion.Version30, HttpVersionPolicy.RequestVersionOrLower);
}
[Theory]
[OuterLoop]
[MemberData(nameof(InteropUris))]
public Task Public_Interop_Upgrade_Request2OrHigher_Success(string uri)
{
return Public_Interop_Upgrade_Core(uri, HttpVersion.Version20, HttpVersionPolicy.RequestVersionOrHigher);
}
private async Task Public_Interop_Upgrade_Core(string uri, Version requestVersion, HttpVersionPolicy policy)
{
// Create the handler manually without passing in useVersion = Http3 to avoid using VersionHttpClientHandler,
// because it overrides VersionPolicy on each request with RequestVersionExact (bypassing Alt-Svc code path completely).
using HttpClient client = CreateHttpClient(CreateHttpClientHandler(useVersion: null));
// First request uses HTTP/1 or HTTP/2 and receives an Alt-Svc either by header or (with HTTP/2) by frame.
using (HttpRequestMessage requestA = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(uri, UriKind.Absolute),
Version = requestVersion,
VersionPolicy = policy
})
{
try
{
using HttpResponseMessage responseA = await client.SendAsync(requestA).WaitAsync(TimeSpan.FromSeconds(20));
Assert.Equal(HttpStatusCode.OK, responseA.StatusCode);
Assert.NotEqual(3, responseA.Version.Major);
}
catch (TimeoutException ex)
{
_output.WriteLine($"Unable to establish non-H/3 connection to {uri}: {ex}");
return;
}
catch (HttpRequestException ex) when
(ex.InnerException is SocketException se &&
(se.SocketErrorCode == SocketError.NetworkUnreachable || se.SocketErrorCode == SocketError.HostUnreachable || se.SocketErrorCode == SocketError.ConnectionRefused))
{
_output.WriteLine($"Unable to establish non-H/3 connection to {uri}: {ex}");
return;
}
}
// Second request uses HTTP/3.
using (HttpRequestMessage requestB = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(uri, UriKind.Absolute),
Version = requestVersion,
VersionPolicy = policy
})
{
using HttpResponseMessage responseB = await client.SendAsync(requestB).WaitAsync(TimeSpan.FromSeconds(20));
Assert.Equal(HttpStatusCode.OK, responseB.StatusCode);
Assert.Equal(3, responseB.Version.Major);
}
}
public enum CancellationType
{
Dispose,
CancellationToken
}
[Theory]
[InlineData(CancellationType.Dispose)]
[InlineData(CancellationType.CancellationToken)]
public async Task ResponseCancellation_ServerReceivesCancellation(CancellationType type)
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
using var clientDone = new SemaphoreSlim(0);
using var serverDone = new SemaphoreSlim(0);
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
HttpRequestData request = await stream.ReadRequestDataAsync().ConfigureAwait(false);
int contentLength = 2 * 1024 * 1024;
var headers = new List<HttpHeaderData>();
headers.Append(new HttpHeaderData("Content-Length", contentLength.ToString(CultureInfo.InvariantCulture)));
await stream.SendResponseHeadersAsync(HttpStatusCode.OK, headers).ConfigureAwait(false);
await stream.SendDataFrameAsync(new byte[1024]).ConfigureAwait(false);
await clientDone.WaitAsync();
// It is possible that PEER_RECEIVE_ABORTED event will arrive with a significant delay after peer calls AbortReceive
// In that case even with synchronization via semaphores, first writes after peer aborting may "succeed" (get SEND_COMPLETE event)
// We are asserting that PEER_RECEIVE_ABORTED would still arrive eventually
var ex = await AssertThrowsQuicExceptionAsync(QuicError.StreamAborted, () => SendDataForever(stream).WaitAsync(TimeSpan.FromSeconds(10)));
Assert.Equal(268, ex.ApplicationErrorCode);
serverDone.Release();
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).WaitAsync(TimeSpan.FromSeconds(10));
Stream stream = await response.Content.ReadAsStreamAsync();
int bytesRead = await stream.ReadAsync(new byte[1024]);
Assert.Equal(1024, bytesRead);
var cts = new CancellationTokenSource(200);
if (type == CancellationType.Dispose)
{
cts.Token.Register(() => response.Dispose());
}
CancellationToken readCt = type == CancellationType.CancellationToken ? cts.Token : default;
Exception ex = await Assert.ThrowsAnyAsync<Exception>(() => stream.ReadAsync(new byte[1024], cancellationToken: readCt).AsTask());
if (type == CancellationType.CancellationToken)
{
Assert.IsType<OperationCanceledException>(ex);
}
else
{
var ioe = Assert.IsType<IOException>(ex);
var hre = Assert.IsType<HttpRequestException>(ioe.InnerException);
var qex = Assert.IsType<QuicException>(hre.InnerException);
Assert.Equal(QuicError.OperationAborted, qex.QuicError);
}
clientDone.Release();
await serverDone.WaitAsync();
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(20_000);
}
[Fact]
public async Task ResponseCancellation_BothCancellationTokenAndDispose_Success()
{
using Http3LoopbackServer server = CreateHttp3LoopbackServer();
using var clientDone = new SemaphoreSlim(0);
using var serverDone = new SemaphoreSlim(0);
Task serverTask = Task.Run(async () =>
{
await using Http3LoopbackConnection connection = (Http3LoopbackConnection)await server.EstablishGenericConnectionAsync();
await using Http3LoopbackStream stream = await connection.AcceptRequestStreamAsync();
HttpRequestData request = await stream.ReadRequestDataAsync().ConfigureAwait(false);
int contentLength = 2 * 1024 * 1024;
var headers = new List<HttpHeaderData>();
headers.Append(new HttpHeaderData("Content-Length", contentLength.ToString(CultureInfo.InvariantCulture)));
await stream.SendResponseHeadersAsync(HttpStatusCode.OK, headers).ConfigureAwait(false);
await stream.SendDataFrameAsync(new byte[1024]).ConfigureAwait(false);
await clientDone.WaitAsync();
// It is possible that PEER_RECEIVE_ABORTED event will arrive with a significant delay after peer calls AbortReceive
// In that case even with synchronization via semaphores, first writes after peer aborting may "succeed" (get SEND_COMPLETE event)
// We are asserting that PEER_RECEIVE_ABORTED would still arrive eventually
QuicException ex = await AssertThrowsQuicExceptionAsync(QuicError.StreamAborted, () => SendDataForever(stream).WaitAsync(TimeSpan.FromSeconds(20)));
// exact error code depends on who won the race
Assert.True(ex.ApplicationErrorCode == 268 /* cancellation */ || ex.ApplicationErrorCode == 0xffffffff /* disposal */, $"Expected 268 or 0xffffffff, got {ex.ApplicationErrorCode}");
serverDone.Release();
});
Task clientTask = Task.Run(async () =>
{
using HttpClient client = CreateHttpClient();
using HttpRequestMessage request = new()
{
Method = HttpMethod.Get,
RequestUri = server.Address,
Version = HttpVersion30,
VersionPolicy = HttpVersionPolicy.RequestVersionExact
};
HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).WaitAsync(TimeSpan.FromSeconds(20));
Stream stream = await response.Content.ReadAsStreamAsync();
int bytesRead = await stream.ReadAsync(new byte[1024]);
Assert.Equal(1024, bytesRead);
var cts = new CancellationTokenSource(200);
cts.Token.Register(() => response.Dispose());
Exception ex = await Assert.ThrowsAnyAsync<Exception>(() => stream.ReadAsync(new byte[1024], cancellationToken: cts.Token).AsTask());
// exact exception depends on who won the race
if (ex is not OperationCanceledException)
{
var ioe = Assert.IsType<IOException>(ex);
var hre = Assert.IsType<HttpRequestException>(ioe.InnerException);
var qex = Assert.IsType<QuicException>(hre.InnerException);
Assert.Equal(QuicError.OperationAborted, qex.QuicError);
}
clientDone.Release();
await serverDone.WaitAsync();
});
await new[] { clientTask, serverTask }.WhenAllOrAnyFailed(200_000);
}
private static async Task SendDataForever(Http3LoopbackStream stream)
{
var buf = new byte[100];
while (true)
{
await stream.SendDataFrameAsync(buf);
}
}
[Fact]