-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathUnleashBuilder.php
executable file
·613 lines (518 loc) · 20.7 KB
/
UnleashBuilder.php
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
<?php
namespace Unleash\Client;
use JetBrains\PhpStorm\Immutable;
use JetBrains\PhpStorm\Pure;
use JsonSerializable;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\SimpleCache\CacheInterface;
use SplFileInfo;
use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Traversable;
use Unleash\Client\Bootstrap\BootstrapHandler;
use Unleash\Client\Bootstrap\BootstrapProvider;
use Unleash\Client\Bootstrap\DefaultBootstrapHandler;
use Unleash\Client\Bootstrap\EmptyBootstrapProvider;
use Unleash\Client\Bootstrap\FileBootstrapProvider;
use Unleash\Client\Bootstrap\JsonBootstrapProvider;
use Unleash\Client\Bootstrap\JsonSerializableBootstrapProvider;
use Unleash\Client\Client\DefaultRegistrationService;
use Unleash\Client\Client\RegistrationService;
use Unleash\Client\Configuration\Context;
use Unleash\Client\Configuration\UnleashConfiguration;
use Unleash\Client\ContextProvider\DefaultUnleashContextProvider;
use Unleash\Client\ContextProvider\UnleashContextProvider;
use Unleash\Client\Exception\CyclicDependencyException;
use Unleash\Client\Exception\InvalidValueException;
use Unleash\Client\Helper\Builder\CacheAware;
use Unleash\Client\Helper\Builder\ConfigurationAware;
use Unleash\Client\Helper\Builder\HttpClientAware;
use Unleash\Client\Helper\Builder\MetricsSenderAware;
use Unleash\Client\Helper\Builder\RequestFactoryAware;
use Unleash\Client\Helper\Builder\StaleCacheAware;
use Unleash\Client\Helper\Builder\StickinessCalculatorAware;
use Unleash\Client\Helper\DefaultImplementationLocator;
use Unleash\Client\Helper\UnleashBuilderContainer;
use Unleash\Client\Metrics\DefaultMetricsBucketSerializer;
use Unleash\Client\Metrics\DefaultMetricsHandler;
use Unleash\Client\Metrics\DefaultMetricsSender;
use Unleash\Client\Metrics\MetricsBucketSerializer;
use Unleash\Client\Metrics\MetricsHandler;
use Unleash\Client\Repository\DefaultUnleashProxyRepository;
use Unleash\Client\Repository\DefaultUnleashRepository;
use Unleash\Client\Stickiness\MurmurHashCalculator;
use Unleash\Client\Strategy\ApplicationHostnameStrategyHandler;
use Unleash\Client\Strategy\DefaultStrategyHandler;
use Unleash\Client\Strategy\GradualRolloutRandomStrategyHandler;
use Unleash\Client\Strategy\GradualRolloutSessionIdStrategyHandler;
use Unleash\Client\Strategy\GradualRolloutStrategyHandler;
use Unleash\Client\Strategy\GradualRolloutUserIdStrategyHandler;
use Unleash\Client\Strategy\IpAddressStrategyHandler;
use Unleash\Client\Strategy\StrategyHandler;
use Unleash\Client\Strategy\UserIdStrategyHandler;
use Unleash\Client\Variant\DefaultVariantHandler;
use Unleash\Client\Variant\VariantHandler;
#[Immutable]
final class UnleashBuilder
{
private DefaultImplementationLocator $defaultImplementationLocator;
private ?string $appUrl = null;
private ?string $instanceId = null;
private ?string $appName = null;
private ?ClientInterface $httpClient = null;
private ?RequestFactoryInterface $requestFactory = null;
private ?CacheInterface $cache = null;
private ?CacheInterface $staleCache = null;
private ?CacheInterface $metricsCache = null;
private ?int $cacheTtl = null;
private ?int $staleTtl = null;
private ?RegistrationService $registrationService = null;
private bool $autoregister = true;
private ?bool $metricsEnabled = null;
private ?int $metricsInterval = null;
private ?Context $defaultContext = null;
private ?UnleashContextProvider $contextProvider = null;
private ?BootstrapProvider $bootstrapProvider = null;
private ?BootstrapHandler $bootstrapHandler = null;
private ?string $proxyKey = null;
private bool $fetchingEnabled = true;
/**
* @var array<string,string>
*/
private array $headers = [];
/**
* @var array<StrategyHandler>
*/
private array $strategies;
private ?EventDispatcherInterface $eventDispatcher = null;
/**
* @var array<EventSubscriberInterface>
*/
private array $eventSubscribers = [];
private ?MetricsHandler $metricsHandler = null;
private ?VariantHandler $variantHandler = null;
private ?MetricsBucketSerializer $metricsBucketSerializer = null;
public function __construct()
{
$this->defaultImplementationLocator = new DefaultImplementationLocator();
if (class_exists(EventDispatcher::class)) {
$this->eventDispatcher = new EventDispatcher();
}
$rolloutStrategyHandler = new GradualRolloutStrategyHandler(new MurmurHashCalculator());
$this->strategies = [
new DefaultStrategyHandler(),
new IpAddressStrategyHandler(),
new UserIdStrategyHandler(),
$rolloutStrategyHandler,
new ApplicationHostnameStrategyHandler(),
new GradualRolloutUserIdStrategyHandler($rolloutStrategyHandler),
new GradualRolloutSessionIdStrategyHandler($rolloutStrategyHandler),
new GradualRolloutRandomStrategyHandler($rolloutStrategyHandler),
];
}
public static function create(): self
{
return new self();
}
public static function createForGitlab(): self
{
return self::create()
->withMetricsEnabled(false)
->withAutomaticRegistrationEnabled(false);
}
#[Pure]
public function withAppUrl(string $appUrl): self
{
return $this->with('appUrl', $appUrl);
}
#[Pure]
public function withInstanceId(string $instanceId): self
{
return $this->with('instanceId', $instanceId);
}
#[Pure]
public function withAppName(string $appName): self
{
return $this->with('appName', $appName);
}
#[Pure]
public function withGitlabEnvironment(string $environment): self
{
return $this->withAppName($environment);
}
#[Pure]
public function withHttpClient(ClientInterface $client): self
{
return $this->with('httpClient', $client);
}
#[Pure]
public function withRequestFactory(RequestFactoryInterface $requestFactory): self
{
return $this->with('requestFactory', $requestFactory);
}
#[Pure]
public function withStrategies(StrategyHandler ...$strategies): self
{
return $this->with('strategies', $strategies);
}
#[Pure]
public function withStrategy(StrategyHandler $strategy): self
{
return $this->withStrategies(...array_merge($this->strategies, [$strategy]));
}
#[Pure]
public function withCacheHandler(?CacheInterface $cache, ?int $timeToLive = null): self
{
$result = $this->with('cache', $cache);
if ($timeToLive !== null) {
$result = $result->withCacheTimeToLive($timeToLive);
}
return $result;
}
#[Pure]
public function withStaleCacheHandler(?CacheInterface $cache): self
{
return $this->with('staleCache', $cache);
}
#[Pure]
public function withMetricsCacheHandler(?CacheInterface $cache): self
{
return $this->with('metricsCache', $cache);
}
#[Pure]
public function withCacheTimeToLive(int $timeToLive): self
{
return $this->with('cacheTtl', $timeToLive);
}
#[Pure]
public function withHeader(string $header, string $value): self
{
return $this->with('headers', array_merge($this->headers, [$header => $value]));
}
/**
* @param array<string, string> $headers
*/
#[Pure]
public function withHeaders(array $headers): self
{
return $this->with('headers', $headers);
}
#[Pure]
public function withRegistrationService(RegistrationService $registrationService): self
{
return $this->with('registrationService', $registrationService);
}
#[Pure]
public function withAutomaticRegistrationEnabled(bool $enabled): self
{
return $this->with('autoregister', $enabled);
}
#[Pure]
public function withMetricsEnabled(bool $enabled): self
{
return $this->with('metricsEnabled', $enabled);
}
#[Pure]
public function withMetricsInterval(int $milliseconds): self
{
return $this->with('metricsInterval', $milliseconds);
}
#[Pure]
public function withContextProvider(?UnleashContextProvider $contextProvider): self
{
return $this->with('contextProvider', $contextProvider);
}
#[Pure]
public function withBootstrapHandler(?BootstrapHandler $handler): self
{
return $this->with('bootstrapHandler', $handler);
}
#[Pure]
public function withBootstrapProvider(?BootstrapProvider $provider): self
{
return $this->with('bootstrapProvider', $provider);
}
/**
* @param array<mixed>|Traversable<mixed>|JsonSerializable|null|string $bootstrap
*/
#[Pure]
public function withBootstrap(array|Traversable|JsonSerializable|null|string $bootstrap): self
{
if ($bootstrap === null) {
$provider = new EmptyBootstrapProvider();
} elseif (is_string($bootstrap)) {
$provider = new JsonBootstrapProvider($bootstrap);
} else {
$provider = new JsonSerializableBootstrapProvider($bootstrap);
}
return $this->withBootstrapProvider($provider);
}
#[Pure]
public function withBootstrapFile(string|SplFileInfo|null $file): self
{
if ($file === null) {
$provider = new EmptyBootstrapProvider();
} else {
$provider = new FileBootstrapProvider($file);
}
return $this->withBootstrapProvider($provider);
}
#[Pure]
public function withBootstrapUrl(?string $url): self
{
return $this->withBootstrapFile($url);
}
#[Pure]
public function withFetchingEnabled(bool $enabled): self
{
return $this->with('fetchingEnabled', $enabled);
}
#[Pure]
public function withEventDispatcher(?EventDispatcherInterface $eventDispatcher): self
{
return $this->with('eventDispatcher', $eventDispatcher);
}
public function withEventSubscriber(EventSubscriberInterface $eventSubscriber): self
{
$subscribers = $this->eventSubscribers;
$subscribers[] = $eventSubscriber;
return $this->with('eventSubscribers', $subscribers);
}
#[Pure]
public function withStaleTtl(?int $ttl): self
{
return $this->with('staleTtl', $ttl);
}
#[Pure]
public function withMetricsHandler(?MetricsHandler $metricsHandler): self
{
return $this->with('metricsHandler', $metricsHandler);
}
#[Pure]
public function withVariantHandler(?VariantHandler $variantHandler): self
{
return $this->with('variantHandler', $variantHandler);
}
#[Pure]
public function withProxy(?string $proxyKey): self
{
return $this->with('proxyKey', $proxyKey);
}
#[Pure]
public function withMetricsBucketSerializer(?MetricsBucketSerializer $metricsBucketSerializer): self
{
return $this->with('metricsBucketSerializer', $metricsBucketSerializer);
}
public function build(): Unleash
{
// basic scalar attributes
$appUrl = $this->appUrl;
$instanceId = $this->instanceId;
$appName = $this->appName;
if (!$this->fetchingEnabled) {
$appUrl ??= 'http://127.0.0.1';
$instanceId ??= 'dev';
$appName ??= 'dev';
}
if ($appUrl === null) {
throw new InvalidValueException("App url must be set, please use 'withAppUrl()' method");
}
if ($instanceId === null) {
throw new InvalidValueException("Instance ID must be set, please use 'withInstanceId()' method");
}
if ($appName === null) {
throw new InvalidValueException(
"App name must be set, please use 'withAppName()' or 'withGitlabEnvironment()' method"
);
}
// PSR services
$cache = $this->cache;
if ($cache === null) {
$cache = $this->defaultImplementationLocator->findCache();
if ($cache === null) {
throw new InvalidValueException(
sprintf(
"No cache implementation provided, please use 'withCacheHandler()' method or install one of officially supported clients: '%s'",
implode("', '", $this->defaultImplementationLocator->getCachePackages())
)
);
}
}
assert($cache instanceof CacheInterface);
$staleCache = $this->staleCache ?? $cache;
$metricsCache = $this->metricsCache ?? $cache;
$httpClient = $this->httpClient;
if ($httpClient === null) {
$httpClient = $this->defaultImplementationLocator->findHttpClient();
if ($httpClient === null) {
throw new InvalidValueException(
"No http client provided, please use 'withHttpClient()' method or install a package providing 'psr/http-client-implementation'.",
);
}
}
assert($httpClient instanceof ClientInterface);
$requestFactory = $this->requestFactory;
if ($requestFactory === null) {
$requestFactory = $this->defaultImplementationLocator->findRequestFactory();
/**
* This will only be thrown if a HTTP client was found, but a request factory is not.
* Due to how php-http/discovery works, this scenario is unlikely to happen.
* See linked comment for more info.
*
* https://github.com/Unleash/unleash-client-php/pull/27#issuecomment-920764416
*/
// @codeCoverageIgnoreStart
if ($requestFactory === null) {
throw new InvalidValueException(
"No request factory provided, please use 'withRequestFactory()' method or install a package providing 'psr/http-factory-implementation'.",
);
}
// @codeCoverageIgnoreEnd
}
assert($requestFactory instanceof RequestFactoryInterface);
// internal shared services needed for UnleashConfiguration
$hashCalculator = new MurmurHashCalculator();
$dependencyContainer = new UnleashBuilderContainer(
cache: $cache,
staleCache: $staleCache,
httpClient: $httpClient,
metricsSender: null,
requestFactory: $requestFactory,
stickinessCalculator: $hashCalculator,
configuration: null,
);
$contextProvider = $this->contextProvider;
if ($contextProvider === null) {
$contextProvider = new DefaultUnleashContextProvider();
}
$bootstrapHandler = $this->bootstrapHandler ?? new DefaultBootstrapHandler();
$bootstrapProvider = $this->bootstrapProvider ?? new EmptyBootstrapProvider();
$eventDispatcher = $this->eventDispatcher ?? new EventDispatcher();
foreach ($this->eventSubscribers as $eventSubscriber) {
$eventDispatcher->addSubscriber($eventSubscriber);
}
$metricsBucketSerializer = $this->metricsBucketSerializer ?? new DefaultMetricsBucketSerializer();
// initialize services
$this->initializeServices($contextProvider, $dependencyContainer);
$this->initializeServices($bootstrapHandler, $dependencyContainer);
$this->initializeServices($bootstrapProvider, $dependencyContainer);
if ($eventDispatcher !== null) {
$this->initializeServices($eventDispatcher, $dependencyContainer);
}
foreach ($this->eventSubscribers as $eventSubscriber) {
$this->initializeServices($eventSubscriber, $dependencyContainer);
}
$configuration = new UnleashConfiguration($appUrl, $appName, $instanceId);
$configuration
->setCache($cache)
->setStaleCache($staleCache)
->setMetricsCache($metricsCache)
->setTtl($this->cacheTtl ?? $configuration->getTtl())
->setStaleTtl($this->staleTtl ?? $configuration->getStaleTtl())
->setMetricsEnabled($this->metricsEnabled ?? $configuration->isMetricsEnabled())
->setMetricsInterval($this->metricsInterval ?? $configuration->getMetricsInterval())
->setHeaders($this->headers)
->setAutoRegistrationEnabled($this->autoregister)
->setContextProvider($contextProvider)
->setBootstrapHandler($bootstrapHandler)
->setBootstrapProvider($bootstrapProvider)
->setFetchingEnabled($this->fetchingEnabled)
->setEventDispatcher($eventDispatcher)
->setMetricsBucketSerializer($metricsBucketSerializer)
;
// runtime-unchangeable blocks of Unleash
$repository = new DefaultUnleashRepository($httpClient, $requestFactory, $configuration);
$metricsSender = new DefaultMetricsSender($httpClient, $requestFactory, $configuration);
$dependencyContainer = new UnleashBuilderContainer(
cache: $cache,
staleCache: $staleCache,
httpClient: $httpClient,
metricsSender: $metricsSender,
requestFactory: $requestFactory,
stickinessCalculator: $hashCalculator,
configuration: $configuration,
);
$registrationService = $this->registrationService;
if ($registrationService === null) {
$registrationService = new DefaultRegistrationService($httpClient, $requestFactory, $configuration);
}
$metricsHandler = $this->metricsHandler ?? new DefaultMetricsHandler($metricsSender, $configuration);
$variantHandler = $this->variantHandler ?? new DefaultVariantHandler($hashCalculator);
// initialization of dependencies
foreach ($this->strategies as $strategy) {
$this->initializeServices($strategy, $dependencyContainer);
}
$this->initializeServices($repository, $dependencyContainer);
$this->initializeServices($registrationService, $dependencyContainer);
$this->initializeServices($metricsHandler, $dependencyContainer);
$this->initializeServices($variantHandler, $dependencyContainer);
if ($this->proxyKey !== null) {
$configuration->setProxyKey($this->proxyKey);
$configuration->setHeaders(array_merge($this->headers, ['Authorization' => $this->proxyKey]));
$proxyRepository = new DefaultUnleashProxyRepository(
$configuration,
$httpClient,
$requestFactory,
);
return new DefaultProxyUnleash(
$proxyRepository,
$metricsHandler,
);
} else {
return new DefaultUnleash(
$this->strategies,
$repository,
$registrationService,
$configuration,
$metricsHandler,
$variantHandler,
);
}
}
private function with(string $property, mixed $value): self
{
$copy = clone $this;
$copy->{$property} = $value;
return $copy;
}
private function initializeServices(object $target, UnleashBuilderContainer $container): void
{
if ($target instanceof CacheAware) {
$target->setCache($container->getCache());
}
if ($target instanceof ConfigurationAware) {
if ($configuration = $container->getConfiguration()) {
$target->setConfiguration($configuration);
} else {
throw new CyclicDependencyException(sprintf(
"A dependency '%s' is tagged as ConfigurationAware but that would cause a cyclic dependency as it needs to be part of Configuration",
$target::class,
));
}
}
if ($target instanceof HttpClientAware) {
$target->setHttpClient($container->getHttpClient());
}
if ($target instanceof MetricsSenderAware) {
if ($sender = $container->getMetricsSender()) {
$target->setMetricsSender($sender);
} else {
throw new CyclicDependencyException(sprintf(
"A dependency '%s' is tagged as MetricsSenderAware but MetricsSender is not available for this type of dependency",
$target::class,
));
}
}
if ($target instanceof RequestFactoryAware) {
$target->setRequestFactory($container->getRequestFactory());
}
if ($target instanceof StaleCacheAware) {
$target->setStaleCache($container->getStaleCache());
}
if ($target instanceof StickinessCalculatorAware) {
$target->setStickinessCalculator($container->getStickinessCalculator());
}
}
}