summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/PreWarm/CachePreWarmer.php
blob: 7d92cc5d3f283cfcf6cfbd0e793667007bcc8b29 (plain) (blame)
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
<?php

namespace Drupal\Core\PreWarm;

use Drupal\Core\DependencyInjection\ClassResolverInterface;

// cspell:ignore ABCDEF FCDABE BEDAFC

/**
 * Prewarms caches for services that implement PreWarmableInterface.
 *
 * Takes a list of prewarmable services and prewarms them at random.
 * Randomization is used because whenever two or more requests are building
 * caches, the most benefit is gained by minimizing duplication. For example
 * two requests rely on the same six services but these services are requested
 * at different times, one request builds caches for the other and vice versa.
 *
 * No randomization:
 *
 * ABCDEF
 * ABCDEF
 *
 * Randomization:
 *
 * ABCDEF
 * FCDABE
 *
 * Randomization and three requests:
 *
 * ABCDEF
 * FCDABE
 * BEDAFC
 *
 * @internal
 *
 * @see Drupal\Core\PreWarm\PreWarmableInterface
 * @see Drupal\Core\DrupalKernel::handle()
 * @see Drupal\Core\LockBackendAbstract::wait()
 * @see Drupal\Core\Routing\RouteProvider::preLoadRoutes()
 */
class CachePreWarmer implements CachePreWarmerInterface {

  /**
   * Whether to prewarm caches at the end of the request.
   */
  protected bool $needsPreWarming = FALSE;

  public function __construct(
    protected readonly ClassResolverInterface $classResolver,
    protected array $serviceIds,
  ) {
    // Ensure the serviceId order is random to reduce chances of conflicts.
    shuffle($this->serviceIds);
  }

  /**
   * {@inheritdoc}
   */
  public function preWarmOneCache(): bool {
    $candidate = array_pop($this->serviceIds);
    if ($candidate === NULL) {
      return FALSE;
    }
    $service = $this->classResolver->getInstanceFromDefinition($candidate);
    $service->preWarm();
    return TRUE;
  }

  /**
   * {@inheritdoc}
   */
  public function preWarmAllCaches(): bool {
    $prewarmed = FALSE;
    while ($this->preWarmOneCache()) {
      $prewarmed = TRUE;
    }
    return $prewarmed;
  }

}