|
| 1 | +using System.Net; |
| 2 | +using System.Net.Http.Headers; |
| 3 | +using System.Text.Json; |
| 4 | + |
| 5 | +namespace FlowableExternalWorkerClient.Tests; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// A DelegatingHandler that records HTTP interactions to a JSON cassette file |
| 9 | +/// and replays them in order on subsequent runs. |
| 10 | +/// |
| 11 | +/// Mode: Auto - if cassette file exists, replays; otherwise records. |
| 12 | +/// Replay is sequential (ordered), not matching-based, to correctly handle |
| 13 | +/// repeated calls to the same endpoint with different responses. |
| 14 | +/// </summary> |
| 15 | +public class CassetteHandler : DelegatingHandler |
| 16 | +{ |
| 17 | + private readonly string _cassettePath; |
| 18 | + private readonly List<RecordedInteraction> _interactions; |
| 19 | + private int _replayIndex; |
| 20 | + private readonly bool _isReplaying; |
| 21 | + |
| 22 | + public CassetteHandler(string cassettePath) |
| 23 | + : base(new HttpClientHandler()) |
| 24 | + { |
| 25 | + _cassettePath = cassettePath; |
| 26 | + if (File.Exists(cassettePath)) |
| 27 | + { |
| 28 | + var json = File.ReadAllText(cassettePath); |
| 29 | + _interactions = JsonSerializer.Deserialize<List<RecordedInteraction>>(json, |
| 30 | + new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }) ?? new(); |
| 31 | + _isReplaying = true; |
| 32 | + } |
| 33 | + else |
| 34 | + { |
| 35 | + _interactions = new(); |
| 36 | + _isReplaying = false; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public bool IsReplaying => _isReplaying; |
| 41 | + |
| 42 | + public HttpClient CreateHttpClient() |
| 43 | + { |
| 44 | + return new HttpClient(this, disposeHandler: false); |
| 45 | + } |
| 46 | + |
| 47 | + protected override async Task<HttpResponseMessage> SendAsync( |
| 48 | + HttpRequestMessage request, CancellationToken cancellationToken) |
| 49 | + { |
| 50 | + if (_isReplaying) |
| 51 | + { |
| 52 | + return Replay(request); |
| 53 | + } |
| 54 | + |
| 55 | + return await Record(request, cancellationToken); |
| 56 | + } |
| 57 | + |
| 58 | + private HttpResponseMessage Replay(HttpRequestMessage request) |
| 59 | + { |
| 60 | + int index; |
| 61 | + lock (_interactions) |
| 62 | + { |
| 63 | + index = _replayIndex++; |
| 64 | + } |
| 65 | + |
| 66 | + if (index >= _interactions.Count) |
| 67 | + { |
| 68 | + throw new InvalidOperationException( |
| 69 | + $"Cassette '{Path.GetFileName(_cassettePath)}' has no more recorded interactions " + |
| 70 | + $"(tried index {index}, total {_interactions.Count}). " + |
| 71 | + $"Delete the cassette file to re-record."); |
| 72 | + } |
| 73 | + |
| 74 | + return _interactions[index].ToHttpResponseMessage(); |
| 75 | + } |
| 76 | + |
| 77 | + private async Task<HttpResponseMessage> Record( |
| 78 | + HttpRequestMessage request, CancellationToken cancellationToken) |
| 79 | + { |
| 80 | + var response = await base.SendAsync(request, cancellationToken); |
| 81 | + |
| 82 | + // Buffer the response body so both recording and caller can use it |
| 83 | + var bodyBytes = response.Content != null |
| 84 | + ? await response.Content.ReadAsByteArrayAsync(cancellationToken) |
| 85 | + : Array.Empty<byte>(); |
| 86 | + |
| 87 | + var interaction = new RecordedInteraction |
| 88 | + { |
| 89 | + Method = request.Method.Method, |
| 90 | + Uri = request.RequestUri?.ToString() ?? "", |
| 91 | + StatusCode = (int)response.StatusCode, |
| 92 | + ResponseBody = Convert.ToBase64String(bodyBytes), |
| 93 | + ResponseContentType = response.Content?.Headers.ContentType?.ToString() |
| 94 | + }; |
| 95 | + |
| 96 | + foreach (var header in response.Headers) |
| 97 | + { |
| 98 | + interaction.ResponseHeaders[header.Key] = header.Value.ToArray(); |
| 99 | + } |
| 100 | + |
| 101 | + lock (_interactions) |
| 102 | + { |
| 103 | + _interactions.Add(interaction); |
| 104 | + } |
| 105 | + |
| 106 | + // Return a new response with buffered body so the caller can read it |
| 107 | + var newResponse = new HttpResponseMessage(response.StatusCode); |
| 108 | + newResponse.Content = new ByteArrayContent(bodyBytes); |
| 109 | + if (response.Content?.Headers.ContentType != null) |
| 110 | + { |
| 111 | + newResponse.Content.Headers.ContentType = response.Content.Headers.ContentType; |
| 112 | + } |
| 113 | + |
| 114 | + foreach (var header in response.Headers) |
| 115 | + { |
| 116 | + newResponse.Headers.TryAddWithoutValidation(header.Key, header.Value); |
| 117 | + } |
| 118 | + |
| 119 | + newResponse.RequestMessage = request; |
| 120 | + return newResponse; |
| 121 | + } |
| 122 | + |
| 123 | + public void Save() |
| 124 | + { |
| 125 | + if (!_isReplaying) |
| 126 | + { |
| 127 | + Directory.CreateDirectory(Path.GetDirectoryName(_cassettePath)!); |
| 128 | + var json = JsonSerializer.Serialize(_interactions, new JsonSerializerOptions |
| 129 | + { |
| 130 | + WriteIndented = true, |
| 131 | + PropertyNamingPolicy = JsonNamingPolicy.CamelCase |
| 132 | + }); |
| 133 | + File.WriteAllText(_cassettePath, json); |
| 134 | + } |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +public class RecordedInteraction |
| 139 | +{ |
| 140 | + public string Method { get; set; } = ""; |
| 141 | + public string Uri { get; set; } = ""; |
| 142 | + public int StatusCode { get; set; } |
| 143 | + public string? ResponseBody { get; set; } |
| 144 | + public string? ResponseContentType { get; set; } |
| 145 | + public Dictionary<string, string[]> ResponseHeaders { get; set; } = new(); |
| 146 | + |
| 147 | + public HttpResponseMessage ToHttpResponseMessage() |
| 148 | + { |
| 149 | + var response = new HttpResponseMessage((HttpStatusCode)StatusCode); |
| 150 | + |
| 151 | + if (ResponseBody != null) |
| 152 | + { |
| 153 | + var bytes = Convert.FromBase64String(ResponseBody); |
| 154 | + response.Content = new ByteArrayContent(bytes); |
| 155 | + if (ResponseContentType != null) |
| 156 | + { |
| 157 | + response.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(ResponseContentType); |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + foreach (var header in ResponseHeaders) |
| 162 | + { |
| 163 | + response.Headers.TryAddWithoutValidation(header.Key, header.Value); |
| 164 | + } |
| 165 | + |
| 166 | + return response; |
| 167 | + } |
| 168 | +} |
0 commit comments