Unverified Commit 3245d571 authored by Alex Pott's avatar Alex Pott
Browse files

perf: #3564937 Remove duplicative caching of views rows

By: catch
parent 9e6f0a2c
Loading
Loading
Loading
Loading
Loading
+10 −0
Changes for core/modules/views/src/Plugin/views/cache/CachePluginBase.php: 10 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -338,8 +338,13 @@ public function getRowCacheTags(ResultRow $row) {
   *
   * @return string[]
   *   The row cache keys.
   *
   * @deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. There
   * is no replacement.
   * @see https://www.drupal.org/node/3564958
   */
  public function getRowCacheKeys(ResultRow $row) {
    @trigger_error(__METHOD__ . ' is deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. There is no replacement. See https://www.drupal.org/node/3564958', E_USER_DEPRECATED);
    return [
      'views',
      'fields',
@@ -357,8 +362,13 @@ public function getRowCacheKeys(ResultRow $row) {
   *
   * @return string
   *   The row identifier.
   *
   * @deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. There
   * is no replacement.
   * @see https://www.drupal.org/node/3564958
   */
  public function getRowId(ResultRow $row) {
    @trigger_error(__METHOD__ . ' is deprecated in drupal:11.4.0 and is removed from drupal:13.0.0. There is no replacement. See https://www.drupal.org/node/3564958', E_USER_DEPRECATED);
    // Here we compute a unique identifier for the row by computing the hash of
    // its data. We exclude the current index, since the same row could have a
    // different result index depending on the user permissions. We exclude also
+0 −11
Changes for core/modules/views/src/Plugin/views/style/StylePluginBase.php: 0 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -686,24 +686,13 @@ protected function renderFields(array $result) {
        foreach ($result as $index => $row) {
          $this->view->row_index = $index;

          // Here we implement render caching for result rows. Since we never
          // build a render array for single rows, given that style templates
          // need individual field markup to support proper theming, we build
          // a raw render array containing all field render arrays and cache it.
          // This allows us to cache the markup of the various children, that is
          // individual fields, which is then available for style template
          // preprocess functions, later in the rendering workflow.
          // @todo Fetch all the available cached row items in one single cache
          //   get operation, once https://www.drupal.org/node/2453945 is fixed.
          $data = [
            '#pre_render' => [[$this, 'elementPreRenderRow']],
            '#row' => $row,
            '#cache' => [
              'keys' => $cache_plugin->getRowCacheKeys($row),
              'tags' => $cache_plugin->getRowCacheTags($row),
              'max-age' => $max_age,
            ],
            '#cache_properties' => $field_ids,
          ];
          $renderer->addCacheableDependency($data, $this->view->storage);
          // Views may be rendered both inside and outside a render context:
+0 −503
Changes for core/modules/views/tests/modules/views_test_config/test_views/views.view.test_row_render_cache.yml: 0 added lines, 503 removed lines.
Original line number Diff line number Diff line
langcode: en
status: true
dependencies:
  config:
    - system.menu.tools
  module:
    - node
id: test_row_render_cache
label: 'Test render cache'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
display:
  default:
    display_plugin: default
    id: default
    display_title: Default
    position: 0
    display_options:
      access:
        type: none
        options: {  }
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 10
          offset: 0
          id: 0
          total_pages: null
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          tags:
            previous: '‹ Previous'
            next: 'Next ›'
            first: '« First'
            last: 'Last »'
          quantity: 9
      style:
        type: table
        options:
          grouping: {  }
          class: ''
          row_class: ''
          default_row_class: true
          override: true
          sticky: false
          caption: ''
          summary: ''
          description: ''
          columns:
            counter: counter
            title: title
            edit_node: edit_node
            delete_node: delete_node
            operations: operations
          info:
            counter:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            title:
              sortable: true
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            edit_node:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            delete_node:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
            operations:
              sortable: false
              default_sort_order: asc
              align: ''
              separator: ''
              empty_column: false
              responsive: ''
          default: '-1'
          empty_table: false
      row:
        type: fields
        options:
          inline: {  }
          separator: ''
          hide_empty: false
          default_field_elements: true
      fields:
        nid:
          id: nid
          table: node_field_data
          field: nid
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: true
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: number_integer
          settings:
            thousand_separator: ''
            prefix_suffix: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: nid
          plugin_id: field
        counter:
          id: counter
          table: views
          field: counter
          relationship: none
          group_type: group
          admin_label: ''
          label: Index
          exclude: false
          alter:
            alter_text: true
            text: '{{ nid }}: {{ counter }} (just in case: {{ nid }})'
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          counter_start: 1
          plugin_id: counter
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          label: Title
          exclude: false
          alter:
            alter_text: true
            text: '<span class="da-title">{{ title }}</span> <span class="counter">{{ counter }}</span>'
            make_link: true
            path: 'node/{{ nid }}'
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: false
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        edit_node:
          id: edit_node
          table: node
          field: edit_node
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          text: ''
          entity_type: node
          plugin_id: entity_link_edit
        delete_node:
          id: delete_node
          table: node
          field: delete_node
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          text: ''
          entity_type: node
          plugin_id: entity_link_delete
        operations:
          id: operations
          table: node
          field: operations
          relationship: none
          group_type: group
          admin_label: ''
          label: Operations
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: true
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          destination: true
          entity_type: node
          plugin_id: entity_operations
      filters:
        status:
          value: '1'
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
      sorts:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          order: ASC
          exposed: false
          expose:
            label: ''
          entity_type: node
          entity_field: title
          plugin_id: standard
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - 'user.node_grants:view'
      max-age: 0
+0 −503

File deleted.

Preview size limit exceeded, changes collapsed.

+0 −225
Changes for core/modules/views/tests/src/Kernel/Plugin/RowRenderCacheTest.php: 0 added lines, 225 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Tests\views\Kernel\Plugin;

use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Html;
use Drupal\Core\Session\AccountInterface;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\node\NodeInterface;
use Drupal\Tests\user\Traits\UserCreationTrait;
use Drupal\Tests\views\Kernel\ViewsKernelTestBase;
use Drupal\views\Views;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests row render caching.
 */
#[Group('views')]
#[RunTestsInSeparateProcesses]
class RowRenderCacheTest extends ViewsKernelTestBase {

  use UserCreationTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['user', 'node'];

  /**
   * Views used by this test.
   *
   * @var array
   */
  public static $testViews = ['test_row_render_cache', 'test_row_render_cache_none'];

  /**
   * An editor user account.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $editorUser;

  /**
   * A power user account.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $powerUser;

  /**
   * A regular user account.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $regularUser;

  /**
   * {@inheritdoc}
   */
  protected function setUpFixtures(): void {
    parent::setUpFixtures();

    $this->installEntitySchema('user');
    $this->installEntitySchema('node');
    $this->installSchema('node', 'node_access');

    NodeType::create([
      'type' => 'test',
      'name' => 'Test',
    ])->save();

    $this->editorUser = $this->createUser(['bypass node access']);
    $this->powerUser = $this->createUser([
      'access content',
      'create test content',
      'edit own test content',
      'delete own test content',
    ]);
    $this->regularUser = $this->createUser(['access content']);

    // Create some test entities.
    for ($i = 0; $i < 5; $i++) {
      Node::create(['title' => 'b' . $i . $this->randomMachineName(), 'type' => 'test'])->save();
    }

    // Create a power user node.
    Node::create(['title' => 'z' . $this->randomMachineName(), 'uid' => $this->powerUser->id(), 'type' => 'test'])->save();
  }

  /**
   * Tests complex field rewriting and uncacheable field handlers.
   */
  public function testAdvancedCaching(): void {
    // Test that row field output is actually cached and with the proper cache
    // contexts.
    $this->doTestRenderedOutput($this->editorUser);
    $this->doTestRenderedOutput($this->editorUser, TRUE);
    $this->doTestRenderedOutput($this->powerUser);
    $this->doTestRenderedOutput($this->powerUser, TRUE);
    $this->doTestRenderedOutput($this->regularUser);
    $this->doTestRenderedOutput($this->regularUser, TRUE);

    // Alter the result set order and check that counter is still working
    // correctly.
    $this->doTestRenderedOutput($this->editorUser);
    /** @var \Drupal\node\NodeInterface $node */
    $node = Node::load(6);
    $node->setTitle('a' . $this->randomMachineName());
    $node->save();
    $this->doTestRenderedOutput($this->editorUser);
  }

  /**
   * Tests that rows are not cached when the none cache plugin is used.
   */
  public function testNoCaching(): void {
    $this->setCurrentUser($this->regularUser);
    $view = Views::getView('test_row_render_cache_none');
    $view->setDisplay();
    $view->preview();

    /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
    $render_cache = $this->container->get('render_cache');

    /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
    $cache_plugin = $view->display_handler->getPlugin('cache');

    foreach ($view->result as $row) {
      $keys = $cache_plugin->getRowCacheKeys($row);
      $cache = [
        '#cache' => [
          'keys' => $keys,
          'contexts' => ['languages:language_interface', 'theme', 'user.permissions'],
        ],
      ];
      $element = $render_cache->get($cache);
      $this->assertFalse($element);
    }
  }

  /**
   * Check whether the rendered output matches expectations.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The user account to tests rendering with.
   * @param bool $check_cache
   *   (optional) Whether explicitly test render cache entries.
   */
  protected function doTestRenderedOutput(AccountInterface $account, $check_cache = FALSE): void {
    $this->setCurrentUser($account);
    $view = Views::getView('test_row_render_cache');
    $view->setDisplay();
    $view->preview();

    /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
    $render_cache = $this->container->get('render_cache');

    /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
    $cache_plugin = $view->display_handler->getPlugin('cache');

    // Retrieve nodes and sort them in alphabetical order to match view results.
    $nodes = Node::loadMultiple();
    usort($nodes, function (NodeInterface $a, NodeInterface $b) {
      return strcmp($a->label(), $b->label());
    });

    $index = 0;
    foreach ($nodes as $node) {
      $nid = $node->id();
      $access = $node->access('update');

      $counter = $index + 1;
      $expected = "$nid: $counter (just in case: $nid)";
      $counter_output = $view->style_plugin->getField($index, 'counter');
      $this->assertSame($expected, (string) $counter_output);

      $node_url = $node->toUrl()->toString();
      $expected = "<a href=\"$node_url\"><span class=\"da-title\">{$node->label()}</span> <span class=\"counter\">$counter_output</span></a>";
      $output = $view->style_plugin->getField($index, 'title');
      $this->assertSame($expected, (string) $output);

      $expected = $access ? "<a href=\"$node_url/edit?destination=/\" hreflang=\"en\">edit</a>" : "";
      $output = $view->style_plugin->getField($index, 'edit_node');
      $this->assertSame($expected, (string) $output);

      $expected = $access ? "<a href=\"$node_url/delete?destination=/\" hreflang=\"en\">delete</a>" : "";
      $output = $view->style_plugin->getField($index, 'delete_node');
      $this->assertSame($expected, (string) $output);

      if ($access) {
        $expected = '  <div class="dropbutton-wrapper" data-drupal-ajax-container>' . PHP_EOL . '    <div class="dropbutton-widget"><ul class="dropbutton">' .
          '<li><a href="' . $node_url . '/edit?destination=/" aria-label="Edit ' . $node->label() . '" hreflang="en">Edit</a></li>' .
          '<li><a href="' . $node_url . '/delete?destination=/" aria-label="Delete ' . $node->label() . '" class="use-ajax" data-dialog-type="modal" data-dialog-options="' . Html::escape(Json::encode(['width' => 880])) . '" hreflang="en">Delete</a></li>' .
          '<li><a href="' . $node_url . '?destination=/" aria-label="View ' . $node->label() . '" hreflang="en">View</a></li>' .
          '</ul></div>' . PHP_EOL . '  </div>';
      }
      else {
        $expected = '  <div class="dropbutton-wrapper" data-drupal-ajax-container>' . PHP_EOL . '    <div class="dropbutton-widget"><ul class="dropbutton">' .
          '<li><a href="' . $node_url . '?destination=/" aria-label="View ' . $node->label() . '" hreflang="en">View</a></li>' .
          '</ul></div>' . PHP_EOL . '  </div>';
      }
      $output = $view->style_plugin->getField($index, 'operations');
      $this->assertSame($expected, (string) $output);

      if ($check_cache) {
        $keys = $cache_plugin->getRowCacheKeys($view->result[$index]);
        $cache = [
          '#cache' => [
            'keys' => $keys,
            'contexts' => ['languages:language_interface', 'theme', 'user.permissions'],
          ],
        ];
        $element = $render_cache->get($cache);
        $this->assertNotEmpty($element);
      }

      $index++;
    }
  }

}
Loading