-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathNodeIndexer.php
More file actions
664 lines (574 loc) · 23.3 KB
/
NodeIndexer.php
File metadata and controls
664 lines (574 loc) · 23.3 KB
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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
<?php
declare(strict_types=1);
namespace Flowpack\ElasticSearch\ContentRepositoryAdaptor\Indexer;
/*
* This file is part of the Flowpack.ElasticSearch.ContentRepositoryAdaptor package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Domain\Model\TargetContextPath;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Driver\DocumentDriverInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Driver\IndexDriverInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Driver\IndexerDriverInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Driver\NodeTypeMappingBuilderInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Driver\RequestDriverInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Driver\SystemDriverInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\ElasticSearchClient;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\ErrorHandling\ErrorHandlingService;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\ErrorHandling\ErrorStorageInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Exception;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Service\DimensionsService;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Service\DocumentIdentifier\DocumentIdentifierGeneratorInterface;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Service\IndexNameService;
use Flowpack\ElasticSearch\ContentRepositoryAdaptor\Service\NodeTypeIndexingConfiguration;
use Flowpack\ElasticSearch\Domain\Model\Document as ElasticSearchDocument;
use Flowpack\ElasticSearch\Domain\Model\Index;
use Flowpack\ElasticSearch\Transfer\Exception\ApiException;
use Neos\ContentRepository\Domain\Model\NodeInterface;
use Neos\ContentRepository\Domain\Service\Context;
use Neos\ContentRepository\Domain\Service\ContextFactoryInterface;
use Neos\ContentRepository\Search\Indexer\AbstractNodeIndexer;
use Neos\ContentRepository\Search\Indexer\BulkNodeIndexerInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\Exception\IllegalObjectTypeException;
use Neos\Utility\Exception\FilesException;
use Neos\Flow\Log\Utility\LogEnvironment;
use Psr\Log\LoggerInterface;
/**
* Indexer for Content Repository Nodes. Triggered from the NodeIndexingManager.
*
* Internally, uses a bulk request.
*
* @Flow\Scope("singleton")
*/
class NodeIndexer extends AbstractNodeIndexer implements BulkNodeIndexerInterface
{
/**
* @Flow\Inject
* @var NodeTypeMappingBuilderInterface
*/
protected $nodeTypeMappingBuilder;
/**
* @Flow\Inject
* @var ErrorHandlingService
*/
protected $errorHandlingService;
/**
* @Flow\Inject
* @var ElasticSearchClient
*/
protected $searchClient;
/**
* @Flow\Inject
* @var LoggerInterface
*/
protected $logger;
/**
* @Flow\Inject
* @var ContextFactoryInterface
*/
protected $contextFactory;
/**
* @var DocumentDriverInterface
* @Flow\Inject
*/
protected $documentDriver;
/**
* @var IndexerDriverInterface
* @Flow\Inject
*/
protected $indexerDriver;
/**
* @var IndexDriverInterface
* @Flow\Inject
*/
protected $indexDriver;
/**
* @var RequestDriverInterface
* @Flow\Inject
*/
protected $requestDriver;
/**
* @var SystemDriverInterface
* @Flow\Inject
*/
protected $systemDriver;
/**
* @var array
* @Flow\InjectConfiguration(package="Flowpack.ElasticSearch.ContentRepositoryAdaptor", path="indexing.batchSize")
*/
protected $batchSize;
/**
* @var array
* @Flow\InjectConfiguration(package="Flowpack.ElasticSearch", path="indexes")
*/
protected $indexConfiguration;
/**
* @Flow\Inject
* @var DimensionsService
*/
protected $dimensionService;
/**
* @Flow\Inject
* @var NodeTypeIndexingConfiguration
*/
protected $nodeTypeIndexingConfiguration;
/**
* @Flow\Inject
* @var DocumentIdentifierGeneratorInterface
*/
protected $documentIdentifierGenerator;
/**
* @Flow\Inject
* @var ErrorStorageInterface
*/
protected $errorStorage;
/**
* The current Elasticsearch bulk request, in the format required by https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html
*/
protected array $currentBulkRequest = [];
/**
* Optional postfix for the index, e.g. to have different indexes by timestamp.
*/
protected string $indexNamePostfix = '';
protected bool $bulkProcessing = false;
public function setDimensions(array $dimensionsValues): void
{
$this->searchClient->setDimensions($dimensionsValues);
}
/**
* Returns the index name to be used for indexing, with optional indexNamePostfix appended.
*
* @return string
* @throws Exception\ConfigurationException
* @throws Exception
*/
public function getIndexName(): string
{
$indexName = $this->searchClient->getIndexName();
if ($this->indexNamePostfix !== '') {
$indexName .= IndexNameService::INDEX_PART_SEPARATOR . $this->indexNamePostfix;
}
return $indexName;
}
/**
* Set the postfix for the index name
*
* @param string $indexNamePostfix
* @return void
*/
public function setIndexNamePostfix(string $indexNamePostfix): void
{
$this->indexNamePostfix = $indexNamePostfix;
}
/**
* Return the currently active index to be used for indexing
*
* @return Index
* @throws Exception
* @throws \Flowpack\ElasticSearch\Exception
* @throws Exception\ConfigurationException
*/
public function getIndex(): Index
{
$index = $this->searchClient->findIndex($this->getIndexName());
$perDimensionConfiguration = $this->indexConfiguration[$this->searchClient->getBundle()][$this->searchClient->getIndexName()] ?? null;
if ($perDimensionConfiguration !== null) {
$index->setSettingsKey($this->searchClient->getIndexName());
} else {
$index->setSettingsKey($this->searchClient->getIndexNamePrefix());
}
return $index;
}
/**
* Index this node, and add it to the current bulk request.
*
* @param NodeInterface $node
* @param string $targetWorkspaceName In case indexing is triggered during publishing, a target workspace name will be passed in
* @return void
* @throws Exception
*/
public function indexNode(NodeInterface $node, $targetWorkspaceName = null): void
{
if ($this->nodeTypeIndexingConfiguration->isIndexable($node->getNodeType()) === false) {
$this->logger->debug(sprintf('Node "%s" (%s) skipped, Node Type is not allowed in the index.', $node->getContextPath(), $node->getNodeType()), LogEnvironment::fromMethodName(__METHOD__));
return;
}
$indexer = function (NodeInterface $node, $targetWorkspaceName = null) {
if ($this->settings['indexAllWorkspaces'] === false) {
// we are only supposed to index the live workspace.
// We need to check the workspace at two occasions; checking the
// $targetWorkspaceName and the workspace name of the node's context as fallback
if ($targetWorkspaceName !== null && $targetWorkspaceName !== 'live') {
return;
}
if ($targetWorkspaceName === null && $node->getContext()->getWorkspaceName() !== 'live') {
return;
}
}
// Don't index node into fulltext if it has a hidden parent node that is not a fulltext root
// Example: If a text node is in a hidden container element, it should not be indexed into the document
$parentNode = $node;
while (($parentNode = $parentNode->getParent())
&& !$parentNode->getNodeType()->getConfiguration('search.fulltext.isRoot')) {
if (!$parentNode->isVisible()) {
return;
}
}
$documentIdentifier = $this->documentIdentifierGenerator->generate($node, $targetWorkspaceName);
$nodeType = $node->getNodeType();
$mappingType = $this->getIndex()->findType($nodeType->getName());
$fulltextIndexOfNode = [];
$nodePropertiesToBeStoredInIndex = $this->extractPropertiesAndFulltext($node, $fulltextIndexOfNode, function ($propertyName) use ($documentIdentifier, $node) {
$this->logger->debug(sprintf('Property "%s" not indexed because no configuration found, node type %s.', $propertyName, $node->getNodeType()->getName()), LogEnvironment::fromMethodName(__METHOD__));
});
$document = new ElasticSearchDocument(
$mappingType,
$nodePropertiesToBeStoredInIndex,
$documentIdentifier
);
$documentData = $document->getData();
if ($targetWorkspaceName !== null) {
$documentData['neos_workspace'] = $targetWorkspaceName;
}
$this->toBulkRequest($node, $this->indexerDriver->document($this->getIndexName(), $node, $document, $documentData));
if ($this->isFulltextEnabled($node)) {
$this->toBulkRequest($node, $this->indexerDriver->fulltext($node, $fulltextIndexOfNode, $targetWorkspaceName));
}
};
$handleNode = function (NodeInterface $node, Context $context) use ($targetWorkspaceName, $indexer) {
$nodeFromContext = $context->getNodeByIdentifier($node->getIdentifier());
if ($nodeFromContext instanceof NodeInterface) {
$this->searchClient->withDimensions(static function () use ($indexer, $nodeFromContext, $targetWorkspaceName) {
$indexer($nodeFromContext, $targetWorkspaceName);
}, $nodeFromContext->getContext()->getTargetDimensions());
} else {
if ($node->isRemoved()) {
$this->removeNode($node, $context->getWorkspaceName());
$this->logger->debug(sprintf('Removed node with identifier %s, no longer in workspace %s', $node->getIdentifier(), $context->getWorkspaceName()), LogEnvironment::fromMethodName(__METHOD__));
} else {
$this->logger->debug(sprintf('Could not index node with identifier %s, not found in workspace %s with dimensions %s', $node->getIdentifier(), $context->getWorkspaceName(), json_encode($context->getDimensions())), LogEnvironment::fromMethodName(__METHOD__));
}
}
};
$workspaceName = $targetWorkspaceName ?: $node->getContext()->getWorkspaceName();
$dimensionCombinations = $this->dimensionService->getDimensionCombinationsForIndexing($node);
if (array_filter($dimensionCombinations) === []) {
$handleNode($node, $this->createContentContext($workspaceName));
} else {
foreach ($dimensionCombinations as $combination) {
$handleNode($node, $this->createContentContext($workspaceName, $combination));
}
}
}
/**
* @param string $workspaceName
* @param array $dimensions
* @return Context
*/
protected function createContentContext(string $workspaceName, array $dimensions = []): Context
{
$configuration = [
'workspaceName' => $workspaceName,
'invisibleContentShown' => true
];
if ($dimensions !== []) {
$configuration['dimensions'] = $dimensions;
}
return $this->contextFactory->create($configuration);
}
/**
* @param NodeInterface $node
* @param array|null $requests
* @throws Exception
* @throws \Flowpack\ElasticSearch\Exception
* @throws FilesException
*/
protected function toBulkRequest(NodeInterface $node, array $requests = null): void
{
if ($requests === null) {
return;
}
$this->currentBulkRequest[] = new BulkRequestPart($this->dimensionService->hashByNode($node), $requests);
$this->flushIfNeeded();
}
/**
* Schedule node removal into the current bulk request.
*
* @param NodeInterface $node
* @param string|null $targetWorkspaceName
* @return void
* @throws Exception
* @throws FilesException
* @throws \Flowpack\ElasticSearch\Exception
*/
public function removeNode(NodeInterface $node, string $targetWorkspaceName = null): void
{
if ($this->settings['indexAllWorkspaces'] === false) {
// we are only supposed to index the live workspace.
// We need to check the workspace at two occasions; checking the
// $targetWorkspaceName and the workspace name of the node's context as fallback
if ($targetWorkspaceName !== null && $targetWorkspaceName !== 'live') {
return;
}
if ($targetWorkspaceName === null && $node->getContext()->getWorkspaceName() !== 'live') {
return;
}
}
$documentIdentifier = $this->documentIdentifierGenerator->generate($node, $targetWorkspaceName);
$this->toBulkRequest($node, $this->documentDriver->delete($node, $documentIdentifier));
$this->toBulkRequest($node, $this->indexerDriver->fulltext($node, [], $targetWorkspaceName));
$this->logger->debug(sprintf('NodeIndexer (%s): Removed node %s (%s) from index.', $documentIdentifier, $node->getContextPath(), $node->getIdentifier()), LogEnvironment::fromMethodName(__METHOD__));
}
/**
* @throws Exception
* @throws Exception\ConfigurationException
* @throws \Flowpack\ElasticSearch\Exception
*/
protected function flushIfNeeded(): void
{
if ($this->bulkRequestLength() >= $this->batchSize['elements'] || $this->bulkRequestSize() >= $this->batchSize['octets']) {
$this->flush();
}
}
protected function bulkRequestSize(): int
{
return array_reduce($this->currentBulkRequest, static function ($sum, BulkRequestPart $request) {
return $sum + $request->getSize();
}, 0);
}
/**
* @return int
*/
protected function bulkRequestLength(): int
{
return count($this->currentBulkRequest);
}
/**
* Perform the current bulk request
*
* @return void
* @throws Exception
* @throws \Flowpack\ElasticSearch\Exception
* @throws Exception\ConfigurationException
*/
public function flush(): void
{
$bulkRequest = $this->currentBulkRequest;
$bulkRequestSize = $this->bulkRequestLength();
if ($bulkRequestSize === 0) {
return;
}
$this->logger->debug(
vsprintf(
'Flush bulk request, elements=%d, maximumElements=%s, octets=%d, maximumOctets=%d',
[$bulkRequestSize, $this->batchSize['elements'], $this->bulkRequestSize(), $this->batchSize['octets']]
),
LogEnvironment::fromMethodName(__METHOD__)
);
$payload = [];
/** @var BulkRequestPart $bulkRequestPart */
foreach ($bulkRequest as $bulkRequestPart) {
if (!$bulkRequestPart instanceof BulkRequestPart) {
throw new \RuntimeException('Invalid bulk request part', 1577016145);
}
$hash = $bulkRequestPart->getTargetDimensionsHash();
if (!isset($payload[$hash])) {
$payload[$hash] = [];
}
foreach ($bulkRequestPart->getRequest() as $bulkRequestItem) {
if ($bulkRequestItem === null) {
$this->logger->error('Indexing Error: A bulk request item could not be encoded as JSON', LogEnvironment::fromMethodName(__METHOD__));
continue 2;
}
$payload[$hash][] = $bulkRequestItem;
}
}
if ($payload === []) {
$this->reset();
return;
}
foreach ($this->dimensionService->getDimensionsRegistry() as $hash => $dimensions) {
if (!isset($payload[$hash])) {
continue;
}
$this->searchClient->setDimensions($dimensions);
$response = $this->requestDriver->bulk($this->getIndex(), implode(chr(10), $payload[$hash]));
if (isset($response['errors']) && $response['errors'] !== false) {
foreach ($response['items'] as $responseInfo) {
if ((int)current($responseInfo)['status'] > 299) {
$this->errorHandlingService->log($this->errorStorage->logErrorResult($responseInfo), LogEnvironment::fromMethodName(__METHOD__));
}
}
}
}
$this->reset();
}
protected function reset(): void
{
$this->dimensionService->reset();
$this->currentBulkRequest = [];
}
/**
* Update the index alias
*
* @return void
* @throws Exception
* @throws ApiException
* @throws \Flowpack\ElasticSearch\Exception
* @throws \Exception
*/
public function updateIndexAlias(): void
{
$aliasName = $this->searchClient->getIndexName(); // The alias name is the unprefixed index name
if ($this->getIndexName() === $aliasName) {
throw new Exception('UpdateIndexAlias is only allowed to be called when setIndexNamePostfix() has been called.', 1383649061);
}
if (!$this->getIndex()->exists()) {
throw new Exception(sprintf('The target index "%s" does not exist.', $this->getIndex()->getName()), 1383649125);
}
$aliasActions = [];
try {
$indexNames = $this->indexDriver->getIndexNamesByAlias($aliasName);
if ($indexNames === []) {
// if there is an actual index with the name we want to use as alias, remove it now
$this->indexDriver->deleteIndex($aliasName);
} else {
// Remove all existing aliasses
foreach ($indexNames as $indexName) {
$aliasActions[] = [
'remove' => [
'index' => $indexName,
'alias' => $aliasName
]
];
}
}
} catch (ApiException $exception) {
// in case of 404, do not throw an error...
if ($exception->getResponse()->getStatusCode() !== 404) {
throw $exception;
}
}
$aliasActions[] = [
'add' => [
'index' => $this->getIndexName(),
'alias' => $aliasName
]
];
$this->indexDriver->aliasActions($aliasActions);
}
/**
* Update the main alias to allow to query all indices at once
* @throws Exception
* @throws Exception\ConfigurationException
* @throws ApiException
*/
public function updateMainAlias(): void
{
$aliasActions = [];
$aliasNamePrefix = $this->searchClient->getIndexNamePrefix(); // The alias name is the unprefixed index name
$indexNames = IndexNameService::filterIndexNamesByPostfix($this->indexDriver->getIndexNamesByPrefix($aliasNamePrefix), $this->indexNamePostfix);
$cleanupAlias = function ($alias) use (&$aliasActions) {
try {
$indexNames = $this->indexDriver->getIndexNamesByAlias($alias);
if ($indexNames === []) {
// if there is an actual index with the name we want to use as alias, remove it now
$this->indexDriver->deleteIndex($alias);
} else {
foreach ($indexNames as $indexName) {
$aliasActions[] = [
'remove' => [
'index' => $indexName,
'alias' => $alias
]
];
}
}
} catch (ApiException $exception) {
// in case of 404, do not throw an error...
if ($exception->getResponse()->getStatusCode() !== 404) {
throw $exception;
}
}
};
$postfix = function ($alias) {
return $alias . IndexNameService::INDEX_PART_SEPARATOR . $this->indexNamePostfix;
};
if (\count($indexNames) > 0) {
$cleanupAlias($aliasNamePrefix);
$cleanupAlias($postfix($aliasNamePrefix));
foreach ($indexNames as $indexName) {
$aliasActions[] = [
'add' => [
'index' => $indexName,
'alias' => $aliasNamePrefix
]
];
$aliasActions[] = [
'add' => [
'index' => $indexName,
'alias' => $postfix($aliasNamePrefix)
]
];
}
}
$this->indexDriver->aliasActions($aliasActions);
}
/**
* Remove old indices which are not active anymore (remember, each bulk index creates a new index from scratch,
* making the "old" index a stale one).
*
* @return array<string> a list of index names which were removed
* @throws Exception
* @throws Exception\ConfigurationException
*/
public function removeOldIndices(): array
{
$aliasName = $this->searchClient->getIndexName(); // The alias name is the unprefixed index name
$currentlyLiveIndices = $this->indexDriver->getIndexNamesByAlias($aliasName);
$indexStatus = $this->systemDriver->status();
$allIndices = array_keys($indexStatus['indices']);
$indicesToBeRemoved = [];
foreach ($allIndices as $indexName) {
if (strpos($indexName, $aliasName . IndexNameService::INDEX_PART_SEPARATOR) !== 0) {
// filter out all indices not starting with the alias-name, as they are unrelated to our application
continue;
}
if (in_array($indexName, $currentlyLiveIndices, true)) {
// skip the currently live index names from deletion
continue;
}
$indicesToBeRemoved[] = $indexName;
}
array_map(function ($index) {
$this->indexDriver->deleteIndex($index);
}, $indicesToBeRemoved);
return $indicesToBeRemoved;
}
/**
* Perform indexing without checking about duplication document
*
* This is used during bulk indexing to improve performance
*
* @param callable $callback
* @throws \Exception
*/
public function withBulkProcessing(callable $callback): void
{
$bulkProcessing = $this->bulkProcessing;
$this->bulkProcessing = true;
try {
/** @noinspection PhpUndefinedMethodInspection */
$callback->__invoke();
} catch (\Exception $exception) {
$this->bulkProcessing = $bulkProcessing;
throw $exception;
}
$this->bulkProcessing = $bulkProcessing;
}
}