Commit c8c15069 authored by catch's avatar catch
Browse files

task: #3622391 Use tagged iterators in CacheTagsInvalidator

By: longwave
By: smustgrave
By: mfb
By: berdir
By: bceyssens
(cherry picked from commit af2ff7c4)
parent 04671a87
Loading
Loading
Loading
Loading
Loading
+1 −4
Changes for core/core.services.yml: 1 added line, 4 removed lines.
Original line number Diff line number Diff line
@@ -246,10 +246,7 @@ services:
  Drupal\Core\Cache\Context\CacheContextsManager: '@cache_contexts_manager'
  cache_tags.invalidator:
    class: Drupal\Core\Cache\CacheTagsInvalidator
    tags:
      - { name: service_collector, call: addInvalidator, tag: cache_tags_invalidator }
      - { name: service_collector, call: addBin, tag: cache.bin }
      - { name: service_collector, call: addBin, tag: cache.bin.memory }
    arguments: [!tagged_iterator cache_tags_invalidator, !tagged_iterator cache.bin, !tagged_iterator cache.bin.memory]
  Drupal\Core\Cache\CacheTagsInvalidatorInterface: '@cache_tags.invalidator'
  cache_tags.invalidator.checksum:
    class: Drupal\Core\Cache\DatabaseCacheTagsChecksum
+10 −16
Changes for core/lib/Drupal/Core/Cache/CacheTagsInvalidator.php: 10 added lines, 16 removed lines.
Original line number Diff line number Diff line
@@ -9,19 +9,11 @@
 */
class CacheTagsInvalidator implements CacheTagsInvalidatorInterface, CacheTagsPurgeInterface {

  /**
   * Holds an array of cache tags invalidators.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface[]
   */
  protected $invalidators = [];

  /**
   * Holds an array of cache bins that support invalidations.
   *
   * @var \Drupal\Core\Cache\CacheTagsInvalidatorInterface[]
   */
  protected array $bins = [];
  public function __construct(
    protected iterable $invalidators = [],
    protected iterable $bins = [],
    protected iterable $memoryBins = [],
  ) {}

  /**
   * {@inheritdoc}
@@ -35,10 +27,12 @@ public function invalidateTags(array $tags) {
    }

    // Additionally, notify each cache bin if it implements the service.
    foreach ($this->bins as $bin) {
    foreach ([...$this->bins, ...$this->memoryBins] as $bin) {
      if ($bin instanceof CacheTagsInvalidatorInterface) {
        $bin->invalidateTags($tags);
      }
    }
  }

  /**
   * Reset statically cached tags in all cache tag checksum services.
@@ -71,7 +65,7 @@ public function purge(): void {
   *   A cache invalidator.
   */
  public function addInvalidator(CacheTagsInvalidatorInterface $invalidator) {
    $this->invalidators[] = $invalidator;
    $this->invalidators = [...$this->invalidators, $invalidator];
  }

  /**
@@ -82,7 +76,7 @@ public function addInvalidator(CacheTagsInvalidatorInterface $invalidator) {
   */
  public function addBin(CacheBackendInterface $bin): void {
    if ($bin instanceof CacheTagsInvalidatorInterface) {
      $this->bins[] = $bin;
      $this->bins = [...$this->bins, $bin];
    }
  }

+101
Changes for core/tests/Drupal/KernelTests/Core/Cache/CacheTagsInvalidatorTest.php: 101 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\KernelTests\Core\Cache;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Cache\MemoryBackend;
use Drupal\Core\Cache\NullBackend;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\KernelTests\KernelTestBase;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use PHPUnit\Framework\Attributes\TestWith;
use Symfony\Component\DependencyInjection\Reference;

/**
 * Tests lazy cache tag invalidation services.
 */
#[Group('Cache')]
#[RunTestsInSeparateProcesses]
class CacheTagsInvalidatorTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public function register(ContainerBuilder $container): void {
    parent::register($container);
    foreach (['cache_tags_invalidator', 'cache.bin', 'cache.bin.memory'] as $tag) {
      $container->register('test.' . $tag, DependentMemoryBackend::class)
        ->addArgument(new Reference('datetime.time'))
        ->addArgument(new Reference('cache_tags.invalidator'))
        ->addTag($tag);
    }
    $container->register('test.non_invalidating_bin', NullBackend::class)
      ->addArgument('test')
      ->addTag('cache.bin');
  }

  /**
   * Tests tagged services are only initialized when needed.
   */
  public function testLazyInvalidation(): void {
    $invalidator = $this->container->get('cache_tags.invalidator');
    $services = ['test.cache_tags_invalidator', 'test.cache.bin', 'test.cache.bin.memory', 'test.non_invalidating_bin'];
    foreach ($services as $id) {
      $this->assertFalse($this->container->initialized($id), $id);
    }

    $invalidator->invalidateTags(['test']);
    foreach ($services as $id) {
      $this->assertTrue($this->container->initialized($id), $id);
    }

    // The tagged iterators must be reusable on subsequent invalidations.
    for ($i = 0; $i < 2; $i++) {
      foreach (array_slice($services, 0, 3) as $id) {
        $this->container->get($id)->set('item', 'value', Cache::PERMANENT, ['test']);
        $this->assertNotFalse($this->container->get($id)->get('item'));
      }
      $invalidator->invalidateTags(['test']);
      foreach (array_slice($services, 0, 3) as $id) {
        $this->assertFalse($this->container->get($id)->get('item'));
      }
    }
  }

