From 5abcf624d0c9b0d6f0e60ca17f369090651c0fea Mon Sep 17 00:00:00 2001 From: Juan de Paco Date: Thu, 4 Jul 2024 11:24:23 +0200 Subject: [PATCH] [wpmlbridge-300] Cache cluster indices. - Avoid multiple checks on index name existance on multiple processes. https://github.com/OnTheGoSystems/wpml-elasticpress/issues/48 --- src/Manager/Indices.php | 40 ++++++++++++++++++++++++++- tests/phpstan/stubs/elasticpress.stub | 10 +++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/src/Manager/Indices.php b/src/Manager/Indices.php index 099524e..2c474b0 100644 --- a/src/Manager/Indices.php +++ b/src/Manager/Indices.php @@ -34,6 +34,9 @@ class Indices { /** @var string|null */ private $stopwordFilterSlug = null; + /** @var string[]|null */ + private static $clusterIndices = null; + /** * @param Elasticsearch $elasticsearch * @param Indexables $indexables @@ -90,13 +93,46 @@ public function clearCurrentIndexLanguage() { $this->currentIndexLanguage = ''; } + /** + * @return string[] + */ + private function getClusterIndicesCache() { + if ( null === self::$clusterIndices ) { + $clusterIndices = $this->elasticsearch->get_cluster_indices(); + self::$clusterIndices = wp_list_pluck( $clusterIndices, 'index' ); + } + + return self::$clusterIndices; + } + + /** + * @param string $indexName + */ + private function saveIndexInClusterCache( $indexName ) { + if ( null === self::$clusterIndices ) { + self::$clusterIndices = []; + } + + if ( in_array( $indexName, self::$clusterIndices, true ) ) { + return; + } + + self::$clusterIndices[] = $indexName; + } + + private function clearClusterIndicesCache() { + self::$clusterIndices = null; + } + /** * @param string $indexName * * @return bool */ public function indexExists( $indexName ) { - return $this->elasticsearch->index_exists( $indexName ); + $clusterIndices = $this->getClusterIndicesCache(); + + return in_array( $indexName, $clusterIndices, true ); } /** @@ -155,6 +191,7 @@ public function generateIndexByIndexable( $indexable ) { ]; $this->elasticsearch->put_mapping( $indexName, $mapping ); + $this->saveIndexInClusterCache( $indexName ); } /** @@ -168,6 +205,7 @@ public function generateIndexableIndexes( $indexables ) { public function clearAllIndices() { $this->elasticsearch->delete_all_indices(); + $this->clearClusterIndicesCache(); } public function generateMissingIndices() { diff --git a/tests/phpstan/stubs/elasticpress.stub b/tests/phpstan/stubs/elasticpress.stub index 5a2b4a2..640d7b4 100644 --- a/tests/phpstan/stubs/elasticpress.stub +++ b/tests/phpstan/stubs/elasticpress.stub @@ -67,6 +67,11 @@ namespace ElasticPress { */ public function put_mapping( $index, $mapping, $return_type = 'bool' ) {} + /** + * @return string[] + */ + public function get_cluster_indices() {} + /** * @return boolean */ @@ -160,6 +165,11 @@ namespace ElasticPress { */ public function get_index_name( $blog_id = null ) {} + /** + * @return array + */ + public function get_indexable_post_status() {} + /** * @return array */