Repository navigation
Expand file tree
/
Copy pathQuick.Core.Extensions.HttpClient.pas
More file actions
726 lines (634 loc) · 25.9 KB
/
Copy pathQuick.Core.Extensions.HttpClient.pas
File metadata and controls
726 lines (634 loc) · 25.9 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
{ ***************************************************************************
Copyright (c) 2016-2026 Kike Perez
Unit : Quick.Core.Extensions.HttpClient
Description : HttpClient factory with Polly-like resilience pipeline
Author : Kike Perez
Version : 1.0
Created : 08/05/2026
Modified : 08/05/2026
This file is part of QuickCore: https://github.com/exilon/QuickCore
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Core.Extensions.HttpClient;
{$i QuickCore.inc}
interface
uses
System.SysUtils,
System.Classes,
System.JSON,
System.Generics.Collections,
System.Net.HttpClient,
System.Net.URLClient,
System.SyncObjs,
Quick.Core.DependencyInjection,
Quick.Core.Resilience.Abstractions,
Quick.Core.Resilience.Retry,
Quick.Core.Resilience.CircuitBreaker,
Quick.Core.Resilience.Timeout;
type
// ── Exceptions ──────────────────────────────────────────────────────────────
/// <summary>
/// Raised when an HTTP response carries a 5xx server-error status code.
/// Used internally so the retry / circuit-breaker policies can treat it as
/// a transient failure.
/// </summary>
EHttpException = class(Exception)
private
fStatusCode: Integer;
public
constructor Create(aStatusCode: Integer; const aMessage: string);
property StatusCode: Integer read fStatusCode;
end;
// ── Response ────────────────────────────────────────────────────────────────
/// <summary>
/// HTTP response returned by IHttpClient methods.
///
/// IsSuccess : status code in [200..299]
/// IsServerError: status code in [500..599] (triggers retries by default)
/// ContentAsJson: parses Body as TJSONValue; nil if Body is not valid JSON.
/// Caller does NOT own the returned object — it is owned by
/// the THttpResponse instance.
/// </summary>
IHttpResponse = interface
['{A1B2C3D4-E5F6-7890-ABCD-EF1234567891}']
function StatusCode : Integer;
function StatusText : string;
function Body : string;
function IsSuccess : Boolean;
function IsServerError: Boolean;
function ContentAsJson: TJSONValue;
end;
THttpResponse = class(TInterfacedObject, IHttpResponse)
private
fStatusCode: Integer;
fStatusText: string;
fBody : string;
fJsonCache : TJSONValue;
public
constructor Create(aStatusCode: Integer; const aStatusText, aBody: string);
destructor Destroy; override;
function StatusCode : Integer;
function StatusText : string;
function Body : string;
function IsSuccess : Boolean;
function IsServerError: Boolean;
function ContentAsJson: TJSONValue;
end;
// ── Client interface ────────────────────────────────────────────────────────
/// <summary>
/// Resilient HTTP client. All methods combine the configured base URL with
/// the supplied path/URL and apply the resilience pipeline (Timeout → Retry →
/// CircuitBreaker).
///
/// 5xx responses raise EHttpException, which is treated as a transient failure
/// by the retry and circuit-breaker policies.
/// 4xx responses are returned as-is (not retried).
///
/// Equivalent to: IHttpClientFactory.CreateClient() in .NET + Polly handler.
/// </summary>
IHttpClient = interface
['{B2C3D4E5-F6A7-8901-BCDE-F12345678902}']
function Get (const aUrl: string): IHttpResponse;
function Post (const aUrl: string; const aBody: string): IHttpResponse; overload;
function Post (const aUrl: string; aJson: TJSONObject): IHttpResponse; overload;
function Put (const aUrl: string; const aBody: string): IHttpResponse;
function Delete(const aUrl: string): IHttpResponse;
end;
// ── Options ─────────────────────────────────────────────────────────────────
THttpClientOptions = class
private
fBaseUrl : string;
fResponseTimeout : Integer; // ms (0 = RTL default)
fConnectionTimeout: Integer; // ms (0 = RTL default)
fUserAgent : string;
fHeaders : TDictionary<string, string>;
public
constructor Create;
destructor Destroy; override;
property BaseUrl : string read fBaseUrl write fBaseUrl;
property ResponseTimeout : Integer read fResponseTimeout write fResponseTimeout;
property ConnectionTimeout: Integer read fConnectionTimeout write fConnectionTimeout;
property UserAgent : string read fUserAgent write fUserAgent;
property Headers : TDictionary<string, string> read fHeaders;
procedure AddHeader(const aName, aValue: string);
end;
// ── Forward ─────────────────────────────────────────────────────────────────
THttpClientServiceExtension = class;
// ── Builder ─────────────────────────────────────────────────────────────────
/// <summary>
/// Fluent builder for a named HTTP client. Returned by
/// THttpClientServiceExtension.AddHttpClient.
///
/// Usage:
/// services.Extension<THttpClientServiceExtension>
/// .AddHttpClient('github', procedure(o: THttpClientOptions)
/// begin o.BaseUrl := 'https://api.github.com' end)
/// .AddRetry(3, 500, btExponential)
/// .AddCircuitBreaker(5, 30000)
/// .AddTimeout(10000)
/// .Services
/// .AddHttpClient('stripe', ...) // chain another client
/// ...;
///
/// Then inject / resolve:
/// var factory := services.Resolve<IHttpClientFactory>;
/// var client := factory.CreateClient('github');
/// var resp := client.Get('/repos/exilon/QuickCore');
/// </summary>
THttpClientBuilder = class
private
fServices : TServiceCollection;
fName : string;
fOptions : THttpClientOptions; // owned
// Retry
fHasRetry : Boolean;
fRetryMax : Integer;
fRetryDelayMs : Int64;
fRetryBackoff : TBackoffType;
fRetryMaxDelayMs : Int64;
fRetryOnRetry : TRetryEvent;
// Circuit Breaker
fHasCB : Boolean;
fCBThreshold : Integer;
fCBDurationMs : Int64;
fCBOnChange : TCircuitStateChangeEvent;
// Timeout
fHasTimeout : Boolean;
fTimeoutMs : Int64;
fTimeoutOnTimeout : TTimeoutEvent;
public
constructor Create(aServices: TServiceCollection; const aName: string;
aOptions: THttpClientOptions);
destructor Destroy; override;
function WithBaseUrl(const aUrl: string): THttpClientBuilder;
function WithResponseTimeout(aMs: Integer): THttpClientBuilder;
function WithConnectionTimeout(aMs: Integer): THttpClientBuilder;
function WithUserAgent(const aAgent: string): THttpClientBuilder;
function WithHeader(const aName, aValue: string): THttpClientBuilder;
/// <summary>Add a retry policy. Defaults: 3 retries, 500 ms initial delay,
/// exponential backoff, 30 s cap. Only retries on EHttpException (5xx) and
/// network exceptions by default.</summary>
function AddRetry(aMaxRetries: Integer = 3;
aInitialDelayMs: Int64 = 500;
aBackoffType: TBackoffType = btExponential;
aMaxDelayMs: Int64 = 30000;
aOnRetry: TRetryEvent = nil): THttpClientBuilder;
/// <summary>Add a circuit breaker. Defaults: opens after 5 consecutive
/// failures, stays open for 30 seconds.</summary>
function AddCircuitBreaker(aFailureThreshold: Integer = 5;
aDurationOfBreakMs: Int64 = 30000;
aOnStateChange: TCircuitStateChangeEvent = nil): THttpClientBuilder;
/// <summary>Add a per-attempt timeout. Defaults: 10 seconds.</summary>
function AddTimeout(aTimeoutMs: Int64 = 10000;
aOnTimeout: TTimeoutEvent = nil): THttpClientBuilder;
/// <summary>Return the service collection for further chaining.</summary>
function Services: TServiceCollection;
// Accessors for the factory
property Name : string read fName;
property Options: THttpClientOptions read fOptions;
property HasRetry : Boolean read fHasRetry;
property RetryMax : Integer read fRetryMax;
property RetryDelayMs : Int64 read fRetryDelayMs;
property RetryBackoff : TBackoffType read fRetryBackoff;
property RetryMaxDelayMs: Int64 read fRetryMaxDelayMs;
property RetryOnRetry : TRetryEvent read fRetryOnRetry;
property HasCB : Boolean read fHasCB;
property CBThreshold : Integer read fCBThreshold;
property CBDurationMs : Int64 read fCBDurationMs;
property CBOnChange : TCircuitStateChangeEvent read fCBOnChange;
property HasTimeout : Boolean read fHasTimeout;
property TimeoutMs : Int64 read fTimeoutMs;
property TimeoutOnTimeout: TTimeoutEvent read fTimeoutOnTimeout;
end;
// ── Factory ──────────────────────────────────────────────────────────────────
/// <summary>
/// Creates named or default IHttpClient instances.
/// Each named client keeps its circuit-breaker state alive between calls.
///
/// Equivalent to: IHttpClientFactory in Microsoft.Extensions.Http.
/// </summary>
IHttpClientFactory = interface
['{C3D4E5F6-A7B8-9012-CDEF-123456789013}']
/// <summary>Create a client using the default (unnamed) registration.</summary>
function CreateClient: IHttpClient; overload;
/// <summary>Create a client from the named registration.</summary>
function CreateClient(const aName: string): IHttpClient; overload;
end;
// ── DI Extension ─────────────────────────────────────────────────────────────
/// <summary>
/// DI helper for registering named HTTP clients.
///
/// Usage — in ConfigureServices:
/// services.Extension<THttpClientServiceExtension>
/// .AddHttpClient('payments', procedure(o: THttpClientOptions)
/// begin o.BaseUrl := 'https://pay.example.com'; end)
/// .AddRetry(3)
/// .AddCircuitBreaker(5, 10000)
/// .AddTimeout(8000);
///
/// Registers IHttpClientFactory as a singleton automatically.
/// </summary>
THttpClientServiceExtension = class(TServiceCollectionExtension)
private class var
fBuilders: TObjectDictionary<string, THttpClientBuilder>;
class function EnsureRegistry: TObjectDictionary<string, THttpClientBuilder>;
public
class function AddHttpClient(const aName: string = '';
aConfigure: TProc<THttpClientOptions> = nil): THttpClientBuilder;
end;
implementation
// ── THttpResponse ────────────────────────────────────────────────────────────
constructor THttpResponse.Create(aStatusCode: Integer;
const aStatusText, aBody: string);
begin
inherited Create;
fStatusCode := aStatusCode;
fStatusText := aStatusText;
fBody := aBody;
fJsonCache := nil;
end;
destructor THttpResponse.Destroy;
begin
fJsonCache.Free;
inherited;
end;
function THttpResponse.StatusCode : Integer; begin Result := fStatusCode; end;
function THttpResponse.StatusText : string; begin Result := fStatusText; end;
function THttpResponse.Body : string; begin Result := fBody; end;
function THttpResponse.IsSuccess : Boolean; begin Result := (fStatusCode >= 200) and (fStatusCode <= 299); end;
function THttpResponse.IsServerError: Boolean; begin Result := (fStatusCode >= 500) and (fStatusCode <= 599); end;
function THttpResponse.ContentAsJson: TJSONValue;
begin
if (fJsonCache = nil) and (fBody <> '') then
fJsonCache := TJSONObject.ParseJSONValue(fBody);
Result := fJsonCache;
end;
// ── EHttpException ────────────────────────────────────────────────────────────
constructor EHttpException.Create(aStatusCode: Integer; const aMessage: string);
begin
inherited Create(aMessage);
fStatusCode := aStatusCode;
end;
// ── THttpClientOptions ────────────────────────────────────────────────────────
constructor THttpClientOptions.Create;
begin
inherited Create;
fResponseTimeout := 30000;
fConnectionTimeout := 10000;
fUserAgent := 'QuickCore-HttpClient/1.0';
fHeaders := TDictionary<string, string>.Create;
end;
destructor THttpClientOptions.Destroy;
begin
fHeaders.Free;
inherited;
end;
procedure THttpClientOptions.AddHeader(const aName, aValue: string);
begin
fHeaders.AddOrSetValue(aName, aValue);
end;
// ── THttpClientBuilder ────────────────────────────────────────────────────────
constructor THttpClientBuilder.Create(aServices: TServiceCollection;
const aName: string; aOptions: THttpClientOptions);
begin
inherited Create;
fServices := aServices;
fName := aName;
fOptions := aOptions;
// Defaults
fRetryMax := 3;
fRetryDelayMs := 500;
fRetryBackoff := btExponential;
fRetryMaxDelayMs := 30000;
fCBThreshold := 5;
fCBDurationMs := 30000;
fTimeoutMs := 10000;
end;
destructor THttpClientBuilder.Destroy;
begin
fOptions.Free;
inherited;
end;
function THttpClientBuilder.WithBaseUrl(const aUrl: string): THttpClientBuilder;
begin
fOptions.BaseUrl := aUrl;
Result := Self;
end;
function THttpClientBuilder.WithResponseTimeout(aMs: Integer): THttpClientBuilder;
begin
fOptions.ResponseTimeout := aMs;
Result := Self;
end;
function THttpClientBuilder.WithConnectionTimeout(aMs: Integer): THttpClientBuilder;
begin
fOptions.ConnectionTimeout := aMs;
Result := Self;
end;
function THttpClientBuilder.WithUserAgent(const aAgent: string): THttpClientBuilder;
begin
fOptions.UserAgent := aAgent;
Result := Self;
end;
function THttpClientBuilder.WithHeader(const aName, aValue: string): THttpClientBuilder;
begin
fOptions.AddHeader(aName, aValue);
Result := Self;
end;
function THttpClientBuilder.AddRetry(aMaxRetries: Integer; aInitialDelayMs: Int64;
aBackoffType: TBackoffType; aMaxDelayMs: Int64; aOnRetry: TRetryEvent): THttpClientBuilder;
begin
fHasRetry := True;
fRetryMax := aMaxRetries;
fRetryDelayMs := aInitialDelayMs;
fRetryBackoff := aBackoffType;
fRetryMaxDelayMs := aMaxDelayMs;
fRetryOnRetry := aOnRetry;
Result := Self;
end;
function THttpClientBuilder.AddCircuitBreaker(aFailureThreshold: Integer;
aDurationOfBreakMs: Int64; aOnStateChange: TCircuitStateChangeEvent): THttpClientBuilder;
begin
fHasCB := True;
fCBThreshold := aFailureThreshold;
fCBDurationMs := aDurationOfBreakMs;
fCBOnChange := aOnStateChange;
Result := Self;
end;
function THttpClientBuilder.AddTimeout(aTimeoutMs: Int64;
aOnTimeout: TTimeoutEvent): THttpClientBuilder;
begin
fHasTimeout := True;
fTimeoutMs := aTimeoutMs;
fTimeoutOnTimeout := aOnTimeout;
Result := Self;
end;
function THttpClientBuilder.Services: TServiceCollection;
begin
Result := fServices;
end;
// ── TResilienceHttpClient ─────────────────────────────────────────────────────
// (internal — not exposed in the interface section)
type
TResilienceHttpClient = class(TInterfacedObject, IHttpClient)
private
fHttp : THTTPClient;
fBaseUrl : string;
fCircuitBreaker: IResiliencePolicy<IHttpResponse>;
fRetry : IResiliencePolicy<IHttpResponse>;
fTimeout : IResiliencePolicy<IHttpResponse>;
function BuildUrl(const aPath: string): string;
function Execute(aFunc: TResilienceFunc<IHttpResponse>): IHttpResponse;
function Perform(const aMethod, aUrl: string; aBody: TStream): IHttpResponse;
public
constructor Create(aOptions: THttpClientOptions;
aCB : IResiliencePolicy<IHttpResponse>;
aRetry : IResiliencePolicy<IHttpResponse>;
aTimeout: IResiliencePolicy<IHttpResponse>);
destructor Destroy; override;
function Get (const aUrl: string): IHttpResponse;
function Post (const aUrl: string; const aBody: string): IHttpResponse; overload;
function Post (const aUrl: string; aJson: TJSONObject): IHttpResponse; overload;
function Put (const aUrl: string; const aBody: string): IHttpResponse;
function Delete(const aUrl: string): IHttpResponse;
end;
constructor TResilienceHttpClient.Create(aOptions: THttpClientOptions;
aCB: IResiliencePolicy<IHttpResponse>; aRetry: IResiliencePolicy<IHttpResponse>;
aTimeout: IResiliencePolicy<IHttpResponse>);
var
pair: TPair<string, string>;
begin
inherited Create;
fBaseUrl := aOptions.BaseUrl;
fCircuitBreaker := aCB;
fRetry := aRetry;
fTimeout := aTimeout;
fHttp := THTTPClient.Create;
fHttp.ContentType := 'application/json';
fHttp.UserAgent := aOptions.UserAgent;
if aOptions.ResponseTimeout > 0 then fHttp.ResponseTimeout := aOptions.ResponseTimeout;
if aOptions.ConnectionTimeout > 0 then fHttp.ConnectionTimeout := aOptions.ConnectionTimeout;
for pair in aOptions.Headers do
fHttp.CustomHeaders[pair.Key] := pair.Value;
end;
destructor TResilienceHttpClient.Destroy;
begin
fHttp.Free;
inherited;
end;
function TResilienceHttpClient.BuildUrl(const aPath: string): string;
begin
if (fBaseUrl = '') or aPath.StartsWith('http://', True) or aPath.StartsWith('https://', True) then
Result := aPath
else
Result := fBaseUrl.TrimRight(['/']) + '/' + aPath.TrimLeft(['/']);
end;
function TResilienceHttpClient.Execute(aFunc: TResilienceFunc<IHttpResponse>): IHttpResponse;
var
f: TResilienceFunc<IHttpResponse>;
begin
f := aFunc;
// Build pipeline innermost first: Timeout → Retry → CircuitBreaker
if Assigned(fTimeout) then
begin
var inner := f;
f := function: IHttpResponse begin Result := fTimeout.Execute(inner) end;
end;
if Assigned(fRetry) then
begin
var inner := f;
f := function: IHttpResponse begin Result := fRetry.Execute(inner) end;
end;
if Assigned(fCircuitBreaker) then
begin
var inner := f;
f := function: IHttpResponse begin Result := fCircuitBreaker.Execute(inner) end;
end;
Result := f();
end;
function TResilienceHttpClient.Perform(const aMethod, aUrl: string;
aBody: TStream): IHttpResponse;
var
respStream: TStringStream;
resp : IHTTPResponse;
begin
respStream := TStringStream.Create('', TEncoding.UTF8);
try
if aMethod = 'GET' then
resp := fHttp.Get(aUrl, respStream)
else if aMethod = 'DELETE' then
resp := fHttp.Delete(aUrl, respStream)
else if aMethod = 'POST' then
resp := fHttp.Post(aUrl, aBody, respStream)
else if aMethod = 'PUT' then
resp := fHttp.Put(aUrl, aBody, respStream)
else
raise EHttpException.Create(0, 'Unsupported HTTP method: ' + aMethod);
Result := THttpResponse.Create(resp.StatusCode, resp.StatusText,
respStream.DataString);
if Result.IsServerError then
raise EHttpException.Create(Result.StatusCode,
Format('HTTP %d %s', [Result.StatusCode, Result.StatusText]));
finally
respStream.Free;
end;
end;
function TResilienceHttpClient.Get(const aUrl: string): IHttpResponse;
var
url: string;
begin
url := BuildUrl(aUrl);
Result := Execute(function: IHttpResponse begin Result := Perform('GET', url, nil) end);
end;
function TResilienceHttpClient.Post(const aUrl: string; const aBody: string): IHttpResponse;
var
url : string;
body: TStringStream;
begin
url := BuildUrl(aUrl);
body := TStringStream.Create(aBody, TEncoding.UTF8);
try
Result := Execute(function: IHttpResponse begin Result := Perform('POST', url, body) end);
finally
body.Free;
end;
end;
function TResilienceHttpClient.Post(const aUrl: string; aJson: TJSONObject): IHttpResponse;
begin
Result := Post(aUrl, aJson.ToJSON);
end;
function TResilienceHttpClient.Put(const aUrl: string; const aBody: string): IHttpResponse;
var
url : string;
body: TStringStream;
begin
url := BuildUrl(aUrl);
body := TStringStream.Create(aBody, TEncoding.UTF8);
try
Result := Execute(function: IHttpResponse begin Result := Perform('PUT', url, body) end);
finally
body.Free;
end;
end;
function TResilienceHttpClient.Delete(const aUrl: string): IHttpResponse;
var
url: string;
begin
url := BuildUrl(aUrl);
Result := Execute(function: IHttpResponse begin Result := Perform('DELETE', url, nil) end);
end;
// ── THttpClientFactory ────────────────────────────────────────────────────────
type
TClientState = record
CircuitBreaker: IResiliencePolicy<IHttpResponse>;
end;
THttpClientFactory = class(TInterfacedObject, IHttpClientFactory)
private
fBuilders : TObjectDictionary<string, THttpClientBuilder>; // not owned
fLock : TCriticalSection;
fStates : TDictionary<string, TClientState>;
function GetOrCreateState(const aName: string;
aBuilder: THttpClientBuilder): TClientState;
public
constructor Create(aBuilders: TObjectDictionary<string, THttpClientBuilder>);
destructor Destroy; override;
function CreateClient: IHttpClient; overload;
function CreateClient(const aName: string): IHttpClient; overload;
end;
constructor THttpClientFactory.Create(
aBuilders: TObjectDictionary<string, THttpClientBuilder>);
begin
inherited Create;
fBuilders := aBuilders;
fLock := TCriticalSection.Create;
fStates := TDictionary<string, TClientState>.Create;
end;
destructor THttpClientFactory.Destroy;
begin
fStates.Free;
fLock.Free;
inherited;
end;
function THttpClientFactory.GetOrCreateState(const aName: string;
aBuilder: THttpClientBuilder): TClientState;
begin
fLock.Enter;
try
if not fStates.TryGetValue(aName, Result) then
begin
// Circuit breaker is stateful — created once per named client
if aBuilder.HasCB then
Result.CircuitBreaker := TCircuitBreakerPolicy<IHttpResponse>.Create(
aBuilder.CBThreshold, aBuilder.CBDurationMs, aBuilder.CBOnChange);
fStates.Add(aName, Result);
end;
finally
fLock.Leave;
end;
end;
function THttpClientFactory.CreateClient: IHttpClient;
begin
Result := CreateClient('');
end;
function THttpClientFactory.CreateClient(const aName: string): IHttpClient;
var
builder: THttpClientBuilder;
state : TClientState;
retry : IResiliencePolicy<IHttpResponse>;
timeout: IResiliencePolicy<IHttpResponse>;
begin
if not fBuilders.TryGetValue(aName, builder) then
raise EArgumentException.CreateFmt(
'HttpClientFactory: no client registered with name "%s"', [aName]);
state := GetOrCreateState(aName, builder);
// Retry and Timeout: stateless, created fresh each time (lightweight)
retry := nil;
timeout := nil;
if builder.HasRetry then
retry := TRetryPolicy<IHttpResponse>.Create(builder.RetryMax,
builder.RetryDelayMs, builder.RetryBackoff, builder.RetryMaxDelayMs,
builder.RetryOnRetry);
if builder.HasTimeout then
timeout := TTimeoutPolicy<IHttpResponse>.Create(builder.TimeoutMs,
builder.TimeoutOnTimeout);
Result := TResilienceHttpClient.Create(builder.Options,
state.CircuitBreaker, retry, timeout);
end;
// ── THttpClientServiceExtension ───────────────────────────────────────────────
class function THttpClientServiceExtension.EnsureRegistry: TObjectDictionary<string, THttpClientBuilder>;
begin
if not Assigned(fBuilders) then
fBuilders := TObjectDictionary<string, THttpClientBuilder>.Create([doOwnsValues]);
Result := fBuilders;
end;
class function THttpClientServiceExtension.AddHttpClient(const aName: string;
aConfigure: TProc<THttpClientOptions>): THttpClientBuilder;
var
opts : THttpClientOptions;
builder: THttpClientBuilder;
reg : TObjectDictionary<string, THttpClientBuilder>;
begin
reg := EnsureRegistry;
opts := THttpClientOptions.Create;
if Assigned(aConfigure) then
aConfigure(opts);
builder := THttpClientBuilder.Create(ServiceCollection, aName, opts);
reg.AddOrSetValue(aName, builder);
// Register IHttpClientFactory as singleton (lazy, only once)
if not ServiceCollection.IsRegistered<IHttpClientFactory> then
ServiceCollection.AddSingleton<IHttpClientFactory>(
function: IHttpClientFactory
begin
Result := THttpClientFactory.Create(fBuilders);
end);
Result := builder;
end;
end.