{{ message }}
forked from NpgsqlRest/NpgsqlRest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClientTypeHandler.cs
More file actions
489 lines (428 loc) · 19.7 KB
/
Copy pathHttpClientTypeHandler.cs
File metadata and controls
489 lines (428 loc) · 19.7 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
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Text;
using Npgsql;
using NpgsqlTypes;
namespace NpgsqlRest.HttpClientType;
public class HttpClientTypeHandler(HttpTypeDefinition definition, Dictionary<string, string>.AlternateLookup<ReadOnlySpan<char>>? replacements = null)
{
private static readonly HttpClient SharedClient = new()
{
Timeout = Timeout.InfiniteTimeSpan // We handle timeout per-request
};
/// <summary>
/// HttpClient for self-referencing calls (relative paths). Uses SelfBaseUrl or a custom handler.
/// </summary>
private static HttpClient? _selfClient;
private string? _resolvedUrl;
/// <summary>
/// Base URL for resolving relative paths (e.g., "/api/test" → "http://localhost:5000/api/test").
/// Auto-detected from the server's listening address, or set via HttpClientOptions.SelfBaseUrl.
/// </summary>
internal static string? SelfBaseUrl { get; set; }
/// <summary>
/// Set a custom HttpClient for self-referencing calls (e.g., from WebApplicationFactory TestServer).
/// </summary>
internal static void SetSelfClient(HttpClient client)
{
_selfClient = client;
}
// Response properties
private int StatusCode { get; set; }
private string? Body { get; set; }
private string? ResponseHeaders { get; set; }
private string? ContentType { get; set; }
private bool IsSuccess { get; set; }
private string? ErrorMessage { get; set; }
public async Task InvokeAsync(CancellationToken cancellationToken = default)
{
int maxRetries = definition.RetryDelays?.Length ?? 0;
for (int attempt = 0; attempt <= maxRetries; attempt++)
{
var startTimestamp = Stopwatch.GetTimestamp();
_resolvedUrl = ResolveValue(definition.Url);
var resolvedUrl = _resolvedUrl;
if (attempt == 0)
{
Logger?.LogDebug("HTTP client starting {Method} request to '{Url}'", definition.Method, resolvedUrl);
}
else
{
Logger?.LogDebug("HTTP client retrying {Method} request to '{Url}' (attempt {Attempt}/{MaxRetries})",
definition.Method, resolvedUrl, attempt + 1, maxRetries + 1);
}
try
{
bool isSelfCall = definition.Url.StartsWith('/');
// Use internal request handler for self-calls (bypasses HTTP stack entirely)
if (isSelfCall && InternalRequestHandler.IsAvailable)
{
var url = definition.NeedsParsing && replacements is not null
? Formatter.FormatString(definition.Url.AsSpan(), replacements.Value).ToString()
: definition.Url;
var internalResponse = await InternalRequestHandler.ExecuteAsync(
definition.Method,
url,
definition.Headers,
definition.NeedsParsing && definition.Body is not null && replacements is not null
? Formatter.FormatString(definition.Body.AsSpan(), replacements.Value).ToString()
: definition.Body,
definition.ContentType,
cancellationToken);
StatusCode = internalResponse.StatusCode;
Body = internalResponse.Body;
ContentType = internalResponse.ContentType;
ResponseHeaders = internalResponse.Headers;
IsSuccess = internalResponse.IsSuccess;
ErrorMessage = IsSuccess ? null : $"Internal request returned {StatusCode}";
var elapsed = Stopwatch.GetElapsedTime(startTimestamp);
Logger?.LogDebug("Internal request to '{Url}' completed with status {StatusCode} in {Elapsed}ms",
resolvedUrl, StatusCode, elapsed.TotalMilliseconds.ToString("F1"));
if (!IsSuccess && attempt < maxRetries && ShouldRetry(StatusCode))
{
Logger?.LogWarning("Internal request to '{Url}' returned {StatusCode}, retrying after {Delay}ms",
resolvedUrl, StatusCode, definition.RetryDelays![attempt].TotalMilliseconds);
await Task.Delay(definition.RetryDelays![attempt], cancellationToken);
continue;
}
return;
}
using var request = CreateRequest();
using var cts = CreateTimeoutCancellationTokenSource(cancellationToken);
var client = isSelfCall && _selfClient is not null ? _selfClient : SharedClient;
using var response = await client.SendAsync(request, cts?.Token ?? cancellationToken);
await ProcessResponseAsync(response, startTimestamp);
if (!IsSuccess && attempt < maxRetries && ShouldRetry(StatusCode))
{
Logger?.LogWarning("HTTP client request to '{Url}' returned {StatusCode}, retrying after {Delay}ms",
resolvedUrl, StatusCode, definition.RetryDelays![attempt].TotalMilliseconds);
await Task.Delay(definition.RetryDelays![attempt], cancellationToken);
continue;
}
return;
}
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
{
StatusCode = 408;
IsSuccess = false;
ErrorMessage = $"Request timed out after {definition.Timeout?.TotalSeconds ?? 30} seconds";
if (attempt < maxRetries)
{
Logger?.LogWarning("HTTP client request to '{Url}' timed out, retrying after {Delay}ms",
resolvedUrl, definition.RetryDelays![attempt].TotalMilliseconds);
await Task.Delay(definition.RetryDelays![attempt], cancellationToken);
continue;
}
Logger?.LogWarning("HTTP client request to '{Url}' timed out after {Timeout}s",
resolvedUrl, definition.Timeout?.TotalSeconds ?? 30);
}
catch (HttpRequestException ex)
{
StatusCode = (int?)ex.StatusCode ?? 0;
IsSuccess = false;
ErrorMessage = ex.Message;
if (attempt < maxRetries)
{
Logger?.LogWarning("HTTP client request to '{Url}' failed ({Message}), retrying after {Delay}ms",
resolvedUrl, ex.Message, definition.RetryDelays![attempt].TotalMilliseconds);
await Task.Delay(definition.RetryDelays![attempt], cancellationToken);
continue;
}
Logger?.LogError(ex, "HTTP client request to '{Url}' failed with status {StatusCode}",
resolvedUrl, StatusCode);
}
catch (Exception ex)
{
StatusCode = 0;
IsSuccess = false;
ErrorMessage = ex.Message;
Logger?.LogError(ex, "HTTP client request to '{Url}' failed with unexpected error", resolvedUrl);
return; // Unexpected errors are not retryable
}
}
}
/// <summary>
/// Runs the outbound call, routing it through <see cref="HttpResponseCache"/> when the type opts in
/// via <c>@cache</c> and caching is enabled globally. On a cache hit (or a coalesced concurrent call)
/// the cached response is applied to this handler so the fill loop reads it exactly as a live response.
/// </summary>
public async Task InvokeWithCacheAsync(CancellationToken cancellationToken = default)
{
if (!Options.HttpClientOptions.CacheEnabled || !definition.CacheEnabled)
{
await InvokeAsync(cancellationToken);
return;
}
var key = ComputeCacheKey();
var cached = await HttpResponseCache.GetOrCreateAsync(
key,
definition.CacheDuration,
async ct =>
{
await InvokeAsync(ct);
return SnapshotResponse();
},
cancellationToken);
ApplyResponse(cached);
}
/// <summary>
/// Cache key for this request: method + resolved URL + resolved content-type + resolved headers
/// (sorted) + resolved body. Placeholders are resolved so per-request values vary the key; a type
/// with no placeholders produces a constant key (one shared cached response).
/// </summary>
private string ComputeCacheKey()
{
var sb = new StringBuilder();
sb.Append(definition.Method).Append('\n');
sb.Append(ResolveValue(definition.Url)).Append('\n');
if (definition.ContentType is not null)
{
sb.Append(ResolveValue(definition.ContentType));
}
sb.Append('\n');
if (definition.Headers is { Count: > 0 })
{
foreach (var header in definition.Headers.OrderBy(h => h.Key, StringComparer.Ordinal))
{
sb.Append(header.Key).Append(':').Append(ResolveValue(header.Value)).Append('\n');
}
}
sb.Append('\n');
if (definition.Body is not null)
{
sb.Append(ResolveValue(definition.Body));
}
return sb.ToString();
}
private CachedHttpResponse SnapshotResponse() =>
new(StatusCode, Body, ResponseHeaders, ContentType, IsSuccess, ErrorMessage);
private void ApplyResponse(CachedHttpResponse r)
{
StatusCode = r.StatusCode;
Body = r.Body;
ResponseHeaders = r.ResponseHeaders;
ContentType = r.ContentType;
IsSuccess = r.IsSuccess;
ErrorMessage = r.ErrorMessage;
}
private bool ShouldRetry(int statusCode)
{
if (definition.RetryOnStatusCodes is null)
{
return true; // No filter = retry any failure
}
return definition.RetryOnStatusCodes.Contains(statusCode);
}
private HttpRequestMessage CreateRequest()
{
var url = ResolveValue(definition.Url);
// Resolve relative paths against the server's own base URL (skip if _selfClient handles it via BaseAddress)
if (url.StartsWith('/') && _selfClient is null && SelfBaseUrl is not null)
{
url = string.Concat(SelfBaseUrl, url);
}
var method = new HttpMethod(definition.Method);
var request = new HttpRequestMessage(method, url);
// Add headers
if (definition.Headers is { Count: > 0 })
{
foreach (var header in definition.Headers)
{
var headerValue = ResolveValue(header.Value);
request.Headers.TryAddWithoutValidation(header.Key, headerValue);
}
}
// Add body
if (definition.Body is not null)
{
var body = ResolveValue(definition.Body);
var contentType = definition.ContentType is not null
? ResolveValue(definition.ContentType)
: "application/json";
request.Content = new StringContent(body);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType);
}
return request;
}
private CancellationTokenSource? CreateTimeoutCancellationTokenSource(CancellationToken cancellationToken)
{
if (definition.Timeout is null)
{
return null;
}
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(definition.Timeout.Value);
return cts;
}
private async Task ProcessResponseAsync(HttpResponseMessage response, long startTimestamp)
{
StatusCode = (int)response.StatusCode;
IsSuccess = response.IsSuccessStatusCode;
ContentType = response.Content.Headers.ContentType?.ToString();
Body = await response.Content.ReadAsStringAsync();
// Build response headers as JSON object string
ResponseHeaders = BuildHeadersJson(response);
var duration = Stopwatch.GetElapsedTime(startTimestamp);
Logger?.LogDebug("HTTP client request to '{Url}' completed with status {StatusCode}, content-type: {ContentType}, body length: {BodyLength}, duration: {Duration}ms",
_resolvedUrl ?? definition.Url, StatusCode, ContentType, Body?.Length ?? 0, duration.TotalMilliseconds);
}
private static string BuildHeadersJson(HttpResponseMessage response)
{
var sb = new StringBuilder();
sb.Append('{');
bool first = true;
foreach (var header in response.Headers)
{
if (!first) sb.Append(',');
first = false;
sb.Append(PgConverters.SerializeString(header.Key));
sb.Append(':');
sb.Append(PgConverters.SerializeString(string.Join(", ", header.Value)));
}
foreach (var header in response.Content.Headers)
{
if (!first) sb.Append(',');
first = false;
sb.Append(PgConverters.SerializeString(header.Key));
sb.Append(':');
sb.Append(PgConverters.SerializeString(string.Join(", ", header.Value)));
}
sb.Append('}');
return sb.ToString();
}
private string ResolveValue(string value)
{
if (definition.NeedsParsing is false || replacements is null)
{
return value;
}
return new string(Formatter.FormatString(value.AsSpan(), replacements.Value));
}
public static async Task InvokeAllAsync(
IEnumerable<string> typeNames,
Dictionary<string, string>.AlternateLookup<ReadOnlySpan<char>>? replacements,
NpgsqlParameterCollection parameters,
CancellationToken cancellationToken)
{
var handlers = new Dictionary<string, HttpClientTypeHandler>();
var tasks = new List<(string TypeName, HttpClientTypeHandler Handler, Task Task)>();
foreach (var typeName in typeNames)
{
// A DB-function composite parameter is expanded into one parameter per field,
// each carrying the same CustomType, so typeNames can contain the same type
// multiple times. Fire exactly one outbound call per distinct HTTP type - the
// fill loop below resolves handlers by distinct type name as well.
if (handlers.ContainsKey(typeName))
{
continue;
}
if (HttpClientTypes.Definitions.TryGetValue(typeName, out var definition))
{
var handler = new HttpClientTypeHandler(definition, replacements);
handlers[typeName] = handler;
tasks.Add((typeName, handler, handler.InvokeWithCacheAsync(cancellationToken)));
}
}
await Task.WhenAll(tasks.Select(t => t.Task));
for (var i = 0; i < parameters.Count; i++)
{
var parameter = (NpgsqlRestParameter)parameters[i];
if (parameter.TypeDescriptor.CustomType is null)
{
continue;
}
if (!handlers.TryGetValue(parameter.TypeDescriptor.CustomType, out var handler))
{
continue;
}
// Single composite parameter (SQL files): build composite text value
if (parameter.TypeDescriptor.CustomTypeName is null)
{
parameter.Value = BuildCompositeTextValue(handler, parameter.CompositeFieldNames);
continue;
}
// Expanded field parameter (functions): fill individual field
bool asText = parameter.NpgsqlDbType == NpgsqlDbType.Unknown || parameter.TypeDescriptor.IsText;
if (string.Equals(parameter.TypeDescriptor.CustomTypeName, Options.HttpClientOptions.ResponseStatusCodeField, StringComparison.InvariantCulture))
{
parameter.Value = asText ? handler.StatusCode.ToString() : handler.StatusCode;
}
else if (string.Equals(parameter.TypeDescriptor.CustomTypeName, Options.HttpClientOptions.ResponseBodyField, StringComparison.InvariantCulture))
{
parameter.Value = (object?)handler.Body ?? DBNull.Value;
}
else if (string.Equals(parameter.TypeDescriptor.CustomTypeName, Options.HttpClientOptions.ResponseHeadersField, StringComparison.InvariantCulture))
{
parameter.Value = (object?)handler.ResponseHeaders ?? DBNull.Value;
}
else if (string.Equals(parameter.TypeDescriptor.CustomTypeName, Options.HttpClientOptions.ResponseContentTypeField, StringComparison.InvariantCulture))
{
parameter.Value = (object?)handler.ContentType ?? DBNull.Value;
}
else if (string.Equals(parameter.TypeDescriptor.CustomTypeName, Options.HttpClientOptions.ResponseSuccessField, StringComparison.InvariantCulture))
{
parameter.Value = asText ? (object)handler.IsSuccess.ToString().ToLowerInvariant() : handler.IsSuccess;
}
else if (string.Equals(parameter.TypeDescriptor.CustomTypeName, Options.HttpClientOptions.ResponseErrorMessageField, StringComparison.InvariantCulture))
{
parameter.Value = (object?)handler.ErrorMessage ?? DBNull.Value;
}
}
}
/// <summary>
/// Build a PostgreSQL composite type text representation from HTTP response values.
/// Format: (field1_value,field2_value,...) where values are double-quoted and internal quotes escaped.
/// Field order comes from the composite type definition in pg_catalog.
/// </summary>
private static object BuildCompositeTextValue(HttpClientTypeHandler handler, string[]? fieldNames)
{
if (fieldNames is null || fieldNames.Length == 0)
{
return DBNull.Value;
}
var httpOptions = Options.HttpClientOptions;
var sb = new System.Text.StringBuilder();
sb.Append('(');
for (int i = 0; i < fieldNames.Length; i++)
{
if (i > 0) sb.Append(',');
var fieldName = fieldNames[i];
string? value = null;
if (string.Equals(fieldName, httpOptions.ResponseBodyField, StringComparison.InvariantCulture))
{
value = handler.Body;
}
else if (string.Equals(fieldName, httpOptions.ResponseStatusCodeField, StringComparison.InvariantCulture))
{
value = handler.StatusCode.ToString();
}
else if (string.Equals(fieldName, httpOptions.ResponseHeadersField, StringComparison.InvariantCulture))
{
value = handler.ResponseHeaders;
}
else if (string.Equals(fieldName, httpOptions.ResponseContentTypeField, StringComparison.InvariantCulture))
{
value = handler.ContentType;
}
else if (string.Equals(fieldName, httpOptions.ResponseSuccessField, StringComparison.InvariantCulture))
{
value = handler.IsSuccess ? "t" : "f";
}
else if (string.Equals(fieldName, httpOptions.ResponseErrorMessageField, StringComparison.InvariantCulture))
{
value = handler.ErrorMessage;
}
if (value is null)
{
// NULL: empty between commas
continue;
}
// Double-quote the value, escaping internal double-quotes
sb.Append('"');
sb.Append(value.Replace("\"", "\"\""));
sb.Append('"');
}
sb.Append(')');
return sb.ToString();
}
}
You can’t perform that action at this time.