  /**
   * Tests checksum operations do not initialize cache bins.
   */
  #[TestWith(['resetChecksums'])]
  #[TestWith(['purge'])]
  public function testLazyChecksumOperation(string $method): void {
    $invalidator = $this->container->get('cache_tags.invalidator');
    $this->assertFalse($this->container->initialized('test.cache_tags_invalidator'));
    for ($i = 0; $i < 2; $i++) {
      $invalidator->$method();
      $this->assertTrue($this->container->initialized('test.cache_tags_invalidator'));
      $this->assertFalse($this->container->initialized('test.cache.bin'));
      $this->assertFalse($this->container->initialized('test.cache.bin.memory'));
      $this->assertFalse($this->container->initialized('test.non_invalidating_bin'));
    }
  }

}

/**
 * A cache backend that depends on the cache tags invalidator.
 */
class DependentMemoryBackend extends MemoryBackend {

  /**
   * Constructs a DependentMemoryBackend object.
   */
  public function __construct(TimeInterface $time, protected CacheTagsInvalidatorInterface $invalidator) {
    parent::__construct($time);
  }

}
+55
Changes for core/tests/Drupal/Tests/Core/Cache/CacheTagsInvalidatorTest.php: 55 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -5,11 +5,14 @@
namespace Drupal\Tests\Core\Cache;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\CacheTagsChecksumInterface;
use Drupal\Core\Cache\CacheTagsInvalidator;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Cache\CacheTagsPurgeInterface;
use Drupal\Tests\UnitTestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\TestWith;

/**
 * Tests Drupal\Core\Cache\CacheTagsInvalidator.
@@ -58,9 +61,61 @@ public function testInvalidateTags(): void {
    $cache_tags_invalidator->invalidateTags(['node:1']);
  }

  /**
   * Tests injected iterators and runtime additions support repeated operations.
   */
  #[TestWith([FALSE])]
  #[TestWith([TRUE])]
  public function testIteratorsWithRuntimeAdditions(bool $add_at_runtime): void {
    $invalidators = [];
    for ($i = 0; $i < 2; $i++) {
      $invalidator = $this->createMock(ChecksumInvalidatorInterface::class);
      $invalidator->expects($this->exactly(2))->method('invalidateTags')->with(['node:1']);
      $invalidator->expects($this->exactly(2))->method('reset');
      $invalidator->expects($this->exactly(2))->method('purge');
      $invalidators[] = $invalidator;
    }
    $bins = [];
    for ($i = 0; $i < 3; $i++) {
      $bin = $this->createMock(InvalidatingCacheBackendInterface::class);
      $bin->expects($this->exactly(2))->method('invalidateTags')->with(['node:1']);
      $bins[] = $bin;
    }
    $non_invalidating_bin = $this->createStub(CacheBackendInterface::class);
    $plain_invalidator = $this->createMock(CacheTagsInvalidatorInterface::class);
    $plain_invalidator->expects($this->exactly(2))->method('invalidateTags')->with(['node:1']);
    $injected_invalidators = [$invalidators[0], $plain_invalidator];
    $injected_bins = [$non_invalidating_bin, $bins[0]];
    if (!$add_at_runtime) {
      $injected_invalidators[] = $invalidators[1];
      $injected_bins[] = $bins[2];
    }
    $cache_tags_invalidator = new CacheTagsInvalidator(
      new \ArrayIterator($injected_invalidators),
      new \ArrayIterator($injected_bins),
      new \ArrayIterator([$non_invalidating_bin, $bins[1]]),
    );
    if ($add_at_runtime) {
      $cache_tags_invalidator->addInvalidator($invalidators[1]);
      $cache_tags_invalidator->addBin($bins[2]);
      $cache_tags_invalidator->addBin($non_invalidating_bin);
    }

    for ($i = 0; $i < 2; $i++) {
      $cache_tags_invalidator->invalidateTags(['node:1']);
      $cache_tags_invalidator->resetChecksums();
      $cache_tags_invalidator->purge();
    }
  }

}

/**
 * Test interface for testing the cache tags validator.
 */
interface InvalidatingCacheBackendInterface extends CacheTagsInvalidatorInterface, CacheBackendInterface {}

/**
 * A cache tags invalidator that supports checksum resets and purging.
 */
interface ChecksumInvalidatorInterface extends CacheTagsInvalidatorInterface, CacheTagsChecksumInterface, CacheTagsPurgeInterface {}