-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathHttpClientExtensionsTests.cs
More file actions
915 lines (778 loc) · 34.4 KB
/
Copy pathHttpClientExtensionsTests.cs
File metadata and controls
915 lines (778 loc) · 34.4 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
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
using System.IO.Compression;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Time.Testing;
using PostHog;
using PostHog.Api;
using PostHog.Library;
#if NETCOREAPP3_1
using TestLibrary.Fakes.Polyfills;
#endif
namespace HttpClientExtensionsTests;
public class ThePostJsonWithRetryAsyncMethod
{
static readonly Uri BatchUrl = new("https://us.i.posthog.com/batch");
static PostHogOptions CreateOptions(
int maxRetries = 3,
TimeSpan? initialRetryDelay = null,
TimeSpan? maxRetryDelay = null,
bool enableCompression = false) => new()
{
ProjectToken = "test-api-key",
MaxRetries = maxRetries,
InitialRetryDelay = initialRetryDelay ?? TimeSpan.FromMilliseconds(1),
MaxRetryDelay = maxRetryDelay ?? TimeSpan.FromSeconds(30),
EnableCompression = enableCompression
};
static HttpClient CreateHttpClient(FakeRetryHttpMessageHandler handler)
=> new(handler) { BaseAddress = new Uri("https://us.i.posthog.com") };
[Fact]
public async Task ReturnsSuccessOnFirstAttemptWithNoRetry()
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions();
var timeProvider = new FakeTimeProvider();
var result = await httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(1, handler.RequestCount);
}
[Theory]
[InlineData(HttpStatusCode.InternalServerError)] // 500
[InlineData(HttpStatusCode.BadGateway)] // 502
[InlineData(HttpStatusCode.ServiceUnavailable)] // 503
[InlineData(HttpStatusCode.GatewayTimeout)] // 504
[InlineData(HttpStatusCode.RequestTimeout)] // 408
[InlineData(HttpStatusCode.TooManyRequests)] // 429
public async Task RetriesOnRetryableStatusCodeThenSucceeds(HttpStatusCode statusCode)
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(statusCode, new { error = "transient" });
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
// Start the request
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete before advancing time
await handler.WaitForRequestCountAsync(1);
// Advance time to trigger the retry
timeProvider.Advance(TimeSpan.FromSeconds(1));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(2, handler.RequestCount);
}
[Theory]
[InlineData(HttpStatusCode.BadRequest)] // 400
[InlineData(HttpStatusCode.Forbidden)] // 403
public async Task DoesNotRetryOnNonRetryableStatusCodeAndThrowsApiException(HttpStatusCode statusCode)
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(statusCode, new { type = "error", detail = "Bad request" });
handler.AddResponse(HttpStatusCode.OK, new { status = 1 }); // Should never be reached
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
await Assert.ThrowsAsync<ApiException>(() =>
httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None));
Assert.Equal(1, handler.RequestCount);
}
[Fact]
public async Task DoesNotRetryOnUnauthorizedAndThrowsUnauthorizedAccessException()
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(HttpStatusCode.Unauthorized, new { type = "error", detail = "Invalid API key" });
handler.AddResponse(HttpStatusCode.OK, new { status = 1 }); // Should never be reached
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
await Assert.ThrowsAsync<UnauthorizedAccessException>(() =>
httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None));
Assert.Equal(1, handler.RequestCount);
}
[Fact]
public async Task DoesNotRetryOnNotFoundAndThrowsHttpRequestException()
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(HttpStatusCode.NotFound, new { type = "error", detail = "Not found" });
handler.AddResponse(HttpStatusCode.OK, new { status = 1 }); // Should never be reached
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
await Assert.ThrowsAsync<HttpRequestException>(() =>
httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None));
Assert.Equal(1, handler.RequestCount);
}
[Fact]
public async Task ThrowsAfterMaxRetriesWhenAllAttemptsFail()
{
var handler = new FakeRetryHttpMessageHandler();
// Add 4 failures (1 initial + 3 retries)
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error", detail = "Down" });
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error", detail = "Down" });
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error", detail = "Down" });
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error", detail = "Down" });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Advance time for each retry attempt (1 initial + 3 retries)
for (var i = 1; i <= 4 && !task.IsCompleted; i++)
{
await handler.WaitForRequestCountAsync(i);
timeProvider.Advance(TimeSpan.FromSeconds(1));
}
await Assert.ThrowsAsync<ApiException>(() => task);
Assert.Equal(4, handler.RequestCount); // 1 initial + 3 retries
}
[Fact]
public async Task RespectsRetryAfterDeltaHeader()
{
var handler = new FakeRetryHttpMessageHandler();
using var responseWithRetryAfter = new HttpResponseMessage(HttpStatusCode.TooManyRequests)
{
Content = new StringContent("{\"type\": \"error\", \"detail\": \"rate limited\"}")
};
responseWithRetryAfter.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromMilliseconds(100));
handler.AddResponse(responseWithRetryAfter);
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete before advancing time
await handler.WaitForRequestCountAsync(1);
#if NET8_0_OR_GREATER
// Verify task is waiting for the Retry-After delay
Assert.False(task.IsCompleted, "Task should be waiting for Retry-After delay");
#endif
// Advance time by the Retry-After value
timeProvider.Advance(TimeSpan.FromMilliseconds(100));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(2, handler.RequestCount);
}
[Fact]
public async Task RespectsRetryAfterDateHeader()
{
var handler = new FakeRetryHttpMessageHandler();
using var responseWithRetryAfter = new HttpResponseMessage(HttpStatusCode.TooManyRequests)
{
Content = new StringContent("{\"type\": \"error\", \"detail\": \"rate limited\"}")
};
var timeProvider = new FakeTimeProvider();
// Set Retry-After to a date 100ms in the future
var retryAfterDate = timeProvider.GetUtcNow().AddMilliseconds(100);
responseWithRetryAfter.Headers.RetryAfter = new RetryConditionHeaderValue(retryAfterDate);
handler.AddResponse(responseWithRetryAfter);
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete before advancing time
await handler.WaitForRequestCountAsync(1);
#if NET8_0_OR_GREATER
// Verify task is waiting for the Retry-After delay
Assert.False(task.IsCompleted, "Task should be waiting for Retry-After date");
#endif
// Advance time past the Retry-After date
timeProvider.Advance(TimeSpan.FromMilliseconds(100));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(2, handler.RequestCount);
}
[Fact]
public async Task RespectsRetryAfterDateInThePastByUsingZeroDelay()
{
var handler = new FakeRetryHttpMessageHandler();
var timeProvider = new FakeTimeProvider();
using var responseWithPastRetryAfter = new HttpResponseMessage(HttpStatusCode.TooManyRequests)
{
Content = new StringContent("{\"type\": \"error\", \"detail\": \"rate limited\"}")
};
// Set Retry-After to a date 100ms in the PAST (simulates clock skew between client and server)
var retryAfterDate = timeProvider.GetUtcNow().AddMilliseconds(-100);
responseWithPastRetryAfter.Headers.RetryAfter = new RetryConditionHeaderValue(retryAfterDate);
handler.AddResponse(responseWithPastRetryAfter);
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete
await handler.WaitForRequestCountAsync(1);
// With date in past, delay should be clamped to 0 - even minimal time advancement should trigger retry
timeProvider.Advance(TimeSpan.FromMilliseconds(1));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(2, handler.RequestCount);
}
#if NET8_0_OR_GREATER
[Fact]
public async Task ThrowsOperationCanceledExceptionWhenCancellationRequestedDuringDelay()
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error" });
handler.AddResponse(HttpStatusCode.OK, new { status = 1 }); // Should never be reached
using var httpClient = CreateHttpClient(handler);
// Use a long delay so we can cancel during it
var options = CreateOptions(maxRetries: 3, initialRetryDelay: TimeSpan.FromMinutes(1));
var timeProvider = new FakeTimeProvider();
using var cts = new CancellationTokenSource();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
cts.Token);
// Wait for first request to complete (the one that returns 503)
await handler.WaitForRequestCountAsync(1);
// Cancel while waiting for retry delay
await cts.CancelAsync();
// TaskCanceledException inherits from OperationCanceledException
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
Assert.Equal(1, handler.RequestCount); // Should not have retried after cancellation
}
#endif
[Fact]
public async Task CapsRetryDelayAtMaxRetryDelay()
{
var handler = new FakeRetryHttpMessageHandler();
using var responseWithLargeRetryAfter = new HttpResponseMessage(HttpStatusCode.TooManyRequests)
{
Content = new StringContent("{\"type\": \"error\", \"detail\": \"rate limited\"}")
};
// Server requests 500ms delay, but our max is 50ms
responseWithLargeRetryAfter.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromMilliseconds(500));
handler.AddResponse(responseWithLargeRetryAfter);
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3, maxRetryDelay: TimeSpan.FromMilliseconds(50));
var timeProvider = new FakeTimeProvider();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete before advancing time
await handler.WaitForRequestCountAsync(1);
#if NET8_0_OR_GREATER
// Verify task is waiting (delay was capped, not skipped)
Assert.False(task.IsCompleted, "Task should be waiting for capped delay");
#endif
// Advance time by max delay (50ms), not the full 500ms - should be enough due to capping
timeProvider.Advance(TimeSpan.FromMilliseconds(50));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
}
[Fact]
public async Task RetriesOnHttpRequestException()
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddException(new HttpRequestException("Network error"));
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete before advancing time
await handler.WaitForRequestCountAsync(1);
timeProvider.Advance(TimeSpan.FromSeconds(1));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(2, handler.RequestCount);
}
[Fact]
public async Task RetriesUntilSuccessAfterMultipleServiceUnavailableResponses()
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error" });
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error" });
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error" });
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
// Use small delays for fast tests
var options = CreateOptions(maxRetries: 3, initialRetryDelay: TimeSpan.FromMilliseconds(10));
var timeProvider = new FakeTimeProvider();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Advance time for each retry with exponential backoff
// Delays: 10ms, 20ms, 40ms (doubled each time)
for (var i = 1; i <= 4 && !task.IsCompleted; i++)
{
await handler.WaitForRequestCountAsync(i);
timeProvider.Advance(TimeSpan.FromMilliseconds(50));
}
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(4, handler.RequestCount); // 1 initial + 3 retries
}
[Fact]
public async Task MaxRetriesZeroMeansNoRetry()
{
var handler = new FakeRetryHttpMessageHandler();
handler.AddResponse(HttpStatusCode.ServiceUnavailable, new { type = "error", detail = "Down" });
handler.AddResponse(HttpStatusCode.OK, new { status = 1 }); // Should never be reached
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 0);
var timeProvider = new FakeTimeProvider();
await Assert.ThrowsAsync<ApiException>(() =>
httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None));
Assert.Equal(1, handler.RequestCount); // Only the initial attempt
}
[Fact]
public async Task ClampsNegativeRetryAfterDeltaToZero()
{
var handler = new FakeRetryHttpMessageHandler();
using var responseWithNegativeRetryAfter = new HttpResponseMessage(HttpStatusCode.TooManyRequests)
{
Content = new StringContent("{\"type\": \"error\", \"detail\": \"rate limited\"}")
};
// Negative delta (malformed server response)
responseWithNegativeRetryAfter.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromMilliseconds(-100));
handler.AddResponse(responseWithNegativeRetryAfter);
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete
await handler.WaitForRequestCountAsync(1);
// With negative delta clamped to 0, minimal time advancement triggers retry
timeProvider.Advance(TimeSpan.FromMilliseconds(1));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(2, handler.RequestCount);
}
[Fact]
public async Task RetriesOnTaskCanceledExceptionFromTimeout()
{
var handler = new FakeRetryHttpMessageHandler();
// Simulate HttpClient timeout (throws TaskCanceledException with non-canceled token)
handler.AddException(new TaskCanceledException("The request timed out."));
handler.AddResponse(HttpStatusCode.OK, new { status = 1 });
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
var task = httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
CancellationToken.None);
// Wait for first request to complete before advancing time
await handler.WaitForRequestCountAsync(1);
timeProvider.Advance(TimeSpan.FromSeconds(1));
var result = await task;
Assert.NotNull(result);
Assert.Equal(1, result.Status);
Assert.Equal(2, handler.RequestCount);
}
#if NET8_0_OR_GREATER
[Fact]
public async Task DoesNotRetryOnUserCancellation()
{
var handler = new FakeRetryHttpMessageHandler();
using var cts = new CancellationTokenSource();
// Cancel the token before starting
await cts.CancelAsync();
// The TaskCanceledException will be thrown with a canceled token
handler.AddException(new TaskCanceledException("Operation was canceled.", null, cts.Token));
handler.AddResponse(HttpStatusCode.OK, new { status = 1 }); // Should never be reached
using var httpClient = CreateHttpClient(handler);
var options = CreateOptions(maxRetries: 3);
var timeProvider = new FakeTimeProvider();
// Should throw immediately, not retry
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
new { api_key = "test", batch = Array.Empty<object>() },
timeProvider,
options,
cts.Token));
Assert.Equal(1, handler.RequestCount); // Only the initial attempt
}
#endif
}
public class ThePostCompressedJsonAsyncMethod
{
static readonly Uri BatchUrl = new("https://us.i.posthog.com/batch");
[Fact]
public async Task CompressesRequestBodyWithGzip()
{
byte[]? capturedBody = null;
IEnumerable<string>? capturedContentEncoding = null;
string? capturedContentType = null;
var handler = new LambdaHttpMessageHandler(async request =>
{
capturedContentType = request.Content?.Headers.ContentType?.MediaType;
capturedContentEncoding = request.Content?.Headers.ContentEncoding;
if (request.Content != null)
{
capturedBody = await request.Content.ReadAsByteArrayAsync();
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("{\"status\": 1}")
};
});
using var httpClient = new HttpClient(handler);
var options = new PostHogOptions
{
ProjectToken = "test-api-key",
EnableCompression = true
};
var timeProvider = new FakeTimeProvider();
var payload = new { api_key = "test", batch = new[] { new { @event = "test-event" } } };
var result = await httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
payload,
timeProvider,
options,
CancellationToken.None);
Assert.NotNull(result);
Assert.NotNull(capturedBody);
Assert.Equal("application/json", capturedContentType);
Assert.Contains("gzip", capturedContentEncoding!);
// Decompress and verify content
using var compressedStream = new MemoryStream(capturedBody);
using var gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress);
using var reader = new StreamReader(gzipStream, Encoding.UTF8);
var decompressedJson = await reader.ReadToEndAsync();
Assert.Contains("test-event", decompressedJson, StringComparison.Ordinal);
Assert.Contains("api_key", decompressedJson, StringComparison.Ordinal);
}
public static IEnumerable<object[]> CompressionFailureExceptions()
{
yield return [new IOException("gzip failed")];
yield return [new InvalidDataException("gzip failed")];
yield return [new NotSupportedException("gzip failed")];
yield return [new ObjectDisposedException("gzip")];
}
[Theory]
[MemberData(nameof(CompressionFailureExceptions))]
public async Task FallsBackToUncompressedRequestWhenCompressionFails(Exception compressionException)
{
string? capturedBody = null;
IEnumerable<string>? capturedContentEncoding = null;
var handler = new LambdaHttpMessageHandler(async request =>
{
capturedContentEncoding = request.Content?.Headers.ContentEncoding;
if (request.Content != null)
{
capturedBody = await request.Content.ReadAsStringAsync();
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("{\"status\": 1}")
};
});
using var httpClient = new HttpClient(handler);
var options = new PostHogOptions
{
ProjectToken = "test-api-key",
EnableCompression = true
};
var timeProvider = new FakeTimeProvider();
var payload = new { api_key = "test", batch = new[] { new { @event = "test-event" } } };
var originalCompressor = HttpClientExtensions.CreateCompressedJsonContentAsync;
HttpClientExtensions.CreateCompressedJsonContentAsync = (_, _) => Task.FromException<ByteArrayContent>(compressionException);
try
{
await httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
payload,
timeProvider,
options,
CancellationToken.None);
}
finally
{
HttpClientExtensions.CreateCompressedJsonContentAsync = originalCompressor;
}
Assert.Empty(capturedContentEncoding ?? Enumerable.Empty<string>());
Assert.NotNull(capturedBody);
Assert.Contains("test-event", capturedBody, StringComparison.Ordinal);
Assert.Contains("api_key", capturedBody, StringComparison.Ordinal);
}
[Fact]
public async Task DoesNotCompressWhenCompressionDisabled()
{
IEnumerable<string>? capturedContentEncoding = null;
var handler = new LambdaHttpMessageHandler(request =>
{
capturedContentEncoding = request.Content?.Headers.ContentEncoding;
// Response disposal is handled by PostJsonWithRetryAsync via using declaration
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("{\"status\": 1}")
});
});
using var httpClient = new HttpClient(handler);
var options = new PostHogOptions
{
ProjectToken = "test-api-key",
EnableCompression = false
};
var timeProvider = new FakeTimeProvider();
var payload = new { api_key = "test", batch = new[] { new { @event = "test-event" } } };
await httpClient.PostJsonWithRetryAsync<ApiResult>(
BatchUrl,
payload,
timeProvider,
options,
CancellationToken.None);
Assert.Empty(capturedContentEncoding ?? Enumerable.Empty<string>());
}
}
/// <summary>
/// A fake HTTP message handler for testing retry logic.
/// Queues responses that are returned in order.
/// </summary>
sealed class FakeRetryHttpMessageHandler : HttpMessageHandler
{
readonly Queue<Func<Task<HttpResponseMessage>>> _responses = new();
int _requestCount;
public int RequestCount => _requestCount;
/// <summary>
/// Waits until the request count reaches the specified value.
/// Use this instead of Task.Delay for deterministic test synchronization.
/// </summary>
public async Task WaitForRequestCountAsync(int count, int timeoutMs = 5000)
{
var start = DateTime.UtcNow;
while (Volatile.Read(ref _requestCount) < count)
{
if ((DateTime.UtcNow - start).TotalMilliseconds > timeoutMs)
{
throw new TimeoutException($"Timed out waiting for request count {count}. Current: {_requestCount}");
}
await Task.Yield();
}
}
// Note: HttpResponseMessage disposal is handled by PostJsonWithRetryAsync via using declaration.
// The handler creates responses that are returned to and disposed by the calling code.
public void AddResponse(HttpStatusCode statusCode, object body)
{
var json = JsonSerializer.Serialize(body);
_responses.Enqueue(() => Task.FromResult(new HttpResponseMessage(statusCode)
{
Content = new StringContent(json, Encoding.UTF8, "application/json")
}));
}
public void AddResponse(HttpResponseMessage response)
{
_responses.Enqueue(() => Task.FromResult(response));
}
public void AddException(Exception exception)
{
_responses.Enqueue(() => throw exception);
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
Interlocked.Increment(ref _requestCount);
if (_responses.Count == 0)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
return await _responses.Dequeue()();
}
}
public class TheDoubleWithCapMethod
{
[Fact]
public void DoublesValueWhenBelowMax()
{
var current = TimeSpan.FromMilliseconds(100);
var max = TimeSpan.FromMilliseconds(1000);
var result = HttpClientExtensions.DoubleWithCap(current, max);
Assert.Equal(TimeSpan.FromMilliseconds(200), result);
}
[Fact]
public void CapsAtMaxWhenDoublingWouldExceedMax()
{
var current = TimeSpan.FromMilliseconds(600);
var max = TimeSpan.FromMilliseconds(1000);
var result = HttpClientExtensions.DoubleWithCap(current, max);
// 600 * 2 = 1200, which exceeds 1000, so cap at 1000
Assert.Equal(TimeSpan.FromMilliseconds(1000), result);
}
[Fact]
public void ReturnsMaxWhenCurrentEqualsMax()
{
var current = TimeSpan.FromMilliseconds(1000);
var max = TimeSpan.FromMilliseconds(1000);
var result = HttpClientExtensions.DoubleWithCap(current, max);
Assert.Equal(max, result);
}
[Fact]
public void ReturnsMaxWhenCurrentExceedsMax()
{
var current = TimeSpan.FromMilliseconds(1500);
var max = TimeSpan.FromMilliseconds(1000);
var result = HttpClientExtensions.DoubleWithCap(current, max);
Assert.Equal(max, result);
}
[Fact]
public void HandlesOverflowProtectionForLargeValues()
{
// Use a value that would overflow if doubled without protection
var current = TimeSpan.FromTicks(long.MaxValue / 2 + 1);
var max = TimeSpan.MaxValue;
var result = HttpClientExtensions.DoubleWithCap(current, max);
// Should cap at max instead of overflowing
Assert.Equal(max, result);
}
[Fact]
public void DoublesCorrectlyAtBoundaryJustBelowHalfMax()
{
var max = TimeSpan.FromMilliseconds(1000);
var current = TimeSpan.FromMilliseconds(499); // Just below half of max
var result = HttpClientExtensions.DoubleWithCap(current, max);
// 499 * 2 = 998, which is below 1000
Assert.Equal(TimeSpan.FromMilliseconds(998), result);
}
[Fact]
public void CapsAtMaxWhenCurrentIsExactlyHalfOfMax()
{
var max = TimeSpan.FromMilliseconds(1000);
var current = TimeSpan.FromMilliseconds(500); // Exactly half of max
var result = HttpClientExtensions.DoubleWithCap(current, max);
// 500 * 2 = 1000, equals max
Assert.Equal(max, result);
}
[Fact]
public void CapsAtMaxWhenCurrentIsJustAboveHalfOfMax()
{
var max = TimeSpan.FromMilliseconds(1000);
var current = TimeSpan.FromMilliseconds(501); // Just above half of max
var result = HttpClientExtensions.DoubleWithCap(current, max);
// 501 > 1000/2, so cap at max to avoid exceeding
Assert.Equal(max, result);
}
}
public class TheExponentialBackoffBehavior
{
[Fact]
public void DelaysDoubleWithEachRetry()
{
// Verify the exponential backoff sequence: 100ms -> 200ms -> 400ms -> 800ms
var initialDelay = TimeSpan.FromMilliseconds(100);
var maxDelay = TimeSpan.FromSeconds(30);
var delay1 = initialDelay;
var delay2 = HttpClientExtensions.DoubleWithCap(delay1, maxDelay);
var delay3 = HttpClientExtensions.DoubleWithCap(delay2, maxDelay);
var delay4 = HttpClientExtensions.DoubleWithCap(delay3, maxDelay);
Assert.Equal(TimeSpan.FromMilliseconds(100), delay1);
Assert.Equal(TimeSpan.FromMilliseconds(200), delay2);
Assert.Equal(TimeSpan.FromMilliseconds(400), delay3);
Assert.Equal(TimeSpan.FromMilliseconds(800), delay4);
}
[Fact]
public void DelaysCappedAtMaxAfterMultipleDoublings()
{
// Start with 1 second, max of 5 seconds
// Sequence: 1s -> 2s -> 4s -> 5s (capped) -> 5s (stays at cap)
var initialDelay = TimeSpan.FromSeconds(1);
var maxDelay = TimeSpan.FromSeconds(5);
var delay1 = initialDelay;
var delay2 = HttpClientExtensions.DoubleWithCap(delay1, maxDelay);
var delay3 = HttpClientExtensions.DoubleWithCap(delay2, maxDelay);
var delay4 = HttpClientExtensions.DoubleWithCap(delay3, maxDelay);
var delay5 = HttpClientExtensions.DoubleWithCap(delay4, maxDelay);
Assert.Equal(TimeSpan.FromSeconds(1), delay1);
Assert.Equal(TimeSpan.FromSeconds(2), delay2);
Assert.Equal(TimeSpan.FromSeconds(4), delay3);
Assert.Equal(TimeSpan.FromSeconds(5), delay4); // Capped
Assert.Equal(TimeSpan.FromSeconds(5), delay5); // Stays at cap
}
}
/// <summary>
/// A simple lambda-based HTTP message handler for testing.
/// </summary>
sealed class LambdaHttpMessageHandler(
Func<HttpRequestMessage, Task<HttpResponseMessage>> handler) : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
=> handler(request);
}