diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9491f1b..7acffad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - php_version: [ '8.2', '8.5' ] + php_version: [ '8.4', '8.5' ] steps: - uses: actions/checkout@v7 @@ -41,8 +41,8 @@ jobs: - uses: actions/checkout@v7 - uses: php-actions/composer@v6 with: - php_version: '8.2' + php_version: '8.4' - uses: php-actions/phpstan@v3 with: - php_version: '8.2' + php_version: '8.4' configuration: phpstan.neon diff --git a/Classes/Aspects/CacheUrlMappingAspect.php b/Classes/Aspects/CacheUrlMappingAspect.php index bc1333a..cc406ba 100644 --- a/Classes/Aspects/CacheUrlMappingAspect.php +++ b/Classes/Aspects/CacheUrlMappingAspect.php @@ -11,13 +11,23 @@ use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\NodeRenderingExtensionManager; use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer; use Flowpack\DecoupledContentStore\NodeRendering\Render\RenderExceptionExtractor; +use JsonException; +use Neos\Cache\Exception as CacheException; use Neos\Cache\Exception\InvalidDataException; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\Cache\Frontend\StringFrontend; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; use Neos\Flow\Annotations as Flow; use Neos\Flow\Aop\JoinPointInterface; +use Neos\Flow\Mvc\ActionRequest; use Neos\Fusion\Core\Cache\CacheSegmentParser; +use Neos\Fusion\Core\Cache\ContentCache; +use Neos\Fusion\Core\Cache\RuntimeContentCache; +use Neos\Fusion\Core\Runtime; +use Neos\Fusion\Exception as FusionException; use Neos\Utility\Exception\PropertyNotAccessibleException; use Neos\Utility\ObjectAccess; +use RuntimeException; /** * This aspect creates the root cache entry which maps the URL to the root cache identifier during rendering. @@ -26,91 +36,70 @@ * through Batch Rendering (so when {@see DocumentRenderer} has invoked the rendering. This is to keep complexity lower * and code paths simpler: The system NEVER re-uses content cache entries created by editors while browsing the page; but * ONLY re-uses content cache entries created by previous Batch Renderings. - * - * @Flow\Aspect - * @Flow\Scope("singleton") */ -class CacheUrlMappingAspect +#[Flow\Aspect] +#[Flow\Scope('singleton')] +final class CacheUrlMappingAspect { /** * are we currently rendering the page from within a Content Release? {@see DocumentRenderer} - * - * @var bool */ - protected $isActive = false; + private bool $isActive = false; - /** - * @var null | int - */ - protected $renderTimestamp = null; + private ?int $renderTimestamp = null; - /** - * @var array - */ - protected $currentEvaluateContext; + private array $currentEvaluateContext = []; /** - * @var \Neos\Flow\Mvc\Controller\ControllerContext + * The cache entry identifier only carries a string identifier of the node, so the node is taken from the Fusion + * context of the segment instead. */ - protected $controllerContext; + private ?Node $currentNode = null; - /** - * @Flow\Inject - * @var \Neos\Fusion\Core\Cache\ContentCache - */ - protected $contentCache; + private ?ActionRequest $actionRequest = null; /** - * @Flow\Inject - * @var NodeRenderingExtensionManager + * Injected via Objects.yaml */ - protected $nodeRenderingExtensionManager; + protected StringFrontend $contentCacheFrontend; - /** - * @var \Neos\Cache\Frontend\StringFrontend - */ - protected $contentCacheFrontend; - - /** - * @Flow\InjectConfiguration(path="nodeRendering.urlExcludelistRegex") - * @var string|false - */ - protected $urlExcludelistRegex = false; - - /** - * @var ContentReleaseLogger - */ - protected $contentReleaseLogger; + private ?ContentReleaseLogger $contentReleaseLogger = null; /** * Did the current document rendering lead to a "doc--..." mapping entry? {@see afterDocumentRendering()} - * - * @var bool */ - protected $mappingWasWrittenForCurrentDocument = false; + private bool $mappingWasWrittenForCurrentDocument = false; - /** - * @Flow\Before("method(Neos\Fusion\Core\Cache\RuntimeContentCache->postProcess())") - */ - public function getCurrentEvaluateAndControllerContext(JoinPointInterface $joinPoint) + public function __construct( + private readonly ContentCache $contentCache, + private readonly NodeRenderingExtensionManager $nodeRenderingExtensionManager, + #[Flow\InjectConfiguration('nodeRendering.urlExcludelistRegex')] + protected readonly string|false|null $urlExcludelistRegex, + ) {} + + #[Flow\Before('method(Neos\Fusion\Core\Cache\RuntimeContentCache->postProcess())')] + public function getCurrentEvaluateAndControllerContext(JoinPointInterface $joinPoint): void { $this->currentEvaluateContext = $joinPoint->getMethodArgument('evaluateContext'); - /** @var \Neos\Fusion\Core\Cache\RuntimeContentCache $runtimeContentCache */ + /** @var RuntimeContentCache $runtimeContentCache */ $runtimeContentCache = $joinPoint->getProxy(); - /** @var \Neos\Fusion\Core\Runtime $runtime */ + /** @var Runtime $runtime */ $runtime = ObjectAccess::getProperty($runtimeContentCache, 'runtime', true); - $this->controllerContext = $runtime->getControllerContext(); + $contextNode = $runtime->getCurrentContext()['node'] ?? null; + $this->currentNode = $contextNode instanceof Node ? $contextNode : null; + $actionRequest = $runtime->fusionGlobals->get('request'); + $this->actionRequest = $actionRequest instanceof ActionRequest ? $actionRequest : null; } /** - * @Flow\After("method(Neos\Fusion\Core\Cache\ContentCache->processCacheSegments())") * @throws Exception - * @throws \JsonException - * @throws \Neos\Cache\Exception + * @throws JsonException + * @throws CacheException * @throws InvalidDataException - * @throws \Neos\Fusion\Exception + * @throws FusionException * @throws PropertyNotAccessibleException */ + #[Flow\After('method(Neos\Fusion\Core\Cache\ContentCache->processCacheSegments())')] public function storeRootCacheIdentifier(JoinPointInterface $joinPoint): void { if (!$this->isActive) { @@ -118,15 +107,15 @@ public function storeRootCacheIdentifier(JoinPointInterface $joinPoint): void } if ( !isset($this->currentEvaluateContext['cacheIdentifierValues']['node']) - || !$this->currentEvaluateContext['cacheIdentifierValues']['node'] instanceof NodeInterface + || $this->currentNode === null + || $this->actionRequest === null ) { return; } + $node = $this->currentNode; + $actionRequest = $this->actionRequest; - /** @var NodeInterface $node */ - $node = $this->currentEvaluateContext['cacheIdentifierValues']['node']; - - $url = $this->getCurrentUrl(); + $url = $this->getCurrentUrl($actionRequest); $storeCacheEntries = $joinPoint->getMethodArgument('storeCacheEntries'); // Do not create mapping (and check for consistency of root identifier) if storage of entries was disabled (e.g. exception was catched) @@ -137,7 +126,7 @@ public function storeRootCacheIdentifier(JoinPointInterface $joinPoint): void 'Cache was disabled for ' . $url . ' with node ' - . $node->getContextPath() + . NodeAddress::fromNode($node)->toJson() . ', but no exception was handled by the publishing. This could be caused by a missing publishing aware @exceptionHandler in Fusion.' . ( $extractedExceptionDto !== null ? "\nException extracted from output: {$extractedExceptionDto}" : '' @@ -159,7 +148,7 @@ public function storeRootCacheIdentifier(JoinPointInterface $joinPoint): void $logger = $this->contentReleaseLogger; if ($logger === null) { - throw new \RuntimeException('TODO Logger not found - should never happen'); + throw new RuntimeException('TODO Logger not found - should never happen'); } if ($this->urlIsMatchingBlacklist($url)) { $logger->info(sprintf( @@ -180,7 +169,7 @@ public function storeRootCacheIdentifier(JoinPointInterface $joinPoint): void $logger->debug('Mapping URL ' . $url . ' to ' . $rootIdentifier . ' with tags ' . implode(', ', $rootTags)); - $arguments = $this->getCurrentArguments($node); + $arguments = $this->getCurrentArguments($actionRequest); // TODO: To make parallel rendering possible, we need to make sure that the cache key also includes the currently rendered workspace, as the node might originate from a base workspace (usually live). See `DocumentNodeCacheKey`. $rootKey = DocumentNodeCacheKey::fromNodeAndArguments($node, $arguments); $rootCacheValues = DocumentNodeCacheValues::create($rootIdentifier, $url)->withMetadata( @@ -191,7 +180,7 @@ public function storeRootCacheIdentifier(JoinPointInterface $joinPoint): void $rootCacheValues = $this->nodeRenderingExtensionManager->runDocumentMetadataGenerators( $node, $arguments, - $this->controllerContext, + $actionRequest, $rootCacheValues, ); $this->contentCacheFrontend->set( @@ -202,13 +191,8 @@ public function storeRootCacheIdentifier(JoinPointInterface $joinPoint): void $this->mappingWasWrittenForCurrentDocument = true; } - /** - * @return string - */ - protected function getCurrentUrl(): string + private function getCurrentUrl(ActionRequest $actionRequest): string { - /** @var \Neos\Flow\Mvc\ActionRequest $actionRequest */ - $actionRequest = $this->controllerContext->getRequest(); $httpRequest = $actionRequest->getHttpRequest(); $url = $httpRequest->getUri(); $url = $url->withQuery(''); @@ -216,23 +200,14 @@ protected function getCurrentUrl(): string return (string) $url; } - /** - * @param NodeInterface $node - */ - protected function getCurrentArguments(NodeInterface $node): array + private function getCurrentArguments(ActionRequest $actionRequest): array { - /** @var \Neos\Flow\Mvc\ActionRequest $actionRequest */ - $actionRequest = $this->controllerContext->getRequest(); $arguments = $actionRequest->getArguments(); unset($arguments['node']); return $arguments; } - /** - * @param array $tags - * @return array - */ - protected function sanitizeTags($tags) + private function sanitizeTags(array $tags): array { foreach ($tags as $key => $value) { $tags[$key] = strtr($value, '.:', '_-'); diff --git a/Classes/Aspects/FixedAssetHandlingInContentCacheFlusherAspect.php b/Classes/Aspects/FixedAssetHandlingInContentCacheFlusherAspect.php deleted file mode 100644 index 8a14874..0000000 --- a/Classes/Aspects/FixedAssetHandlingInContentCacheFlusherAspect.php +++ /dev/null @@ -1,177 +0,0 @@ -`. It is also mentioned here for completeness; so that one has a - * complete overview of the full issue. - * - * 3) Additional Bug: The default implementation of ContentCacheFlusher::registerAssetChange() does not flush the cache of the parent - * nodes until and including the parent document node of all nodes that use that asset. It only flushes the cache of the - * node that uses the asset. This is changed here. - * - * 4) Note: We also directly commit the cache flush and trigger the incremental rendering afterwards to prevent a race condition with - * node enumeration during incremental rendering. - * - * @Flow\Aspect - * @Flow\Scope("singleton") - */ -class FixedAssetHandlingInContentCacheFlusherAspect -{ - use CreateContentContextTrait; - - /** - * @Flow\Inject - * @var PersistenceManagerInterface - */ - protected $persistenceManager; - - /** - * @Flow\Inject - * @var AssetService - */ - protected $assetService; - - /** - * @Flow\Inject - * @var CachingHelper - */ - protected $cachingHelper; - - /** - * @Flow\Inject - * @var ContentReleaseManager - */ - protected $contentReleaseManager; - - /** - * @Flow\InjectConfiguration("startIncrementalReleaseOnAssetChange") - * @var bool - */ - protected $startIncrementalReleaseOnAssetChange; - - /** - * WHY: - * The default implementation of ContentCacheFlusher::registerAssetChange() does not flush the cache of the parent - * nodes until and including the parent document node of all nodes that use that asset. - * - * What we want to accomplish: - * When an asset is updated (including "replaced"), we want to - * 1. flush the cache of the updated asset (with and without workspace hash) - * 2. flush the cache of all parent nodes until (including) the parent document node of all nodes that use that - * asset (assetUsage) - * 3. Commit cache flushes to prevent race condition with node enumeration during incremental rendering - * 3. trigger incremental rendering - */ - /** - * @Flow\Around("method(Neos\Neos\Fusion\Cache\ContentCacheFlusher->registerAssetChange())") - */ - public function registerAssetChange(JoinPointInterface $joinPoint) - { - /* @var AssetInterface $asset */ - $asset = $joinPoint->getMethodArgument('asset'); - - if (!$asset->isInUse()) { - return; - } - - /* @var ContentCacheFlusher $contentCacheFlusher */ - $contentCacheFlusher = $joinPoint->getProxy(); - - // 1. flush asset tag without workspace hash - $assetIdentifier = $this->persistenceManager->getIdentifierByObject($asset); - - $assetCacheTag = 'AssetDynamicTag_' . $assetIdentifier; - - // WHY: ContentCacheFlusher has no public api to flush tags directly - $tagsToFlush = ObjectAccess::getProperty($contentCacheFlusher, 'tagsToFlush', true); - $tagsToFlush[$assetCacheTag] = sprintf( - 'which were tagged with "%s" because asset "%s" has changed.', - $assetCacheTag, - $assetIdentifier, - ); - ObjectAccess::setProperty($contentCacheFlusher, 'tagsToFlush', $tagsToFlush, true); - - $usageReferences = $this->assetService->getUsageReferences($asset); - - foreach ($usageReferences as $assetUsage) { - // get node that uses the asset - $context = $this->_contextFactory->create([ - 'workspaceName' => $assetUsage->getWorkspaceName(), - 'dimensions' => $assetUsage->getDimensionValues(), - 'invisibleContentShown' => true, - 'removedContentShown' => true, - ]); - - $node = $context->getNodeByIdentifier($assetUsage->getNodeIdentifier()); - - // We need this for cache tag generation - $workspaceHash = $this->cachingHelper->renderWorkspaceTagForContextNode($context->getWorkspaceName()); - - // 1. flush asset with workspace hash - $assetCacheTagWithWorkspace = 'AssetDynamicTag_' . $workspaceHash . '_' . $assetIdentifier; - - // WHY: ContentCacheFlusher has no public api to flush tags directly - $tagsToFlush = ObjectAccess::getProperty($contentCacheFlusher, 'tagsToFlush', true); - $tagsToFlush[$assetCacheTagWithWorkspace] = sprintf( - 'which were tagged with "%s" because asset "%s" has changed.', - $assetCacheTagWithWorkspace, - $assetIdentifier, - ); - ObjectAccess::setProperty($contentCacheFlusher, 'tagsToFlush', $tagsToFlush, true); - - // 2. flush all nodes on path to parent document node (a bit excessive, but for now it works) - $currentNode = $node; - while ($currentNode->getParent() !== null) { - // flush node cache - $contentCacheFlusher->registerNodeChange($node); - - // if document node, stop - if ($currentNode->getNodeType()->isOfType('Neos.Neos:Document')) { - break; - } - - // go to parent node - $currentNode = $currentNode->getParent(); - } - } - - // 3. commit cache flushes - // We need force the commit here because we run into a race condition otherwise, where the incremental rendering - // is starting node enumeration before the cache flushes are actually committed. - $contentCacheFlusher->shutdownObject(); - - // 4. trigger incremental rendering - if ($this->startIncrementalReleaseOnAssetChange) { - $this->contentReleaseManager->startIncrementalContentRelease(); - } - } -} diff --git a/Classes/AssetChangeContentReleaseHandler.php b/Classes/AssetChangeContentReleaseHandler.php new file mode 100644 index 0000000..29cc1c5 --- /dev/null +++ b/Classes/AssetChangeContentReleaseHandler.php @@ -0,0 +1,49 @@ +startIncrementalReleaseOnAssetChange) { + return; + } + + // Nodes reference the original asset, never a variant. + if ($asset instanceof AssetVariantInterface) { + $asset = $asset->getOriginalAsset(); + } + + if (!$this->assetService->isInUse($asset)) { + return; + } + + $this->contentCacheFlusher->flushCollectedTags(); + $this->contentReleaseManager->startIncrementalContentRelease(); + } +} diff --git a/Classes/BackendUi/AutomaticReleaseStatusDataSource.php b/Classes/BackendUi/AutomaticReleaseStatusDataSource.php index c5da260..0080e9b 100644 --- a/Classes/BackendUi/AutomaticReleaseStatusDataSource.php +++ b/Classes/BackendUi/AutomaticReleaseStatusDataSource.php @@ -5,8 +5,7 @@ namespace Flowpack\DecoupledContentStore\BackendUi; use Flowpack\DecoupledContentStore\Core\AutomaticReleaseSwitchService; -use Neos\ContentRepository\Domain\Model\NodeInterface; -use Neos\Flow\Annotations as Flow; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; use Neos\Flow\I18n\Translator; use Neos\Neos\Service\DataSource\AbstractDataSource; @@ -30,20 +29,17 @@ final class AutomaticReleaseStatusDataSource extends AbstractDataSource */ protected static $identifier = 'flowpack-decoupledcontentstore-automatic-release-status'; - #[Flow\Inject] - protected AutomaticReleaseSwitchService $automaticReleaseSwitchService; - - #[Flow\Inject] - protected Translator $translator; - - #[Flow\Inject] - protected BackendDateFormatter $backendDateFormatter; + public function __construct( + private readonly AutomaticReleaseSwitchService $automaticReleaseSwitchService, + private readonly Translator $translator, + private readonly BackendDateFormatter $backendDateFormatter, + ) {} /** * @param array $arguments * @return array */ - public function getData(?NodeInterface $node = null, array $arguments = []): array + public function getData(?Node $node = null, array $arguments = []): array { $pauseState = $this->automaticReleaseSwitchService->getPauseState(); diff --git a/Classes/BackendUi/BackendDateFormatter.php b/Classes/BackendUi/BackendDateFormatter.php index 3316ea1..fae9662 100644 --- a/Classes/BackendUi/BackendDateFormatter.php +++ b/Classes/BackendUi/BackendDateFormatter.php @@ -4,6 +4,7 @@ namespace Flowpack\DecoupledContentStore\BackendUi; +use DateTimeInterface; use Neos\Flow\Annotations as Flow; use Neos\Flow\I18n\Cldr\Reader\DatesReader; use Neos\Flow\I18n\Formatter\DatetimeFormatter; @@ -17,15 +18,14 @@ * configuration for us. */ #[Flow\Scope('singleton')] -class BackendDateFormatter +final readonly class BackendDateFormatter { - #[Flow\Inject] - protected LocalizationService $localizationService; + public function __construct( + private LocalizationService $localizationService, + private DatetimeFormatter $datetimeFormatter, + ) {} - #[Flow\Inject] - protected DatetimeFormatter $datetimeFormatter; - - public function format(\DateTimeInterface $dateTime): string + public function format(DateTimeInterface $dateTime): string { return $this->datetimeFormatter->formatDateTime( $dateTime, diff --git a/Classes/BackendUi/BackendUiDataService.php b/Classes/BackendUi/BackendUiDataService.php index cb8cde3..a2de2d1 100644 --- a/Classes/BackendUi/BackendUiDataService.php +++ b/Classes/BackendUi/BackendUiDataService.php @@ -4,6 +4,7 @@ namespace Flowpack\DecoupledContentStore\BackendUi; +use Exception; use Flowpack\DecoupledContentStore\BackendUi\Dto\ContentReleaseDetails; use Flowpack\DecoupledContentStore\BackendUi\Dto\ContentReleaseOverviewRow; use Flowpack\DecoupledContentStore\BackendUi\Dto\RemovedContentReleaseOverviewRow; @@ -21,49 +22,25 @@ use Flowpack\Prunner\Dto\Job; use Flowpack\Prunner\PrunnerApiService; use Neos\Flow\Annotations as Flow; +use Throwable; -/** - * @Flow\Scope("singleton") - */ -class BackendUiDataService +#[Flow\Scope('singleton')] +final readonly class BackendUiDataService { - /** - * @Flow\Inject - * @var PrunnerApiService - */ - protected $prunnerApiService; - - /** - * @Flow\Inject - * @var RedisEnumerationRepository - */ - protected $redisEnumerationRepository; + public function __construct( + private PrunnerApiService $prunnerApiService, + private RedisEnumerationRepository $redisEnumerationRepository, + private RedisContentReleaseService $redisContentReleaseService, + private RedisRenderingTimeStatisticsStore $redisRenderingStatisticsStore, + private RedisRenderingErrorManager $redisRenderingErrorManager, + private RedisReleaseSwitchService $redisReleaseSwitchService, + ) {} /** - * @Flow\Inject - * @var RedisContentReleaseService + * @return ContentReleaseOverviewRow[] + * @throws Exception */ - protected $redisContentReleaseService; - - /** - * @Flow\Inject - * @var RedisRenderingTimeStatisticsStore - */ - protected $redisRenderingStatisticsStore; - - /** - * @Flow\Inject - * @var RedisRenderingErrorManager - */ - protected $redisRenderingErrorManager; - - /** - * @Flow\Inject - * @var RedisReleaseSwitchService - */ - protected $redisReleaseSwitchService; - - public function loadBackendOverviewData(RedisInstanceIdentifier $redisInstanceIdentifier) + public function loadBackendOverviewData(RedisInstanceIdentifier $redisInstanceIdentifier): array { $contentReleaseIds = $this->redisContentReleaseService->fetchAllReleaseIds($redisInstanceIdentifier); $metadata = $this->redisContentReleaseService->fetchMetadataForContentReleases( @@ -93,7 +70,7 @@ public function loadBackendOverviewData(RedisInstanceIdentifier $redisInstanceId foreach ($this->prunnerApiService->loadPipelinesAndJobs()->getJobs() as $job) { $jobsById[$job->getId()->getId()] = $job; } - } catch (\Throwable $throwable) { + } catch (Throwable) { // the overview also holds the controls to pause releases, which must keep working while prunner is down $jobsById = null; } @@ -112,7 +89,7 @@ public function loadBackendOverviewData(RedisInstanceIdentifier $redisInstanceId $metadataForContentRelease = null; } $jobForContentRelease = $metadataForContentRelease !== null - ? $jobsById[$metadataForContentRelease->getPrunnerJobId()->getIdentifier()] ?? null + ? $jobsById[$metadataForContentRelease->prunnerJobId->getIdentifier()] ?? null : null; $status = match (true) { $jobForContentRelease !== null => ContentReleaseStatus::fromJob( @@ -139,7 +116,7 @@ public function loadBackendOverviewData(RedisInstanceIdentifier $redisInstanceId $contentReleaseId->equals($this->redisReleaseSwitchService->getCurrentRelease( $redisInstanceIdentifier, )), - $metadataForContentRelease?->getContentReleaseSize(), + $metadataForContentRelease?->contentReleaseSize, $status, ); } @@ -155,6 +132,7 @@ public function loadBackendOverviewData(RedisInstanceIdentifier $redisInstanceId * "replace", most of them were replaced while waiting and have no logs at all. * * @return RemovedContentReleaseOverviewRow[]|null NULL when the prunner API could not be reached + * @throws Exception */ public function loadRemovedReleasesOverviewData(RedisInstanceIdentifier $redisInstanceIdentifier): ?array { @@ -164,7 +142,7 @@ public function loadRemovedReleasesOverviewData(RedisInstanceIdentifier $redisIn try { $jobs = $this->prunnerApiService->loadPipelinesAndJobs()->getJobs(); - } catch (\Throwable $throwable) { + } catch (Throwable) { // the overview also holds the controls to pause releases, which must keep working while prunner is down return null; } @@ -173,21 +151,19 @@ public function loadRemovedReleasesOverviewData(RedisInstanceIdentifier $redisIn static fn(ContentReleaseIdentifier $id): string => $id->getIdentifier(), $this->redisContentReleaseService->fetchAllReleaseIds($redisInstanceIdentifier), ); - $releasePipelines = [ - ContentReleaseManager::CONTENT_RELEASE_PIPELINE_NAME, - ContentReleaseManager::QUICK_CONTENT_RELEASE_PIPELINE_NAME, - ]; - $removedReleaseJobs = $jobs->filter( - static function (Job $job) use ($releasePipelines, $registeredReleaseIds): bool { - $contentReleaseId = $job->getVariables()['contentReleaseId'] ?? null; - return ( - in_array($job->getPipeline(), $releasePipelines, true) - && $job->getStart() !== null - && is_string($contentReleaseId) - && !in_array($contentReleaseId, $registeredReleaseIds, true) - ); - }, - )->getArray(); + $removedReleaseJobs = $jobs->filter(static function (Job $job) use ($registeredReleaseIds): bool { + $releasePipelines = [ + ContentReleaseManager::CONTENT_RELEASE_PIPELINE_NAME, + ContentReleaseManager::QUICK_CONTENT_RELEASE_PIPELINE_NAME, + ]; + $contentReleaseId = $job->getVariables()['contentReleaseId'] ?? null; + return ( + in_array($job->getPipeline(), $releasePipelines, true) + && $job->getStart() !== null + && is_string($contentReleaseId) + && !in_array($contentReleaseId, $registeredReleaseIds, true) + ); + })->getArray(); usort($removedReleaseJobs, static fn(Job $a, Job $b): int => $b->getStart() <=> $a->getStart()); $contentReleaseIds = array_map( @@ -234,14 +210,12 @@ public function loadDetailsData( return null; } - $contentReleaseJob = $this->prunnerApiService->loadJobDetail( - $contentReleaseMetadata->getPrunnerJobId()->toJobId(), - ); + $contentReleaseJob = $this->prunnerApiService->loadJobDetail($contentReleaseMetadata->prunnerJobId->toJobId()); - $manualTransferJobs = count($contentReleaseMetadata->getManualTransferJobIds()) - ? array_map(function (PrunnerJobId $item) { + $manualTransferJobs = count($contentReleaseMetadata->manualTransferJobIds) > 0 + ? array_filter(array_map(function (PrunnerJobId $item) { return $this->prunnerApiService->loadJobDetail($item->toJobId()); - }, $contentReleaseMetadata->getManualTransferJobIds()) + }, $contentReleaseMetadata->manualTransferJobIds)) : []; $renderingStatistics = array_map( @@ -254,10 +228,10 @@ function (string $item) { ), ); - $renderingErrorCount = count($this->redisRenderingErrorManager->getRenderingErrors( + $renderingErrors = $this->redisRenderingErrorManager->getRenderingErrors( $contentReleaseIdentifier, $redisInstanceIdentifier, - )); + ); $currentReleaseIdentifier = $this->redisReleaseSwitchService->getCurrentRelease($redisInstanceIdentifier); @@ -266,10 +240,10 @@ function (string $item) { $contentReleaseJob, $this->redisEnumerationRepository->count($contentReleaseIdentifier), $renderingStatistics, - $renderingErrorCount, + $renderingErrors, $contentReleaseIdentifier->equals($currentReleaseIdentifier), $manualTransferJobs, - $contentReleaseMetadata->getContentReleaseSize(), + $contentReleaseMetadata->contentReleaseSize, !$this->redisContentReleaseService->isRegistered($contentReleaseIdentifier, $redisInstanceIdentifier), ); } diff --git a/Classes/BackendUi/ContentReleaseStatus.php b/Classes/BackendUi/ContentReleaseStatus.php index 96a4da6..09f11d6 100644 --- a/Classes/BackendUi/ContentReleaseStatus.php +++ b/Classes/BackendUi/ContentReleaseStatus.php @@ -35,7 +35,7 @@ public static function fromJob(Job $job, ?ContentReleaseMetadata $metadata): sel if ($job->isCanceled()) { return self::CANCELED; } - if ($job->isErrored() || ($metadata?->getStatus()->isFailed() ?? false)) { + if ($job->isErrored() || ($metadata?->status->isFailed() ?? false)) { return self::FAILED; } if ($job->isCompleted()) { @@ -51,10 +51,10 @@ public static function fromJob(Job $job, ?ContentReleaseMetadata $metadata): sel */ public static function jobGone(ContentReleaseMetadata $metadata): self { - if ($metadata->getStatus()->isFailed()) { + if ($metadata->status->isFailed()) { return self::FAILED; } - return $metadata->getSwitchTime() !== null ? self::SUCCESS : self::ABORTED; + return $metadata->switchTime !== null ? self::SUCCESS : self::ABORTED; } /** diff --git a/Classes/BackendUi/Dto/ContentReleaseDetails.php b/Classes/BackendUi/Dto/ContentReleaseDetails.php index fb02f50..3a6bb61 100644 --- a/Classes/BackendUi/Dto/ContentReleaseDetails.php +++ b/Classes/BackendUi/Dto/ContentReleaseDetails.php @@ -9,121 +9,25 @@ use Flowpack\Prunner\Dto\Job; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -class ContentReleaseDetails +#[Flow\Proxy(false)] +final readonly class ContentReleaseDetails { - private ContentReleaseIdentifier $contentReleaseIdentifier; - private ?Job $job; - private int $enumeratedDocumentNodesCount; - private int $renderingErrorCount; - private bool $isActive; - private ?float $contentReleaseSize; - private bool $isRemoved; - - /** - * @var Job[] - */ - private array $manualTransferJobs; - /** - * @var RenderingStatistics[] + * @param RenderingStatistics[] $renderingStatistics + * @param string[] $renderingErrors errors registered during rendering and validation, each " - " + * @param Job[] $manualTransferJobs + * @param float|null $contentReleaseSize size in megabytes, or NULL if it was not determined (yet) + * @param bool $isRemoved a removed release is no longer registered, so it can neither be switched to nor transferred - only the keys it keeps after removal are left, and its enumeration is gone */ - private array $renderingStatistics; - public function __construct( - ContentReleaseIdentifier $contentReleaseIdentifier, - ?Job $job, - int $enumeratedDocumentNodesCount, - array $renderingStatistics, - int $renderingErrorCount, - bool $isActive, - array $manualTransferJobIds, - ?float $contentReleaseSize = null, - bool $isRemoved = false, - ) { - $this->contentReleaseIdentifier = $contentReleaseIdentifier; - $this->job = $job; - $this->enumeratedDocumentNodesCount = $enumeratedDocumentNodesCount; - $this->renderingStatistics = $renderingStatistics; - $this->renderingErrorCount = $renderingErrorCount; - $this->isActive = $isActive; - $this->manualTransferJobs = $manualTransferJobIds; - $this->contentReleaseSize = $contentReleaseSize; - $this->isRemoved = $isRemoved; - } - - /** - * @return float|null size of the content release in megabytes, or NULL if it was not determined (yet) - */ - public function getContentReleaseSize(): ?float - { - return $this->contentReleaseSize; - } - - /** - * @return ContentReleaseIdentifier - */ - public function getContentReleaseIdentifier(): ContentReleaseIdentifier - { - return $this->contentReleaseIdentifier; - } - - /** - * @return Job|null - */ - public function getJob(): ?Job - { - return $this->job; - } - - /** - * @return int - */ - public function getEnumeratedDocumentNodesCount(): int - { - return $this->enumeratedDocumentNodesCount; - } - - /** - * @return RenderingStatistics[] - */ - public function getRenderingStatistics(): array - { - return $this->renderingStatistics; - } - - /** - * @return int - */ - public function getRenderingErrorCount(): int - { - return $this->renderingErrorCount; - } - - /** - * @return bool - */ - public function isActive(): bool - { - return $this->isActive; - } - - /** - * @return Job[] - */ - public function getManualTransferJobs(): array - { - return $this->manualTransferJobs; - } - - /** - * A removed release is no longer registered, so it can neither be switched to nor transferred - only the keys it - * keeps after removal are left, and its enumeration is gone. - */ - public function isRemoved(): bool - { - return $this->isRemoved; - } + public ContentReleaseIdentifier $contentReleaseIdentifier, + public ?Job $job, + public int $enumeratedDocumentNodesCount, + public array $renderingStatistics, + public array $renderingErrors, + public bool $isActive, + public array $manualTransferJobs, + public ?float $contentReleaseSize = null, + public bool $isRemoved = false, + ) {} } diff --git a/Classes/BackendUi/Dto/ContentReleaseOverviewRow.php b/Classes/BackendUi/Dto/ContentReleaseOverviewRow.php index 3e03328..c17826a 100644 --- a/Classes/BackendUi/Dto/ContentReleaseOverviewRow.php +++ b/Classes/BackendUi/Dto/ContentReleaseOverviewRow.php @@ -9,10 +9,8 @@ use Flowpack\DecoupledContentStore\PrepareContentRelease\Dto\ContentReleaseMetadata; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -class ContentReleaseOverviewRow +#[Flow\Proxy(false)] +final readonly class ContentReleaseOverviewRow { private ContentReleaseIdentifier $contentReleaseIdentifier; private ?ContentReleaseMetadata $metadata; diff --git a/Classes/BackendUi/Dto/RemovedContentReleaseOverviewRow.php b/Classes/BackendUi/Dto/RemovedContentReleaseOverviewRow.php index 7fc3333..08eb092 100644 --- a/Classes/BackendUi/Dto/RemovedContentReleaseOverviewRow.php +++ b/Classes/BackendUi/Dto/RemovedContentReleaseOverviewRow.php @@ -17,13 +17,13 @@ * that is known about the release. */ #[Flow\Proxy(false)] -final class RemovedContentReleaseOverviewRow +final readonly class RemovedContentReleaseOverviewRow { public function __construct( - private readonly ContentReleaseIdentifier $contentReleaseIdentifier, - private readonly Job $job, - private readonly ?ContentReleaseMetadata $metadata, - private readonly int $errorCount, + private ContentReleaseIdentifier $contentReleaseIdentifier, + private Job $job, + private ?ContentReleaseMetadata $metadata, + private int $errorCount, ) {} public function getContentReleaseIdentifier(): ContentReleaseIdentifier diff --git a/Classes/BackendUi/Dto/WorkerErrorLog.php b/Classes/BackendUi/Dto/WorkerErrorLog.php index 80c89fc..423c89d 100644 --- a/Classes/BackendUi/Dto/WorkerErrorLog.php +++ b/Classes/BackendUi/Dto/WorkerErrorLog.php @@ -5,13 +5,10 @@ namespace Flowpack\DecoupledContentStore\BackendUi\Dto; use Flowpack\DecoupledContentStore\BackendUi\WorkerErrorLogAggregator; -use Neos\Eel\ProtectedContextAwareInterface; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class WorkerErrorLog +#[Flow\Proxy(false)] +final readonly class WorkerErrorLog { public bool $wasKilledByOrchestrator; diff --git a/Classes/BackendUi/FusionObjects/RetrieveFlashMessagesImplementation.php b/Classes/BackendUi/FusionObjects/RetrieveFlashMessagesImplementation.php index 0266e7b..d5fb53b 100644 --- a/Classes/BackendUi/FusionObjects/RetrieveFlashMessagesImplementation.php +++ b/Classes/BackendUi/FusionObjects/RetrieveFlashMessagesImplementation.php @@ -4,19 +4,20 @@ namespace Flowpack\DecoupledContentStore\BackendUi\FusionObjects; +use Neos\Error\Messages\Message; use Neos\Flow\Annotations as Flow; use Neos\Flow\Mvc\FlashMessage\FlashMessageService; use Neos\Fusion\FusionObjects\AbstractFusionObject; -class RetrieveFlashMessagesImplementation extends AbstractFusionObject +final class RetrieveFlashMessagesImplementation extends AbstractFusionObject { + #[Flow\Inject] + protected FlashMessageService $flashMessageService; + /** - * @Flow\Inject - * @var FlashMessageService + * @return Message[] */ - protected $flashMessageService; - - public function evaluate() + public function evaluate(): array { return $this->flashMessageService ->getFlashMessageContainerForRequest($this->runtime->getControllerContext()->getRequest()) diff --git a/Classes/BackendUi/RenderingErrorExtractor.php b/Classes/BackendUi/RenderingErrorExtractor.php index cb6cbf4..4661c3f 100644 --- a/Classes/BackendUi/RenderingErrorExtractor.php +++ b/Classes/BackendUi/RenderingErrorExtractor.php @@ -6,10 +6,8 @@ use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RenderingErrorExtractor +#[Flow\Scope('singleton')] +final readonly class RenderingErrorExtractor { /** * Extracts ERROR-prefixed lines and exception blocks from a raw log string. @@ -80,7 +78,7 @@ public function extractErrorBlocks(string $log): array * * NodeRenderer logs a DEBUG line "Rendering document node variant" before * each render and a logException(...) entry on failure; both include the - * node identifier in the JSON payload. The very last "node":"..." match in + * node identifier in the JSON payload, the DEBUG line also the label path from the site node down. The very last "node":"..." match in * the log is therefore the most likely failing node, whether the worker * threw an exception or got killed mid-render. */ @@ -91,7 +89,7 @@ public function extractLastAttemptedNode(string $log): ?string } if (!preg_match_all( - '/"node"\s*:\s*"((?:\\\\.|[^"\\\\])*)"(?:\s*,\s*"nodeUri"\s*:\s*"((?:\\\\.|[^"\\\\])*)")?/', + '/"node"\s*:\s*"((?:\\\\.|[^"\\\\])*)"(?:\s*,\s*"nodeLabel"\s*:\s*"((?:\\\\.|[^"\\\\])*)")?(?:\s*,\s*"nodeUri"\s*:\s*"((?:\\\\.|[^"\\\\])*)")?/', $log, $matches, PREG_SET_ORDER, @@ -100,9 +98,12 @@ public function extractLastAttemptedNode(string $log): ?string } $last = end($matches); - $node = $this->decodeJsonString($last[1]); - $uri = isset($last[2]) ? $this->decodeJsonString($last[2]) : ''; - return $uri !== '' ? sprintf('%s | %s', $node, $uri) : $node; + $parts = [ + $this->decodeJsonString($last[2] ?? ''), + $this->decodeJsonString($last[1]), + $this->decodeJsonString($last[3] ?? ''), + ]; + return implode(' | ', array_filter($parts, static fn(string $part): bool => $part !== '')); } private function decodeJsonString(string $raw): string diff --git a/Classes/BackendUi/WorkerErrorLogAggregator.php b/Classes/BackendUi/WorkerErrorLogAggregator.php index 5e78223..a82f03d 100644 --- a/Classes/BackendUi/WorkerErrorLogAggregator.php +++ b/Classes/BackendUi/WorkerErrorLogAggregator.php @@ -10,34 +10,26 @@ use Flowpack\Prunner\PrunnerApiService; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class WorkerErrorLogAggregator +#[Flow\Scope('singleton')] +final readonly class WorkerErrorLogAggregator { - /** - * @Flow\Inject - * @var PrunnerApiService - */ - protected $prunnerApiService; - - /** - * @Flow\Inject - * @var RenderingErrorExtractor - */ - protected $renderingErrorExtractor; - /** * Exit code 143 = 128 + SIGTERM(15): orchestrator killed this worker after another one failed. */ public const EXIT_CODE_SIGTERM = 143; + public function __construct( + private PrunnerApiService $prunnerApiService, + private RenderingErrorExtractor $renderingErrorExtractor, + ) {} + /** * @return WorkerErrorLog[] */ public function aggregate(Job $job): array { - $renderTasks = $job->getTaskResults() + $renderTasks = $job + ->getTaskResults() ->filteredByPrefix('render_') ->withoutTasks('render_finished', 'render_orchestrator'); diff --git a/Classes/Command/ContentReleaseEventsCommandController.php b/Classes/Command/ContentReleaseEventsCommandController.php index 4949ee0..015ab5f 100644 --- a/Classes/Command/ContentReleaseEventsCommandController.php +++ b/Classes/Command/ContentReleaseEventsCommandController.php @@ -14,10 +14,13 @@ /** * Commands to read statistics events for a content release from redis */ -class ContentReleaseEventsCommandController extends CommandController +final class ContentReleaseEventsCommandController extends CommandController { - #[Flow\Inject] - protected RedisStatisticsEventService $redisStatisticsEventService; + public function __construct( + private readonly RedisStatisticsEventService $redisStatisticsEventService, + ) { + parent::__construct(); + } /** * Count statistics events in a content release. diff --git a/Classes/Command/ContentReleasePrepareCommandController.php b/Classes/Command/ContentReleasePrepareCommandController.php index 62a98fc..c9f3ca3 100644 --- a/Classes/Command/ContentReleasePrepareCommandController.php +++ b/Classes/Command/ContentReleasePrepareCommandController.php @@ -11,32 +11,21 @@ use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger; use Flowpack\DecoupledContentStore\NodeRendering\Dto\NodeRenderingCompletionStatus; use Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure\RedisContentReleaseService; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; use Neos\Fusion\Core\Cache\ContentCache; /** * Commands for the PREPARE stage in the pipeline. Not meant to be called manually. */ -class ContentReleasePrepareCommandController extends CommandController +final class ContentReleasePrepareCommandController extends CommandController { - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; - - /** - * @Flow\Inject - * @var ConcurrentBuildLockService - */ - protected $concurrentBuildLock; - - /** - * @Flow\Inject - * @var ContentCache - */ - protected $contentCache; + public function __construct( + private readonly RedisContentReleaseService $redisContentReleaseService, + private readonly ConcurrentBuildLockService $concurrentBuildLock, + private readonly ContentCache $contentCache, + ) { + parent::__construct(); + } public function createContentReleaseCommand( string $contentReleaseIdentifier, @@ -56,8 +45,9 @@ public function createContentReleaseCommand( ); } - public function ensureAllOtherInProgressContentReleasesWillBeTerminatedCommand(string $contentReleaseIdentifier): void - { + public function ensureAllOtherInProgressContentReleasesWillBeTerminatedCommand( + string $contentReleaseIdentifier, + ): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $this->concurrentBuildLock->ensureAllOtherInProgressContentReleasesWillBeTerminated($contentReleaseIdentifier); @@ -84,7 +74,7 @@ public function markFailedCommand(string $contentReleaseIdentifier, string $prun { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $metadata = $this->redisContentReleaseService->fetchMetadataForContentRelease($contentReleaseIdentifier); - if ($metadata === null || $metadata->getPrunnerJobId()->getIdentifier() !== $prunnerJobId) { + if ($metadata === null || $metadata->prunnerJobId->getIdentifier() !== $prunnerJobId) { return; } diff --git a/Classes/Command/ContentReleaseQuickPublishCommandController.php b/Classes/Command/ContentReleaseQuickPublishCommandController.php index ebf3161..9fd8182 100644 --- a/Classes/Command/ContentReleaseQuickPublishCommandController.php +++ b/Classes/Command/ContentReleaseQuickPublishCommandController.php @@ -11,7 +11,6 @@ use Flowpack\DecoupledContentStore\QuickPublish\Dto\NodeIdentifiers; use Flowpack\DecoupledContentStore\QuickPublish\Infrastructure\RedisReleaseCopyService; use Flowpack\DecoupledContentStore\QuickPublish\QuickPublishNodeEnumerator; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; /** @@ -19,11 +18,12 @@ */ final class ContentReleaseQuickPublishCommandController extends CommandController { - #[Flow\Inject] - protected RedisReleaseCopyService $redisReleaseCopyService; - - #[Flow\Inject] - protected QuickPublishNodeEnumerator $quickPublishNodeEnumerator; + public function __construct( + private readonly RedisReleaseCopyService $redisReleaseCopyService, + private readonly QuickPublishNodeEnumerator $quickPublishNodeEnumerator, + ) { + parent::__construct(); + } /** * Take the content of a finished content release over into a new one, within the same redis instance. diff --git a/Classes/Command/ContentReleaseSwitchCommandController.php b/Classes/Command/ContentReleaseSwitchCommandController.php index e1209b5..dd61978 100644 --- a/Classes/Command/ContentReleaseSwitchCommandController.php +++ b/Classes/Command/ContentReleaseSwitchCommandController.php @@ -8,22 +8,23 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger; use Flowpack\DecoupledContentStore\ReleaseSwitch\Infrastructure\RedisReleaseSwitchService; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; /** * Commands for the SWITCH stage in the pipeline. Not meant to be called manually. */ -class ContentReleaseSwitchCommandController extends CommandController +final class ContentReleaseSwitchCommandController extends CommandController { - /** - * @Flow\Inject - * @var RedisReleaseSwitchService - */ - protected $redisReleaseSwitchService; + public function __construct( + private readonly RedisReleaseSwitchService $redisReleaseSwitchService, + ) { + parent::__construct(); + } - public function switchActiveContentReleaseCommand(string $redisInstanceIdentifier, string $contentReleaseIdentifier) - { + public function switchActiveContentReleaseCommand( + string $redisInstanceIdentifier, + string $contentReleaseIdentifier, + ): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $logger = ContentReleaseLogger::fromConsoleOutput($this->output, $contentReleaseIdentifier); diff --git a/Classes/Command/ContentReleaseTransferCommandController.php b/Classes/Command/ContentReleaseTransferCommandController.php index 3113984..0f55d60 100644 --- a/Classes/Command/ContentReleaseTransferCommandController.php +++ b/Classes/Command/ContentReleaseTransferCommandController.php @@ -10,49 +10,42 @@ use Flowpack\DecoupledContentStore\Transfer\ContentReleaseCleaner; use Flowpack\DecoupledContentStore\Transfer\ContentReleaseSynchronizer; use Flowpack\DecoupledContentStore\Transfer\Resource\RemoteResourceSynchronizer; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; /** * Commands for the TRANSFER stage in the pipeline. Not meant to be called manually. */ -class ContentReleaseTransferCommandController extends CommandController +final class ContentReleaseTransferCommandController extends CommandController { - /** - * @Flow\Inject - * @var RemoteResourceSynchronizer - */ - protected $remoteResourceSynchronizer; - - /** - * @Flow\Inject - * @var ContentReleaseSynchronizer - */ - protected $contentReleaseSynchronizer; - - /** - * @Flow\Inject - * @var ContentReleaseCleaner - */ - protected $contentReleaseCleaner; + public function __construct( + private readonly RemoteResourceSynchronizer $remoteResourceSynchronizer, + private readonly ContentReleaseSynchronizer $contentReleaseSynchronizer, + private readonly ContentReleaseCleaner $contentReleaseCleaner, + ) { + parent::__construct(); + } - public function syncResourcesCommand(string $contentReleaseIdentifier) + public function syncResourcesCommand(string $contentReleaseIdentifier): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $logger = ContentReleaseLogger::fromConsoleOutput($this->output, $contentReleaseIdentifier); $this->remoteResourceSynchronizer->synchronize($logger); } - public function transferToContentStoreCommand(string $redisContentStoreIdentifier, string $contentReleaseIdentifier) - { + public function transferToContentStoreCommand( + string $redisContentStoreIdentifier, + string $contentReleaseIdentifier, + ): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $redisInstanceIdentifier = RedisInstanceIdentifier::fromString($redisContentStoreIdentifier); $logger = ContentReleaseLogger::fromConsoleOutput($this->output, $contentReleaseIdentifier); $this->contentReleaseSynchronizer->syncToTarget($redisInstanceIdentifier, $contentReleaseIdentifier, $logger); } - public function removeOldReleasesCommand(string $redisContentStoreIdentifier, string $contentReleaseIdentifier) - { + public function removeOldReleasesCommand( + string $redisContentStoreIdentifier, + string $contentReleaseIdentifier, + ): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $redisInstanceIdentifier = RedisInstanceIdentifier::fromString($redisContentStoreIdentifier); $logger = ContentReleaseLogger::fromConsoleOutput($this->output, $contentReleaseIdentifier); diff --git a/Classes/Command/ContentReleaseValidationCommandController.php b/Classes/Command/ContentReleaseValidationCommandController.php index edec92a..b21d28d 100644 --- a/Classes/Command/ContentReleaseValidationCommandController.php +++ b/Classes/Command/ContentReleaseValidationCommandController.php @@ -17,29 +17,22 @@ /** * Commands for the VALIDATION stage in the pipeline. Not meant to be called manually. */ -class ContentReleaseValidationCommandController extends CommandController +final class ContentReleaseValidationCommandController extends CommandController { - /** - * @Flow\Inject - * @var RedisRenderingErrorManager - */ - protected $redisRenderingErrorManager; - - /** - * @Flow\Inject - * @var RedisReleaseSwitchService - */ - protected $redisReleaseSwitchService; - - #[Flow\Inject] - protected ContentReleaseScope $contentReleaseScope; - /** * Factor between 0 and 1 for the amount of URLs a new release needs to include to be valid */ protected float $validReleaseUrlCountThreshold = 0.7; - public function validateCommand(string $contentReleaseIdentifier) + public function __construct( + private readonly RedisRenderingErrorManager $redisRenderingErrorManager, + private readonly RedisReleaseSwitchService $redisReleaseSwitchService, + private readonly ContentReleaseScope $contentReleaseScope, + ) { + parent::__construct(); + } + + public function validateCommand(string $contentReleaseIdentifier): void { $startedAt = microtime(true); $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); @@ -122,7 +115,7 @@ private function logCompletion(ContentReleaseLogger $logger, float $startedAt): )); } - public function ensureNoValidationErrorsExistCommand(string $contentReleaseIdentifier) + public function ensureNoValidationErrorsExistCommand(string $contentReleaseIdentifier): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $logger = ContentReleaseLogger::fromConsoleOutput($this->output, $contentReleaseIdentifier); diff --git a/Classes/Command/ContentStorePruneCommandController.php b/Classes/Command/ContentStorePruneCommandController.php index 5924ae6..bcabd87 100644 --- a/Classes/Command/ContentStorePruneCommandController.php +++ b/Classes/Command/ContentStorePruneCommandController.php @@ -6,18 +6,17 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; use Flowpack\DecoupledContentStore\Core\RedisPruneService; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; -class ContentStorePruneCommandController extends CommandController +final class ContentStorePruneCommandController extends CommandController { - /** - * @Flow\Inject - * @var RedisPruneService - */ - protected $redisPruneService; + public function __construct( + private readonly RedisPruneService $redisPruneService, + ) { + parent::__construct(); + } - public function pruneRedisInstanceCommand(string $redisInstanceIdentifier) + public function pruneRedisInstanceCommand(string $redisInstanceIdentifier): void { $redisInstanceIdentifier = RedisInstanceIdentifier::fromString($redisInstanceIdentifier); diff --git a/Classes/Command/ContentStorePublishCommandController.php b/Classes/Command/ContentStorePublishCommandController.php index 70867be..85dc695 100644 --- a/Classes/Command/ContentStorePublishCommandController.php +++ b/Classes/Command/ContentStorePublishCommandController.php @@ -5,18 +5,17 @@ namespace Flowpack\DecoupledContentStore\Command; use Flowpack\DecoupledContentStore\ContentReleaseManager; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; -class ContentStorePublishCommandController extends CommandController +final class ContentStorePublishCommandController extends CommandController { - /** - * @Flow\Inject - * @var ContentReleaseManager - */ - protected $contentReleaseManager; + public function __construct( + private readonly ContentReleaseManager $contentReleaseManager, + ) { + parent::__construct(); + } - public function allCommand() + public function allCommand(): void { $this->contentReleaseManager->cancelAllRunningContentReleases(); $this->contentReleaseManager->startFullContentRelease(); diff --git a/Classes/Command/NodeEnumerationCommandController.php b/Classes/Command/NodeEnumerationCommandController.php index 09f5b0b..fd0a01a 100644 --- a/Classes/Command/NodeEnumerationCommandController.php +++ b/Classes/Command/NodeEnumerationCommandController.php @@ -7,21 +7,20 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger; use Flowpack\DecoupledContentStore\NodeEnumeration\NodeEnumerator; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; /** * Commands for the ENUMERATE stage in the pipeline. Not meant to be called manually. */ -class NodeEnumerationCommandController extends CommandController +final class NodeEnumerationCommandController extends CommandController { - /** - * @Flow\Inject - * @var NodeEnumerator - */ - protected $nodeEnumerator; + public function __construct( + private readonly NodeEnumerator $nodeEnumerator, + ) { + parent::__construct(); + } - public function enumerateAllNodesCommand(string $contentReleaseIdentifier) + public function enumerateAllNodesCommand(string $contentReleaseIdentifier): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $logger = ContentReleaseLogger::fromConsoleOutput($this->output, $contentReleaseIdentifier); diff --git a/Classes/Command/NodeRenderingCommandController.php b/Classes/Command/NodeRenderingCommandController.php index cd95462..97128f9 100644 --- a/Classes/Command/NodeRenderingCommandController.php +++ b/Classes/Command/NodeRenderingCommandController.php @@ -10,27 +10,21 @@ use Flowpack\DecoupledContentStore\NodeRendering\InterruptibleProcessRuntime; use Flowpack\DecoupledContentStore\NodeRendering\NodeRenderer; use Flowpack\DecoupledContentStore\NodeRendering\NodeRenderOrchestrator; -use Neos\Flow\Annotations as Flow; use Neos\Flow\Cli\CommandController; /** * Commands for the RENDERING stage in the pipeline. Not meant to be called manually. */ -class NodeRenderingCommandController extends CommandController +final class NodeRenderingCommandController extends CommandController { - /** - * @Flow\Inject - * @var NodeRenderOrchestrator - */ - protected $nodeRenderOrchestrator; - - /** - * @Flow\Inject - * @var NodeRenderer - */ - protected $nodeRenderer; - - public function orchestrateRenderingCommand(string $contentReleaseIdentifier) + public function __construct( + private readonly NodeRenderOrchestrator $nodeRenderOrchestrator, + private readonly NodeRenderer $nodeRenderer, + ) { + parent::__construct(); + } + + public function orchestrateRenderingCommand(string $contentReleaseIdentifier): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $logger = ContentReleaseLogger::fromConsoleOutput($this->output, $contentReleaseIdentifier); @@ -41,7 +35,7 @@ public function orchestrateRenderingCommand(string $contentReleaseIdentifier) ))->runUntilEnd(); } - public function renderWorkerCommand(string $contentReleaseIdentifier, string $rendererIdentifier) + public function renderWorkerCommand(string $contentReleaseIdentifier, string $rendererIdentifier): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $rendererIdentifier = RendererIdentifier::fromString($rendererIdentifier); diff --git a/Classes/ContentReleaseManager.php b/Classes/ContentReleaseManager.php index 47c7d6f..51dc30a 100644 --- a/Classes/ContentReleaseManager.php +++ b/Classes/ContentReleaseManager.php @@ -14,51 +14,32 @@ use Flowpack\Prunner\PrunnerApiService; use Flowpack\Prunner\ValueObject\JobId; use Flowpack\Prunner\ValueObject\PipelineName; -use Neos\ContentRepository\Domain\Model\Workspace; +use Neos\ContentRepository\Core\SharedModel\Workspace\Workspace; use Neos\Flow\Annotations as Flow; use Neos\Flow\Log\Utility\LogEnvironment; use Neos\Flow\Security\Context; use Psr\Log\LoggerInterface; -/** - * @Flow\Scope("singleton") - */ -class ContentReleaseManager +#[Flow\Scope('singleton')] +final readonly class ContentReleaseManager { - /** - * @Flow\Inject - * @var PrunnerApiService - */ - protected $prunnerApiService; - - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; + public const string REDIS_CURRENT_RELEASE_KEY = 'contentStore:current'; + public const string NO_PREVIOUS_RELEASE = 'NO_PREVIOUS_RELEASE'; + public const string CONTENT_RELEASE_PIPELINE_NAME = 'do_content_release'; + public const string QUICK_CONTENT_RELEASE_PIPELINE_NAME = 'do_quick_content_release'; /** - * @Flow\InjectConfiguration("configEpoch") - * @var array + * @param array $configEpochSettings */ - protected $configEpochSettings; - - /** - * @FLow\Inject - * @var Context - */ - protected $securityContext; - - #[Flow\Inject] - protected AutomaticReleaseSwitchService $automaticReleaseSwitchService; - - #[Flow\Inject] - protected LoggerInterface $logger; - - const REDIS_CURRENT_RELEASE_KEY = 'contentStore:current'; - const NO_PREVIOUS_RELEASE = 'NO_PREVIOUS_RELEASE'; - const CONTENT_RELEASE_PIPELINE_NAME = 'do_content_release'; - const QUICK_CONTENT_RELEASE_PIPELINE_NAME = 'do_quick_content_release'; + public function __construct( + private PrunnerApiService $prunnerApiService, + private RedisClientManager $redisClientManager, + private AutomaticReleaseSwitchService $automaticReleaseSwitchService, + private LoggerInterface $logger, + private Context $securityContext, + #[Flow\InjectConfiguration('configEpoch')] + protected array $configEpochSettings, + ) {} /** * All automatic release triggers (workspace publish, asset change, re-release after a rendering error) run through @@ -96,7 +77,7 @@ public function startIncrementalContentRelease( 'currentContentReleaseId' => $this->resolveCurrentContentReleaseId($currentContentReleaseId), 'validate' => true, 'flushContentCache' => false, - 'workspaceName' => $workspace !== null ? $workspace->getName() : 'live', + 'workspaceName' => $workspace !== null ? $workspace->workspaceName->value : 'live', 'accountId' => $this->getAccountId(), ]), ); @@ -121,7 +102,7 @@ public function startFullContentRelease( 'currentContentReleaseId' => $this->resolveCurrentContentReleaseId($currentContentReleaseId), 'validate' => $validate, 'flushContentCache' => true, - 'workspaceName' => $workspace !== null ? $workspace->getName() : 'live', + 'workspaceName' => $workspace !== null ? $workspace->workspaceName->value : 'live', 'accountId' => $this->getAccountId(), ]), ); @@ -163,12 +144,14 @@ public function startQuickContentRelease( // Jobs::waiting() means "never started", which is true of a job cancelled while it was still queued as well. // Such a job stays in prunner's list until it falls out of the pipeline's retention_count - a window only // quick releases consume - so without the isCompleted() guard one cancelled job blocks them all until then. - $queuedQuickReleaseJobs = $quickReleaseJobs->waiting() + $queuedQuickReleaseJobs = $quickReleaseJobs + ->waiting() ->filter(static fn(Job $job): bool => !$job->isCompleted()); // Jobs::running() means "started but not ended". A job that was running when prunner stopped // is flagged cancelled on its next boot but never gets an end timestamp, and cancelling it // again is a no-op for prunner - so it reads as running for the rest of its retention window. - $runningQuickReleaseJobs = $quickReleaseJobs->running() + $runningQuickReleaseJobs = $quickReleaseJobs + ->running() ->filter(static fn(Job $job): bool => !$job->isCanceled()); if ($runningQuickReleaseJobs->getArray() !== [] || $queuedQuickReleaseJobs->getArray() !== []) { throw new QuickContentReleaseNotPossibleException( @@ -184,7 +167,7 @@ public function startQuickContentRelease( 'contentReleaseId' => $contentReleaseId, 'currentContentReleaseId' => $currentContentReleaseId, 'quickPublishNodeIdentifiers' => (string) $nodeIdentifiers, - 'workspaceName' => $workspace !== null ? $workspace->getName() : 'live', + 'workspaceName' => $workspace !== null ? $workspace->workspaceName->value : 'live', 'accountId' => $this->getAccountId(), ]), ); diff --git a/Classes/Controller/BackendController.php b/Classes/Controller/BackendController.php index b900a11..7868a1b 100644 --- a/Classes/Controller/BackendController.php +++ b/Classes/Controller/BackendController.php @@ -14,115 +14,54 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger; use Flowpack\DecoupledContentStore\Core\Infrastructure\RedisClientManager; -use Flowpack\DecoupledContentStore\Core\RedisKeyService; use Flowpack\DecoupledContentStore\Core\RedisPruneService; use Flowpack\DecoupledContentStore\Exception; -use Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure\RedisContentReleaseService; use Flowpack\DecoupledContentStore\QuickPublish\Dto\NodeIdentifiers; use Flowpack\DecoupledContentStore\QuickPublish\QuickPublishPreviewService; use Flowpack\DecoupledContentStore\ReleaseSwitch\Infrastructure\RedisReleaseSwitchService; use Flowpack\DecoupledContentStore\Transfer\ContentReleaseCleaner; use Flowpack\Prunner\PrunnerApiService; use Flowpack\Prunner\ValueObject\PipelineName; +use GuzzleHttp\Psr7\Response; use Neos\Error\Messages\Message; use Neos\Flow\Annotations as Flow; use Neos\Flow\I18n\Translator; use Neos\Flow\Mvc\Controller\ActionController; use Neos\Fusion\View\FusionView; use Neos\Neos\Controller\BackendUserTranslationTrait; +use Psr\Http\Message\ResponseInterface; use Symfony\Component\Console\Output\BufferedOutput; -class BackendController extends ActionController +final class BackendController extends ActionController { use BackendUserTranslationTrait; - /** - * @Flow\Inject - * @var PrunnerApiService - */ - protected $prunnerApiService; - - /** - * @Flow\Inject - * @var ContentReleaseManager - */ - protected $contentReleaseManager; - - /** - * @Flow\Inject - * @var BackendUiDataService - */ - protected $backendUiDataService; - - /** - * @Flow\Inject - * @var WorkerErrorLogAggregator - */ - protected $workerErrorLogAggregator; - - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; - - /** - * @Flow\Inject - * @var RedisReleaseSwitchService - */ - protected $redisReleaseSwitchService; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; - - /** - * @Flow\Inject - * @var ContentReleaseCleaner - */ - protected $contentReleaseCleaner; - - /** - * @Flow\Inject - * @var RedisPruneService - */ - protected $redisPruneService; - - #[Flow\Inject] - protected AutomaticReleaseSwitchService $automaticReleaseSwitchService; - - #[Flow\Inject] - protected Translator $translator; - - #[Flow\Inject] - protected BackendDateFormatter $backendDateFormatter; - - #[Flow\Inject] - protected QuickPublishPreviewService $quickPublishPreviewService; - - /** - * @Flow\InjectConfiguration("redisContentStores") - * @var array - */ - protected $redisContentStores; + protected $defaultViewObjectName = FusionView::class; /** - * @Flow\InjectConfiguration("configEpoch") - * @var array + * @param array $redisContentStores + * @param array $configEpochSettings */ - protected $configEpochSettings; - - protected $defaultViewObjectName = FusionView::class; - - public function indexAction(?string $contentStore = null) + public function __construct( + private readonly PrunnerApiService $prunnerApiService, + private readonly ContentReleaseManager $contentReleaseManager, + private readonly BackendUiDataService $backendUiDataService, + private readonly WorkerErrorLogAggregator $workerErrorLogAggregator, + private readonly RedisClientManager $redisClientManager, + private readonly RedisReleaseSwitchService $redisReleaseSwitchService, + private readonly ContentReleaseCleaner $contentReleaseCleaner, + private readonly RedisPruneService $redisPruneService, + private readonly AutomaticReleaseSwitchService $automaticReleaseSwitchService, + private readonly Translator $translator, + private readonly BackendDateFormatter $backendDateFormatter, + private readonly QuickPublishPreviewService $quickPublishPreviewService, + #[Flow\InjectConfiguration('redisContentStores')] + protected readonly array $redisContentStores, + #[Flow\InjectConfiguration('configEpoch')] + protected readonly array $configEpochSettings, + ) {} + + public function indexAction(?string $contentStore = null): void { $contentStore = $contentStore ? RedisInstanceIdentifier::fromString($contentStore) @@ -164,7 +103,7 @@ public function detailsAction( ?string $detailTaskName = '', ?string $prunnerJobId = '', bool $showAllRenderingErrors = false, - ) { + ): void { $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); $contentStore = $contentStore ? RedisInstanceIdentifier::fromString($contentStore) @@ -186,12 +125,12 @@ public function detailsAction( ); } $this->view->assign('removedReleaseJob', $removedReleaseJob); - $job = $detailsData?->getJob() ?? $removedReleaseJob; + $job = $detailsData->job ?? $removedReleaseJob; if ($detailTaskName !== '') { $this->view->assign('detailTaskName', $detailTaskName); $this->view->assign('jobLogs', $this->prunnerApiService->loadJobLogs( - $prunnerJobId ? PrunnerJobId::fromString($prunnerJobId)->toJobId() : $detailsData->getJob()->getId(), + $prunnerJobId ? PrunnerJobId::fromString($prunnerJobId)->toJobId() : $detailsData->job->getId(), $detailTaskName, )); } elseif ($showAllRenderingErrors && $job !== null) { @@ -199,25 +138,24 @@ public function detailsAction( } } - public function publishAllAction() + public function publishAllAction(): void { $this->contentReleaseManager->cancelAllRunningContentReleases(); $this->contentReleaseManager->startFullContentRelease(); $this->redirect('index'); } - public function publishAllWithoutValidationAction() + public function publishAllWithoutValidationAction(): void { $this->contentReleaseManager->cancelAllRunningContentReleases(); $this->contentReleaseManager->startFullContentRelease(false); $this->redirect('index'); } - public function removeAction(string $contentReleaseIdentifier, string $redisInstanceIdentifier) + public function removeAction(string $contentReleaseIdentifier, string $redisInstanceIdentifier): ResponseInterface { if ($this->request->getHttpRequest()->getMethod() !== 'POST') { - $this->response->setStatusCode(405); - return 'Method not allowed'; + return new Response(405, [], 'Method not allowed'); } $contentReleaseIdentifierToRemove = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); @@ -242,11 +180,10 @@ public function removeAction(string $contentReleaseIdentifier, string $redisInst $this->redirect('index', null, null, ['contentStore' => $redisInstanceIdentifier->getIdentifier()]); } - public function switchAction(string $contentReleaseIdentifier, string $redisInstanceIdentifier) + public function switchAction(string $contentReleaseIdentifier, string $redisInstanceIdentifier): ResponseInterface { if ($this->request->getHttpRequest()->getMethod() !== 'POST') { - $this->response->setStatusCode(405); - return 'Method not allowed'; + return new Response(405, [], 'Method not allowed'); } $contentReleaseIdentifier = ContentReleaseIdentifier::fromString($contentReleaseIdentifier); @@ -269,7 +206,7 @@ public function switchAction(string $contentReleaseIdentifier, string $redisInst public function switchContentReleaseOnOtherInstanceAction( string $targetRedisInstanceIdentifier, string $contentReleaseIdentifier, - ) { + ): void { $redis = $this->redisClientManager->getPrimaryRedis(); $currentContentReleaseId = $redis->get('contentStore:current'); @@ -282,7 +219,7 @@ public function switchContentReleaseOnOtherInstanceAction( $this->redirect('index', null, null, ['contentStore' => $targetRedisInstanceIdentifier]); } - public function pruneContentStoreAction(string $redisInstanceIdentifier) + public function pruneContentStoreAction(string $redisInstanceIdentifier): void { $redisInstanceIdentifier = RedisInstanceIdentifier::fromString($redisInstanceIdentifier); $this->redisPruneService->pruneRedisInstance($redisInstanceIdentifier); @@ -290,7 +227,7 @@ public function pruneContentStoreAction(string $redisInstanceIdentifier) $this->redirect('index', null, null, ['contentStore' => $redisInstanceIdentifier->getIdentifier()]); } - public function cancelRunningReleaseAction(string $redisInstanceIdentifier) + public function cancelRunningReleaseAction(string $redisInstanceIdentifier): void { $redisInstanceIdentifier = RedisInstanceIdentifier::fromString($redisInstanceIdentifier); $this->contentReleaseManager->cancelAllRunningContentReleases(); @@ -298,37 +235,31 @@ public function cancelRunningReleaseAction(string $redisInstanceIdentifier) $this->redirect('index', null, null, ['contentStore' => $redisInstanceIdentifier->getIdentifier()]); } - public function pauseAutomaticReleasesAction(?string $contentStore = null): ?string + public function pauseAutomaticReleasesAction(?string $contentStore = null): ResponseInterface { if ($this->request->getHttpRequest()->getMethod() !== 'POST') { - $this->response->setStatusCode(405); - return 'Method not allowed'; + return new Response(405, [], 'Method not allowed'); } $this->automaticReleaseSwitchService->pause(); $this->addFlashMessage($this->translateById('automaticReleases.paused.flashMessage')); $this->redirect('index', null, null, $contentStore !== null ? ['contentStore' => $contentStore] : []); - - return null; } - public function resumeAutomaticReleasesAction(?string $contentStore = null): ?string + public function resumeAutomaticReleasesAction(?string $contentStore = null): ResponseInterface { if ($this->request->getHttpRequest()->getMethod() !== 'POST') { - $this->response->setStatusCode(405); - return 'Method not allowed'; + return new Response(405, [], 'Method not allowed'); } $this->automaticReleaseSwitchService->resume(); $this->addFlashMessage($this->translateById('automaticReleases.resumed.flashMessage')); $this->redirect('index', null, null, $contentStore !== null ? ['contentStore' => $contentStore] : []); - - return null; } - public function toggleConfigEpochAction(string $redisInstanceIdentifier) + public function toggleConfigEpochAction(string $redisInstanceIdentifier): void { $redisInstanceIdentifier = RedisInstanceIdentifier::fromString($redisInstanceIdentifier); $this->contentReleaseManager->toggleConfigEpoch($redisInstanceIdentifier); @@ -350,11 +281,10 @@ public function quickPublishFormAction(?string $contentStore = null, string $nod * What the given identifiers resolve to, before anything is published. The identifiers end up in a shell command * in the pipeline, so this is also where anything which is not a node identifier is rejected. */ - public function quickPublishPreviewAction(string $nodeIdentifiers, ?string $contentStore = null): ?string + public function quickPublishPreviewAction(string $nodeIdentifiers, ?string $contentStore = null): ?ResponseInterface { if ($this->request->getHttpRequest()->getMethod() !== 'POST') { - $this->response->setStatusCode(405); - return 'Method not allowed'; + return new Response(405, [], 'Method not allowed'); } try { @@ -365,8 +295,6 @@ public function quickPublishPreviewAction(string $nodeIdentifiers, ?string $cont 'contentStore' => $contentStore, 'nodeIdentifiers' => $nodeIdentifiers, ]); - - return null; } $previewRows = $this->quickPublishPreviewService->preview($identifiers, $this->controllerContext); @@ -379,11 +307,10 @@ public function quickPublishPreviewAction(string $nodeIdentifiers, ?string $cont return null; } - public function quickPublishAction(string $nodeIdentifiers, ?string $contentStore = null): ?string + public function quickPublishAction(string $nodeIdentifiers, ?string $contentStore = null): ResponseInterface { if ($this->request->getHttpRequest()->getMethod() !== 'POST') { - $this->response->setStatusCode(405); - return 'Method not allowed'; + return new Response(405, [], 'Method not allowed'); } try { @@ -397,14 +324,10 @@ public function quickPublishAction(string $nodeIdentifiers, ?string $contentStor 'contentStore' => $contentStore, 'nodeIdentifiers' => $nodeIdentifiers, ]); - - return null; } $this->addFlashMessage($this->translateById('quickPublish.scheduled.flashMessage', [$contentReleaseIdentifier->getIdentifier()])); $this->redirect('index', null, null, $contentStore !== null ? ['contentStore' => $contentStore] : []); - - return null; } /** diff --git a/Classes/Core/AutomaticReleaseSwitchService.php b/Classes/Core/AutomaticReleaseSwitchService.php index d783589..9eced16 100644 --- a/Classes/Core/AutomaticReleaseSwitchService.php +++ b/Classes/Core/AutomaticReleaseSwitchService.php @@ -20,7 +20,7 @@ * remove it. */ #[Flow\Scope('singleton')] -class AutomaticReleaseSwitchService +final readonly class AutomaticReleaseSwitchService { private const REDIS_KEY = 'contentStore:automaticReleasesPaused'; @@ -37,11 +37,10 @@ class AutomaticReleaseSwitchService end '; - #[Flow\Inject] - protected RedisClientManager $redisClientManager; - - #[Flow\Inject] - protected Context $securityContext; + public function __construct( + private RedisClientManager $redisClientManager, + private Context $securityContext, + ) {} public function isPaused(): bool { @@ -67,7 +66,7 @@ public function pause(): void } $this->redisClientManager->getPrimaryRedis()->hMset(self::REDIS_KEY, [ - 'pausedAt' => (new DateTimeImmutable())->format(DateTimeInterface::ATOM), + 'pausedAt' => new DateTimeImmutable()->format(DateTimeInterface::ATOM), 'accountId' => $this->getAccountId() ?? '', 'suppressedReleaseCount' => 0, ]); diff --git a/Classes/Core/ConcurrentBuildLockService.php b/Classes/Core/ConcurrentBuildLockService.php index 3ba511a..e50d0b4 100644 --- a/Classes/Core/ConcurrentBuildLockService.php +++ b/Classes/Core/ConcurrentBuildLockService.php @@ -6,8 +6,10 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Infrastructure\RedisClientManager; +use Flowpack\DecoupledContentStore\PrepareContentRelease\Dto\ContentReleaseMetadata; use Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure\RedisContentReleaseService; use Neos\Flow\Annotations as Flow; +use RuntimeException; /** * We usually rely on prunner to ensure that only one build per workspace is running at any given time. @@ -25,50 +27,42 @@ * `./flow contentReleasePrepare:ensureAllOtherInProgressContentReleasesWillBeTerminated` * - In the "Enumerate" and "Render" phases, we periodically check whether the concurrentBuildLock is set to the currently * in-progress content release. If NO, we abort. - * - * @Flow\Scope("singleton") */ -class ConcurrentBuildLockService +#[Flow\Scope('singleton')] +final readonly class ConcurrentBuildLockService { private const CONTENT_STORE_CONCURRENT_BUILD_LOCK = 'contentStore:concurrentBuildLocks'; - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisContentReleaseService $redisContentReleaseService, + ) {} - public function ensureAllOtherInProgressContentReleasesWillBeTerminated(ContentReleaseIdentifier $contentReleaseIdentifier): void - { - $metadata = $this->redisContentReleaseService->fetchMetadataForContentRelease($contentReleaseIdentifier); + public function ensureAllOtherInProgressContentReleasesWillBeTerminated( + ContentReleaseIdentifier $contentReleaseIdentifier, + ): void { + $metadata = $this->fetchMetadata($contentReleaseIdentifier); $this->redisClientManager->getPrimaryRedis()->hSet( self::CONTENT_STORE_CONCURRENT_BUILD_LOCK, - $metadata->getWorkspaceName(), + $metadata->workspaceName, (string) $contentReleaseIdentifier, ); } public function assertNoOtherContentReleaseWasStarted(ContentReleaseIdentifier $contentReleaseIdentifier): void { - $metadata = $this->redisContentReleaseService->fetchMetadataForContentRelease($contentReleaseIdentifier); + $metadata = $this->fetchMetadata($contentReleaseIdentifier); $concurrentBuildLockStrings = $this->redisClientManager ->getPrimaryRedis() ->hGetAll(self::CONTENT_STORE_CONCURRENT_BUILD_LOCK); - $concurrentBuildLockStringForWorkspace = $concurrentBuildLockStrings[$metadata->getWorkspaceName()] ?? null; + $concurrentBuildLockStringForWorkspace = $concurrentBuildLockStrings[$metadata->workspaceName] ?? null; if (!$concurrentBuildLockStringForWorkspace) { echo '!!!!! Hard-aborting the current job ' . $contentReleaseIdentifier->getIdentifier() . ' because the concurrentBuildLock does not exist.' - . "\n\n" - ; + . "\n\n"; echo "This should never happen for correctly configured jobs (that run after prepare_finished).\n\n"; exit(1); } @@ -81,15 +75,25 @@ public function assertNoOtherContentReleaseWasStarted(ContentReleaseIdentifier $ '!!!!! Hard-aborting the current job ' . $contentReleaseIdentifier->getIdentifier() . ' because the concurrentBuildLock for workspace "' - . $metadata->getWorkspaceName() + . $metadata->workspaceName . '" contains ' . $concurrentBuildLock->getIdentifier() - . "\n\n" - ; + . "\n\n"; echo - "This is no error during deployment, but should never happen outside a deployment.\n\n It can only happen if two prunner instances run concurrently.\n\n" - ; + "This is no error during deployment, but should never happen outside a deployment.\n\n It can only happen if two prunner instances run concurrently.\n\n"; exit(1); } } + + private function fetchMetadata(ContentReleaseIdentifier $contentReleaseIdentifier): ContentReleaseMetadata + { + $metadata = $this->redisContentReleaseService->fetchMetadataForContentRelease($contentReleaseIdentifier); + if ($metadata === null) { + throw new RuntimeException(sprintf( + 'No metadata found for content release %s.', + $contentReleaseIdentifier->getIdentifier(), + )); + } + return $metadata; + } } diff --git a/Classes/Core/Domain/Dto/ContentReleaseBatchResult.php b/Classes/Core/Domain/Dto/ContentReleaseBatchResult.php index ff81269..979097c 100644 --- a/Classes/Core/Domain/Dto/ContentReleaseBatchResult.php +++ b/Classes/Core/Domain/Dto/ContentReleaseBatchResult.php @@ -7,15 +7,13 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class ContentReleaseBatchResult +#[Flow\Proxy(false)] +final readonly class ContentReleaseBatchResult { /** * @var array key is a content release identifier (stringified); value is a value (depending on which method was asked) */ - protected array $results; + private array $results; private function __construct(array $results) { @@ -27,7 +25,7 @@ public static function createFromArray(array $in): self return new self($in); } - public function getResultForContentRelease(ContentReleaseIdentifier $contentReleaseIdentifier) + public function getResultForContentRelease(ContentReleaseIdentifier $contentReleaseIdentifier): mixed { return $this->results[(string) $contentReleaseIdentifier] ?? null; } diff --git a/Classes/Core/Domain/ValueObject/AutomaticReleasePauseState.php b/Classes/Core/Domain/ValueObject/AutomaticReleasePauseState.php index e2c4216..9b09097 100644 --- a/Classes/Core/Domain/ValueObject/AutomaticReleasePauseState.php +++ b/Classes/Core/Domain/ValueObject/AutomaticReleasePauseState.php @@ -13,7 +13,7 @@ * State of the switch which suppresses automatically triggered content releases. */ #[Flow\Proxy(false)] -final class AutomaticReleasePauseState +final readonly class AutomaticReleasePauseState { private DateTimeImmutable $pausedAt; diff --git a/Classes/Core/Domain/ValueObject/ContentReleaseIdentifier.php b/Classes/Core/Domain/ValueObject/ContentReleaseIdentifier.php index 9d25880..4f0373b 100644 --- a/Classes/Core/Domain/ValueObject/ContentReleaseIdentifier.php +++ b/Classes/Core/Domain/ValueObject/ContentReleaseIdentifier.php @@ -5,12 +5,11 @@ namespace Flowpack\DecoupledContentStore\Core\Domain\ValueObject; use Flowpack\DecoupledContentStore\Exception; +use JsonSerializable; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class ContentReleaseIdentifier implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class ContentReleaseIdentifier implements JsonSerializable { private string $identifier; diff --git a/Classes/Core/Domain/ValueObject/PrunnerJobId.php b/Classes/Core/Domain/ValueObject/PrunnerJobId.php index 6f9797f..e4edd6b 100644 --- a/Classes/Core/Domain/ValueObject/PrunnerJobId.php +++ b/Classes/Core/Domain/ValueObject/PrunnerJobId.php @@ -5,17 +5,13 @@ namespace Flowpack\DecoupledContentStore\Core\Domain\ValueObject; use Flowpack\Prunner\ValueObject\JobId; +use JsonSerializable; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class PrunnerJobId implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class PrunnerJobId implements JsonSerializable { - /** - * @var string - */ - private $identifier; + private string $identifier; private function __construct(string $identifier) { diff --git a/Classes/Core/Domain/ValueObject/RedisInstanceIdentifier.php b/Classes/Core/Domain/ValueObject/RedisInstanceIdentifier.php index 92352bd..ae23f27 100644 --- a/Classes/Core/Domain/ValueObject/RedisInstanceIdentifier.php +++ b/Classes/Core/Domain/ValueObject/RedisInstanceIdentifier.php @@ -6,18 +6,13 @@ use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class RedisInstanceIdentifier +#[Flow\Proxy(false)] +final readonly class RedisInstanceIdentifier { // must match the default config in Settings.yaml private const PRIMARY = 'primary'; - /** - * @var string - */ - private $identifier; + private string $identifier; private function __construct(string $identifier) { diff --git a/Classes/Core/Infrastructure/ConsoleStatisticsEventOutput.php b/Classes/Core/Infrastructure/ConsoleStatisticsEventOutput.php index b081e4e..0ef3a64 100644 --- a/Classes/Core/Infrastructure/ConsoleStatisticsEventOutput.php +++ b/Classes/Core/Infrastructure/ConsoleStatisticsEventOutput.php @@ -8,9 +8,9 @@ use Neos\Flow\Cli\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; -class ConsoleStatisticsEventOutput implements StatisticsEventOutputInterface +final readonly class ConsoleStatisticsEventOutput implements StatisticsEventOutputInterface { - protected OutputInterface $output; + private OutputInterface $output; function __construct(OutputInterface $output) { diff --git a/Classes/Core/Infrastructure/ContentReleaseLogger.php b/Classes/Core/Infrastructure/ContentReleaseLogger.php index c903ffe..68a4d10 100644 --- a/Classes/Core/Infrastructure/ContentReleaseLogger.php +++ b/Classes/Core/Infrastructure/ContentReleaseLogger.php @@ -4,33 +4,25 @@ namespace Flowpack\DecoupledContentStore\Core\Infrastructure; +use Exception; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\NodeRendering\Dto\RendererIdentifier; +use Neos\Error\Messages\Result; use Neos\Flow\Cli\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; +use Throwable; -class ContentReleaseLogger +final class ContentReleaseLogger { - /** - * @var OutputInterface - */ - protected $output; - - /** - * @var StatisticsEventOutputInterface - */ - protected $statisticsEventOutput; + private readonly OutputInterface $output; - /** - * @var ContentReleaseIdentifier - */ - protected $contentReleaseIdentifier; + private readonly StatisticsEventOutputInterface $statisticsEventOutput; - protected string $logPrefix = ''; + private readonly ContentReleaseIdentifier $contentReleaseIdentifier; - protected ?RendererIdentifier $rendererIdentifier; + private readonly string $logPrefix; - protected function __construct( + private function __construct( OutputInterface $output, ContentReleaseIdentifier $contentReleaseIdentifier, StatisticsEventOutputInterface $statisticsEventOutput, @@ -39,12 +31,7 @@ protected function __construct( $this->output = $output; $this->contentReleaseIdentifier = $contentReleaseIdentifier; $this->statisticsEventOutput = $statisticsEventOutput; - $this->rendererIdentifier = $rendererIdentifier; - $this->logPrefix = ''; - - if ($this->rendererIdentifier !== null) { - $this->logPrefix = '[Renderer ' . $this->rendererIdentifier->string() . '] '; - } + $this->logPrefix = $rendererIdentifier !== null ? '[Renderer ' . $rendererIdentifier->string() . '] ' : ''; } public static function fromConsoleOutput( @@ -83,13 +70,13 @@ public function error(string $message, array $additionalPayload = []): void $this->logToOutput('ERROR', $message, $additionalPayload); } - protected function logToOutput(string $level, string $message, array $additionalPayload = []): void + private function logToOutput(string $level, string $message, array $additionalPayload = []): void { $formattedPayload = $additionalPayload ? ' ' . json_encode($additionalPayload) : ''; $this->output->writeln($this->timePrefix() . $this->logPrefix . $level . ': ' . $message . $formattedPayload); } - public function logException(\Exception $exception, string $message, array $additionalPayload) + public function logException(Exception $exception, string $message, array $additionalPayload): void { $this->output->writeln( $this->timePrefix() @@ -97,6 +84,7 @@ public function logException(\Exception $exception, string $message, array $addi . $message . "\n\n" . $exception->getMessage() + . $this->formatValidationErrors($exception) . "\n\n" . $exception->getTraceAsString() . "\n\n" @@ -104,16 +92,36 @@ public function logException(\Exception $exception, string $message, array $addi ); } + /** + * Some exceptions (e.g. Fusion PropType validation) keep their details in a validation Result + * instead of the message; without this the log only says that validation failed, not which property. + */ + private function formatValidationErrors(Throwable $exception): string + { + $lines = ''; + for ($current = $exception; $current !== null; $current = $current->getPrevious()) { + if (!method_exists($current, 'getResult') || !$current->getResult() instanceof Result) { + continue; + } + foreach ($current->getResult()->getFlattenedErrors() as $propertyPath => $errors) { + foreach ($errors as $error) { + $lines .= "\n " . $propertyPath . ': ' . $error->render(); + } + } + } + return $lines; + } + /** * Every log line carries the wall-clock time it was written, so that a pipeline task which looks * stuck in the UI can be told apart from one which is simply slow (compare the last line's time). */ - protected function timePrefix(): string + private function timePrefix(): string { return '[' . date('H:i:s') . '] '; } - public function logStatisticsEvent(string $event, array $additionalPayload = []) + public function logStatisticsEvent(string $event, array $additionalPayload = []): void { $this->statisticsEventOutput->writeEvent( $this->contentReleaseIdentifier, diff --git a/Classes/Core/Infrastructure/RedisClientManager.php b/Classes/Core/Infrastructure/RedisClientManager.php index bca642f..d7cbffe 100644 --- a/Classes/Core/Infrastructure/RedisClientManager.php +++ b/Classes/Core/Infrastructure/RedisClientManager.php @@ -4,33 +4,37 @@ namespace Flowpack\DecoupledContentStore\Core\Infrastructure; +use Exception as PhpException; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; use Flowpack\DecoupledContentStore\Exception; use Neos\Flow\Annotations as Flow; +use Redis; +use RedisException; +use RuntimeException; -/** - * @Flow\Scope("singleton") - */ -class RedisClientManager +#[Flow\Scope('singleton')] +final class RedisClientManager { /** - * @Flow\InjectConfiguration("redisContentStores") - * @var array + * @var array */ - protected $configuration; + private array $redisInstances = []; /** - * @var array<\Redis> + * @param array $configuration */ - protected array $redisInstances = []; + public function __construct( + #[Flow\InjectConfiguration('redisContentStores')] + protected readonly array $configuration, + ) {} /** * @throws Exception */ - protected function connect(RedisInstanceIdentifier $redisInstanceIdentifier): \Redis + private function connect(RedisInstanceIdentifier $redisInstanceIdentifier): Redis { $instanceConfig = $this->configuration[$redisInstanceIdentifier->getIdentifier()]; - $redis = new \Redis(); + $redis = new Redis(); try { $connected = $redis->connect( @@ -38,7 +42,7 @@ protected function connect(RedisInstanceIdentifier $redisInstanceIdentifier): \R (int) ($instanceConfig['port'] ?? 6379), $instanceConfig['timeout'] ?? 0, ) && $redis->select($instanceConfig['database'] ?? 0); - } catch (\Exception $exception) { + } catch (PhpException $exception) { throw new Exception( sprintf( 'Could not connect to Redis server %s:%d. Detailed reason: see nested exception.', @@ -66,9 +70,9 @@ protected function connect(RedisInstanceIdentifier $redisInstanceIdentifier): \R /** * Get the Redis instance and check for an existing connection * - * @return \Redis + * @return Redis */ - public function getRedis(RedisInstanceIdentifier $redisInstanceIdentifier): \Redis + public function getRedis(RedisInstanceIdentifier $redisInstanceIdentifier): Redis { if (!isset($this->redisInstances[$redisInstanceIdentifier->getIdentifier()])) { $this->redisInstances[$redisInstanceIdentifier->getIdentifier()] = $this->connect($redisInstanceIdentifier); @@ -81,7 +85,7 @@ public function getRedis(RedisInstanceIdentifier $redisInstanceIdentifier): \Red $this->redisInstances[$redisInstanceIdentifier->getIdentifier()] = $this->connect($redisInstanceIdentifier); } - } catch (\RedisException $e) { + } catch (RedisException $e) { $redis = $this->redisInstances[$redisInstanceIdentifier->getIdentifier()] = $this->connect($redisInstanceIdentifier); @@ -89,7 +93,7 @@ public function getRedis(RedisInstanceIdentifier $redisInstanceIdentifier): \Red return $redis; } - public function getPrimaryRedis(): \Redis + public function getPrimaryRedis(): Redis { return $this->getRedis(RedisInstanceIdentifier::primary()); } @@ -97,7 +101,7 @@ public function getPrimaryRedis(): \Redis public function getRetentionCount(RedisInstanceIdentifier $redisInstanceIdentifier): int { if (!isset($this->configuration[$redisInstanceIdentifier->getIdentifier()]['contentReleaseRetentionCount'])) { - throw new \RuntimeException( + throw new RuntimeException( 'Did not find a configured contentReleaseRetentionCount for Redis ' . $redisInstanceIdentifier->getIdentifier(), ); diff --git a/Classes/Core/Infrastructure/RedisContentReleaseSizeService.php b/Classes/Core/Infrastructure/RedisContentReleaseSizeService.php index 2479971..411a94e 100644 --- a/Classes/Core/Infrastructure/RedisContentReleaseSizeService.php +++ b/Classes/Core/Infrastructure/RedisContentReleaseSizeService.php @@ -12,18 +12,15 @@ * Calculates how much memory a content release occupies in Redis. * * NOTE: this is an expensive operation, as it needs one MEMORY USAGE call per Redis key of the release. - * For finished releases, use the pre-calculated size from ContentReleaseMetadata::getContentReleaseSize() + * For finished releases, use the pre-calculated size from ContentReleaseMetadata::$contentReleaseSize * instead - it is determined once by the NodeRenderOrchestrator when the release is finished. - * - * @Flow\Scope("singleton") */ -class RedisContentReleaseSizeService +#[Flow\Scope('singleton')] +final readonly class RedisContentReleaseSizeService { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; + public function __construct( + private RedisClientManager $redisClientManager, + ) {} /** * @return float size of the content release in megabytes diff --git a/Classes/Core/Infrastructure/RedisStatisticsEventOutput.php b/Classes/Core/Infrastructure/RedisStatisticsEventOutput.php index 8c5d2c1..15c9b2e 100644 --- a/Classes/Core/Infrastructure/RedisStatisticsEventOutput.php +++ b/Classes/Core/Infrastructure/RedisStatisticsEventOutput.php @@ -7,7 +7,7 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Neos\Flow\Annotations as Flow; -class RedisStatisticsEventOutput implements StatisticsEventOutputInterface +final class RedisStatisticsEventOutput implements StatisticsEventOutputInterface { #[Flow\Inject] protected RedisStatisticsEventService $redisStatisticsEventService; diff --git a/Classes/Core/Infrastructure/RedisStatisticsEventService.php b/Classes/Core/Infrastructure/RedisStatisticsEventService.php index b01527a..df4dfc6 100644 --- a/Classes/Core/Infrastructure/RedisStatisticsEventService.php +++ b/Classes/Core/Infrastructure/RedisStatisticsEventService.php @@ -7,16 +7,16 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\RedisKeyService; use Flowpack\DecoupledContentStore\Exception; +use JsonException; use Neos\Flow\Annotations as Flow; #[Flow\Scope('singleton')] -class RedisStatisticsEventService +final readonly class RedisStatisticsEventService { - #[Flow\Inject] - protected RedisClientManager $redisClientManager; - - #[Flow\Inject] - protected RedisKeyService $redisKeyService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + ) {} public function addEvent( ContentReleaseIdentifier $contentReleaseIdentifier, @@ -40,13 +40,10 @@ public function addEvent( * @param string[] $groupBy * @return array<> * @throws Exception - * @throws \JsonException + * @throws JsonException */ - public function countEvents( - ContentReleaseIdentifier $contentReleaseIdentifier, - array $where, - array $groupBy, - ): array { + public function countEvents(ContentReleaseIdentifier $contentReleaseIdentifier, array $where, array $groupBy): array + { $redis = $this->redisClientManager->getPrimaryRedis(); $key = $this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'statisticsEvents'); $chunkSize = 1000; diff --git a/Classes/Core/RedisKeyService.php b/Classes/Core/RedisKeyService.php index 44b704e..1111f0d 100644 --- a/Classes/Core/RedisKeyService.php +++ b/Classes/Core/RedisKeyService.php @@ -9,16 +9,16 @@ use Flowpack\DecoupledContentStore\Transfer\Dto\RedisKeyPostfixesForEachRelease; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RedisKeyService +#[Flow\Scope('singleton')] +final readonly class RedisKeyService { /** - * @Flow\InjectConfiguration("redisKeyPostfixesForEachRelease") - * @var array + * @param array $redisKeyPostfixesForEachReleaseConfiguration */ - protected $redisKeyPostfixesForEachReleaseConfiguration; + public function __construct( + #[Flow\InjectConfiguration('redisKeyPostfixesForEachRelease')] + protected array $redisKeyPostfixesForEachReleaseConfiguration, + ) {} public function getRedisKeyForPostfix(ContentReleaseIdentifier $contentReleaseIdentifier, string $postfix): string { diff --git a/Classes/Core/RedisPruneService.php b/Classes/Core/RedisPruneService.php index 0108606..cd39e4e 100644 --- a/Classes/Core/RedisPruneService.php +++ b/Classes/Core/RedisPruneService.php @@ -8,10 +8,8 @@ use Flowpack\DecoupledContentStore\Core\Infrastructure\RedisClientManager; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RedisPruneService +#[Flow\Scope('singleton')] +final readonly class RedisPruneService { // go through all keys in the selected content store // check whether they are reserved keys or currently active or contain one of the currently registered releases ids @@ -44,13 +42,11 @@ class RedisPruneService end '; - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; + public function __construct( + private RedisClientManager $redisClientManager, + ) {} - public function pruneRedisInstance(RedisInstanceIdentifier $redisInstanceIdentifier) + public function pruneRedisInstance(RedisInstanceIdentifier $redisInstanceIdentifier): void { $this->redisClientManager->getRedis($redisInstanceIdentifier)->eval(self::PRUNE_LUA_SCRIPT, []); } diff --git a/Classes/Eel/ModuleHelper.php b/Classes/Eel/ModuleHelper.php index 6a8fee9..516d0e7 100644 --- a/Classes/Eel/ModuleHelper.php +++ b/Classes/Eel/ModuleHelper.php @@ -8,10 +8,8 @@ use Neos\Eel\ProtectedContextAwareInterface; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class ModuleHelper implements ProtectedContextAwareInterface +#[Flow\Scope('singleton')] +final readonly class ModuleHelper implements ProtectedContextAwareInterface { /** * Sort task results by name using a natural order, so that numeric render workers appear as diff --git a/Classes/Exception.php b/Classes/Exception.php index a8ab4b4..058fb10 100644 --- a/Classes/Exception.php +++ b/Classes/Exception.php @@ -4,4 +4,6 @@ namespace Flowpack\DecoupledContentStore; -class Exception extends \Neos\Flow\Exception {} +use Neos\Flow\Exception as FlowException; + +class Exception extends FlowException {} diff --git a/Classes/Exception/InvalidReleaseException.php b/Classes/Exception/InvalidReleaseException.php index 2ff6478..2ad85df 100644 --- a/Classes/Exception/InvalidReleaseException.php +++ b/Classes/Exception/InvalidReleaseException.php @@ -6,4 +6,4 @@ use Flowpack\DecoupledContentStore\Exception; -class InvalidReleaseException extends Exception {} +final class InvalidReleaseException extends Exception {} diff --git a/Classes/Exception/InvalidSiteConfigurationException.php b/Classes/Exception/InvalidSiteConfigurationException.php index 9c070fe..0c75f85 100644 --- a/Classes/Exception/InvalidSiteConfigurationException.php +++ b/Classes/Exception/InvalidSiteConfigurationException.php @@ -6,4 +6,4 @@ use Flowpack\DecoupledContentStore\Exception; -class InvalidSiteConfigurationException extends Exception {} +final class InvalidSiteConfigurationException extends Exception {} diff --git a/Classes/Exception/InvalidTransferConfigException.php b/Classes/Exception/InvalidTransferConfigException.php index 6e08e2e..5a8ba3c 100644 --- a/Classes/Exception/InvalidTransferConfigException.php +++ b/Classes/Exception/InvalidTransferConfigException.php @@ -6,4 +6,4 @@ use Flowpack\DecoupledContentStore\Exception; -class InvalidTransferConfigException extends Exception {} +final class InvalidTransferConfigException extends Exception {} diff --git a/Classes/Exception/NodeNotFoundException.php b/Classes/Exception/NodeNotFoundException.php index 90f390c..b2629a1 100644 --- a/Classes/Exception/NodeNotFoundException.php +++ b/Classes/Exception/NodeNotFoundException.php @@ -6,4 +6,4 @@ use Flowpack\DecoupledContentStore\Exception; -class NodeNotFoundException extends Exception {} +final class NodeNotFoundException extends Exception {} diff --git a/Classes/Exception/QuickContentReleaseNotPossibleException.php b/Classes/Exception/QuickContentReleaseNotPossibleException.php index 4de30e7..03f1bfc 100644 --- a/Classes/Exception/QuickContentReleaseNotPossibleException.php +++ b/Classes/Exception/QuickContentReleaseNotPossibleException.php @@ -9,4 +9,4 @@ /** * The message of this exception is written for an editor: it is shown as-is when a quick release cannot be scheduled. */ -class QuickContentReleaseNotPossibleException extends Exception {} +final class QuickContentReleaseNotPossibleException extends Exception {} diff --git a/Classes/Exception/RenderingException.php b/Classes/Exception/RenderingException.php index a6f2536..a697136 100644 --- a/Classes/Exception/RenderingException.php +++ b/Classes/Exception/RenderingException.php @@ -5,32 +5,16 @@ namespace Flowpack\DecoupledContentStore\Exception; use Exception; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Flowpack\DecoupledContentStore\Exception as DecoupledContentStoreException; -class RenderingException extends \Flowpack\DecoupledContentStore\Exception +final class RenderingException extends DecoupledContentStoreException { - private string $nodeUri; - - /** - * @param string $message - * @param NodeInterface $node - * @param string $nodeUri - * @param int $code - * @param Exception $previous - */ public function __construct( string $message, - NodeInterface $node, - $nodeUri, + public readonly string $nodeUri, int $code = 0, ?Exception $previous = null, ) { - $this->nodeUri = $nodeUri; parent::__construct($message, $code, $previous); } - - public function getNodeUri(): string - { - return $this->nodeUri; - } } diff --git a/Classes/Fusion/ExceptionHandlers/PublishingAwareContextDependentHandler.php b/Classes/Fusion/ExceptionHandlers/PublishingAwareContextDependentHandler.php index ef43d34..d153b7c 100644 --- a/Classes/Fusion/ExceptionHandlers/PublishingAwareContextDependentHandler.php +++ b/Classes/Fusion/ExceptionHandlers/PublishingAwareContextDependentHandler.php @@ -4,21 +4,21 @@ namespace Flowpack\DecoupledContentStore\Fusion\ExceptionHandlers; +use Exception; use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer; use Neos\Flow\Annotations as Flow; +use Neos\Fusion\Core\ExceptionHandlers\ContextDependentHandler; -class PublishingAwareContextDependentHandler extends \Neos\Fusion\Core\ExceptionHandlers\ContextDependentHandler +final class PublishingAwareContextDependentHandler extends ContextDependentHandler { - /** - * @Flow\Inject - * @var DocumentRenderer - */ - protected $documentRenderer; + #[Flow\Inject] + protected DocumentRenderer $documentRenderer; /** * {@inheritdoc} + * @throws Exception */ - protected function handle($fusionPath, \Exception $exception, $referenceCode) + protected function handle($fusionPath, Exception $exception, $referenceCode): string { if ($this->documentRenderer->isRendering()) { throw $exception; diff --git a/Classes/Fusion/ExceptionHandlers/PublishingAwareNodeWrappingHandler.php b/Classes/Fusion/ExceptionHandlers/PublishingAwareNodeWrappingHandler.php index 0ec40c5..d118092 100644 --- a/Classes/Fusion/ExceptionHandlers/PublishingAwareNodeWrappingHandler.php +++ b/Classes/Fusion/ExceptionHandlers/PublishingAwareNodeWrappingHandler.php @@ -4,21 +4,21 @@ namespace Flowpack\DecoupledContentStore\Fusion\ExceptionHandlers; +use Exception; use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer; use Neos\Flow\Annotations as Flow; +use Neos\Neos\Fusion\ExceptionHandlers\NodeWrappingHandler; -class PublishingAwareNodeWrappingHandler extends \Neos\Neos\Fusion\ExceptionHandlers\NodeWrappingHandler +final class PublishingAwareNodeWrappingHandler extends NodeWrappingHandler { - /** - * @Flow\Inject - * @var DocumentRenderer - */ - protected $documentRenderer; + #[Flow\Inject] + protected DocumentRenderer $documentRenderer; /** * {@inheritdoc} + * @throws Exception */ - protected function handle($fusionPath, \Exception $exception, $referenceCode) + protected function handle($fusionPath, Exception $exception, $referenceCode): string { if ($this->documentRenderer->isRendering()) { throw $exception; diff --git a/Classes/Fusion/ExceptionHandlers/PublishingAwarePageHandler.php b/Classes/Fusion/ExceptionHandlers/PublishingAwarePageHandler.php index f54acb0..c048ffb 100644 --- a/Classes/Fusion/ExceptionHandlers/PublishingAwarePageHandler.php +++ b/Classes/Fusion/ExceptionHandlers/PublishingAwarePageHandler.php @@ -4,21 +4,20 @@ namespace Flowpack\DecoupledContentStore\Fusion\ExceptionHandlers; +use Exception; use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer; use Neos\Flow\Annotations as Flow; +use Neos\Neos\Fusion\ExceptionHandlers\PageHandler; -class PublishingAwarePageHandler extends \Neos\Neos\Fusion\ExceptionHandlers\PageHandler +final class PublishingAwarePageHandler extends PageHandler { - /** - * @Flow\Inject - * @var DocumentRenderer - */ - protected $documentRenderer; + #[Flow\Inject] + protected DocumentRenderer $documentRenderer; /** * {@inheritdoc} */ - protected function handle($fusionPath, \Exception $exception, $referenceCode) + protected function handle($fusionPath, Exception $exception, $referenceCode): string { if ($this->documentRenderer->isRendering()) { throw $exception; diff --git a/Classes/Fusion/ImageUriImplementation.php b/Classes/Fusion/ImageUriImplementation.php deleted file mode 100644 index 11c0268..0000000 --- a/Classes/Fusion/ImageUriImplementation.php +++ /dev/null @@ -1,36 +0,0 @@ -getAsset(); - - if ($asset) { - $this->runtime->addCacheTag('asset', $this->persistenceManager->getIdentifierByObject($asset)); - } - - return $result; - } -} diff --git a/Classes/IncrementalContentReleaseCatchUpHook.php b/Classes/IncrementalContentReleaseCatchUpHook.php new file mode 100644 index 0000000..91bfa34 --- /dev/null +++ b/Classes/IncrementalContentReleaseCatchUpHook.php @@ -0,0 +1,45 @@ +isBooting = $subscriptionStatus === SubscriptionStatus::BOOTING; + } + + public function onBeforeEvent(EventInterface $eventInstance, EventEnvelope $eventEnvelope): void {} + + public function onAfterEvent(EventInterface $eventInstance, EventEnvelope $eventEnvelope): void + { + if ( + !$this->isBooting + && $eventInstance instanceof WorkspaceWasPublished + && $eventInstance->targetWorkspaceName->isLive() + ) { + $this->incrementalContentReleaseHandler->nodePublished(); + } + } + + public function onAfterBatchCompleted(): void {} + + public function onAfterCatchUp(): void {} +} diff --git a/Classes/IncrementalContentReleaseCatchUpHookFactory.php b/Classes/IncrementalContentReleaseCatchUpHookFactory.php new file mode 100644 index 0000000..5cabc5d --- /dev/null +++ b/Classes/IncrementalContentReleaseCatchUpHookFactory.php @@ -0,0 +1,25 @@ + + */ +final readonly class IncrementalContentReleaseCatchUpHookFactory implements CatchUpHookFactoryInterface +{ + public function __construct( + private IncrementalContentReleaseHandler $incrementalContentReleaseHandler, + ) {} + + public function build(CatchUpHookFactoryDependencies $dependencies): CatchUpHookInterface + { + return new IncrementalContentReleaseCatchUpHook($this->incrementalContentReleaseHandler); + } +} diff --git a/Classes/IncrementalContentReleaseHandler.php b/Classes/IncrementalContentReleaseHandler.php index 387440e..94a55f6 100644 --- a/Classes/IncrementalContentReleaseHandler.php +++ b/Classes/IncrementalContentReleaseHandler.php @@ -6,30 +6,23 @@ use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class IncrementalContentReleaseHandler +#[Flow\Scope('singleton')] +final class IncrementalContentReleaseHandler { - /** - * @Flow\Inject - * @var ContentReleaseManager - */ - protected $contentReleaseManager; + private bool $nodePublishedInThisRequest = false; - /** - * @Flow\InjectConfiguration("startIncrementalReleaseOnWorkspacePublish") - */ - protected $startIncrementalReleaseOnWorkspacePublish; + public function __construct( + private readonly ContentReleaseManager $contentReleaseManager, + #[Flow\InjectConfiguration('startIncrementalReleaseOnWorkspacePublish')] + protected readonly bool $startIncrementalReleaseOnWorkspacePublish, + ) {} - protected $nodePublishedInThisRequest = false; - - public function nodePublished() + public function nodePublished(): void { $this->nodePublishedInThisRequest = true; } - public function startContentReleaseIfNodesWerePublishedBefore() + public function startContentReleaseIfNodesWerePublishedBefore(): void { if ($this->startIncrementalReleaseOnWorkspacePublish === true && $this->nodePublishedInThisRequest === true) { $this->contentReleaseManager->startIncrementalContentRelease(); diff --git a/Classes/Metrics/ContentReleaseMetricsService.php b/Classes/Metrics/ContentReleaseMetricsService.php index af5135d..e9fc42a 100644 --- a/Classes/Metrics/ContentReleaseMetricsService.php +++ b/Classes/Metrics/ContentReleaseMetricsService.php @@ -26,25 +26,16 @@ * which keeps them longer than Redis keeps the release. */ #[Flow\Scope('singleton')] -class ContentReleaseMetricsService +final readonly class ContentReleaseMetricsService { - #[Flow\Inject] - protected RedisContentReleaseService $redisContentReleaseService; - - #[Flow\Inject] - protected RedisEnumerationRepository $redisEnumerationRepository; - - #[Flow\Inject] - protected RedisRenderingTimeStatisticsStore $redisRenderingStatisticsStore; - - #[Flow\Inject] - protected RedisRenderingErrorManager $redisRenderingErrorManager; - - #[Flow\Inject] - protected WorkerErrorLogAggregator $workerErrorLogAggregator; - - #[Flow\Inject] - protected PrunnerApiService $prunnerApiService; + public function __construct( + private RedisContentReleaseService $redisContentReleaseService, + private RedisEnumerationRepository $redisEnumerationRepository, + private RedisRenderingTimeStatisticsStore $redisRenderingStatisticsStore, + private RedisRenderingErrorManager $redisRenderingErrorManager, + private WorkerErrorLogAggregator $workerErrorLogAggregator, + private PrunnerApiService $prunnerApiService, + ) {} /** * Returns NULL when the release has no metadata - it was never created, or it has already been pruned. @@ -94,7 +85,7 @@ public function collectMetrics( private function collectWorkerErrorLogs(ContentReleaseMetadata $metadata): ?array { try { - $job = $this->prunnerApiService->loadJobDetail($metadata->getPrunnerJobId()->toJobId()); + $job = $this->prunnerApiService->loadJobDetail($metadata->prunnerJobId->toJobId()); if ($job === null) { return null; } diff --git a/Classes/Metrics/Dto/ContentReleaseMetrics.php b/Classes/Metrics/Dto/ContentReleaseMetrics.php index aa8f905..281c8b8 100644 --- a/Classes/Metrics/Dto/ContentReleaseMetrics.php +++ b/Classes/Metrics/Dto/ContentReleaseMetrics.php @@ -19,7 +19,7 @@ * before anybody gets to look at it. This DTO is what survives that. */ #[Flow\Proxy(false)] -final class ContentReleaseMetrics implements JsonSerializable +final readonly class ContentReleaseMetrics implements JsonSerializable { /** * Errors are shipped inline, so a release with thousands of failing documents must not produce a log line @@ -39,23 +39,23 @@ final class ContentReleaseMetrics implements JsonSerializable * @param WorkerError[]|null $workerErrors NULL when the worker logs could not be read */ private function __construct( - public readonly string $contentReleaseIdentifier, - public readonly string $prunnerJobId, - public readonly string $status, - public readonly ?string $workspaceName, - public readonly ?string $accountId, - public readonly ?string $startTime, - public readonly ?string $endTime, - public readonly ?int $durationSeconds, - public readonly ?float $sizeMegabytes, - public readonly int $documentCount, - public readonly int $newlyRenderedDocumentCount, - public readonly int $renderingCount, - public readonly int $iterationCount, - public readonly array $iterations, - public readonly int $renderingErrorCount, - public readonly array $renderingErrors, - public readonly ?array $workerErrors, + public string $contentReleaseIdentifier, + public string $prunnerJobId, + public string $status, + public ?string $workspaceName, + public ?string $accountId, + public ?string $startTime, + public ?string $endTime, + public ?int $durationSeconds, + public ?float $sizeMegabytes, + public int $documentCount, + public int $newlyRenderedDocumentCount, + public int $renderingCount, + public int $iterationCount, + public array $iterations, + public int $renderingErrorCount, + public array $renderingErrors, + public ?array $workerErrors, ) {} /** @@ -81,10 +81,10 @@ public static function create( $renderingCount += $iteration->completedRenderings; } - $startTime = $metadata->getStartTime(); + $startTime = $metadata->startTime; // The end time is written when the rendering finished, so the duration covers enumeration and rendering - // not the transfer and switch tasks which run after them. - $endTime = $metadata->getEndTime(); + $endTime = $metadata->endTime; // A release which was aborted never gets an end time written, so its duration is measured up to the // moment this report is taken - which is the moment the pipeline gave up on it. $durationEnd = $endTime ?? $now; @@ -104,14 +104,14 @@ public static function create( return new self( $contentReleaseIdentifier->getIdentifier(), - $metadata->getPrunnerJobId()->getIdentifier(), - $metadata->getStatus()->getStatus(), - $metadata->getWorkspaceName(), - $metadata->getAccountId(), + $metadata->prunnerJobId->getIdentifier(), + $metadata->status->getStatus(), + $metadata->workspaceName, + $metadata->accountId, $startTime?->format(DateTimeInterface::RFC3339_EXTENDED), $endTime?->format(DateTimeInterface::RFC3339_EXTENDED), $startTime !== null ? $durationEnd->getTimestamp() - $startTime->getTimestamp() : null, - $metadata->getContentReleaseSize(), + $metadata->contentReleaseSize, $documentCount, // The first iteration copies everything which is still complete in the content cache and schedules // the rest - so its scheduled count is the number of documents this release rendered anew. diff --git a/Classes/Metrics/Dto/RenderingError.php b/Classes/Metrics/Dto/RenderingError.php index bbabd12..ea9fe89 100644 --- a/Classes/Metrics/Dto/RenderingError.php +++ b/Classes/Metrics/Dto/RenderingError.php @@ -4,21 +4,21 @@ namespace Flowpack\DecoupledContentStore\Metrics\Dto; -use JsonSerializable; use Flowpack\DecoupledContentStore\Metrics\NodeIdentifierExtractor; +use JsonSerializable; use Neos\Flow\Annotations as Flow; /** * One rendering error of a content release, split into the parts an external log aggregator can filter on. */ #[Flow\Proxy(false)] -final class RenderingError implements JsonSerializable +final readonly class RenderingError implements JsonSerializable { private function __construct( - public readonly string $message, - public readonly ?string $node, - public readonly ?string $nodeIdentifier, - public readonly ?string $nodeUri, + public string $message, + public ?string $node, + public ?string $nodeIdentifier, + public ?string $nodeUri, ) {} /** diff --git a/Classes/Metrics/Dto/RenderingIteration.php b/Classes/Metrics/Dto/RenderingIteration.php index a5241ae..8ab23a4 100644 --- a/Classes/Metrics/Dto/RenderingIteration.php +++ b/Classes/Metrics/Dto/RenderingIteration.php @@ -22,11 +22,7 @@ private function __construct( public static function fromRenderingStatistics(int $iteration, RenderingStatistics $renderingStatistics): self { - return new self( - $iteration, - $renderingStatistics->getTotalJobs(), - $renderingStatistics->getRenderedJobs(), - ); + return new self($iteration, $renderingStatistics->getTotalJobs(), $renderingStatistics->getRenderedJobs()); } /** diff --git a/Classes/Metrics/Dto/WorkerError.php b/Classes/Metrics/Dto/WorkerError.php index 22809ff..92012ed 100644 --- a/Classes/Metrics/Dto/WorkerError.php +++ b/Classes/Metrics/Dto/WorkerError.php @@ -6,6 +6,7 @@ use Flowpack\DecoupledContentStore\BackendUi\Dto\WorkerErrorLog; use Flowpack\DecoupledContentStore\Metrics\NodeIdentifierExtractor; +use JsonSerializable; use Neos\Flow\Annotations as Flow; /** @@ -13,10 +14,9 @@ * * Those log files live on the container's disk and fall out of the pipeline's `retention_count` quickly, so the * stacktrace is copied into the measurement of the release while it is still readable. - * - * @Flow\Proxy(false) */ -final class WorkerError implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class WorkerError implements JsonSerializable { /** * Stacktraces are long, and a release which broke usually broke in more than one worker. These caps keep one @@ -29,16 +29,15 @@ final class WorkerError implements \JsonSerializable * @param string[] $errorBlocks */ private function __construct( - public readonly string $workerName, - public readonly string $status, - public readonly int $exitCode, - public readonly bool $wasKilledByOrchestrator, - public readonly ?string $taskError, - public readonly ?string $lastAttemptedNode, - public readonly ?string $lastAttemptedNodeIdentifier, - public readonly array $errorBlocks, - ) { - } + public string $workerName, + public string $status, + public int $exitCode, + public bool $wasKilledByOrchestrator, + public ?string $taskError, + public ?string $lastAttemptedNode, + public ?string $lastAttemptedNodeIdentifier, + public array $errorBlocks, + ) {} public static function fromWorkerErrorLog(WorkerErrorLog $workerErrorLog): self { diff --git a/Classes/Metrics/NodeIdentifierExtractor.php b/Classes/Metrics/NodeIdentifierExtractor.php index 521738f..87339aa 100644 --- a/Classes/Metrics/NodeIdentifierExtractor.php +++ b/Classes/Metrics/NodeIdentifierExtractor.php @@ -13,9 +13,9 @@ * A node identifier is a UUID, and it is the only UUID in any of those strings. */ #[Flow\Proxy(false)] -final class NodeIdentifierExtractor +final readonly class NodeIdentifierExtractor { - private const NODE_IDENTIFIER_PATTERN = '/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i'; + private const string NODE_IDENTIFIER_PATTERN = '/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i'; public static function fromText(?string $text): ?string { diff --git a/Classes/NodeEnumeration/Domain/Dto/EnumeratedNode.php b/Classes/NodeEnumeration/Domain/Dto/EnumeratedNode.php index 52c723a..7e6ba58 100644 --- a/Classes/NodeEnumeration/Domain/Dto/EnumeratedNode.php +++ b/Classes/NodeEnumeration/Domain/Dto/EnumeratedNode.php @@ -4,49 +4,37 @@ namespace Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto; -use Neos\ContentRepository\Domain\Model\NodeInterface; -use Neos\ContentRepository\Domain\Utility\NodePaths; +use Exception; +use JsonSerializable; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class EnumeratedNode implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class EnumeratedNode implements JsonSerializable { /** * We extract the to-be-rendered dimensions and the current site from the context path. Other than that, * it is used NOT for rendering. * * You are NOT ALLOWED to rely on this stored context path as a whole during rendering, because it might have changed because of a move. - * - * @var string */ - protected $contextPath; + private string $contextPath; /** * We identify the node by its identifier - * - * @var string */ - protected $nodeIdentifier; + private string $nodeIdentifier; - /** - * @var array - */ - protected $arguments; + private array $arguments; - /** - * The node type name - * - * @var string - */ - protected $nodeTypeName; + private string $nodeTypeName; /** * The renderer implementation to use for this EnumeratedNode; * a key from Settings at Flowpack.DecoupledContentStore.extensions.documentRenderers.[key] */ - public readonly string $rendererId; + public string $rendererId; private function __construct( string $contextPath, @@ -62,22 +50,25 @@ private function __construct( $this->rendererId = $rendererId; } - public static function fromNode(NodeInterface $node, array $arguments = []): self + public static function fromNode(Node $node, array $arguments = []): self { return new self( - $node->getContextPath(), - $node->getIdentifier(), - $node->getNodeType()->getName(), + NodeAddress::fromNode($node)->toJson(), + $node->aggregateId->value, + $node->nodeTypeName->value, $arguments, '', ); } + /** + * @throws Exception + */ public static function fromJsonString(string $enumeratedNodeString): self { $tmp = json_decode($enumeratedNodeString, true); if (!is_array($tmp)) { - throw new \Exception('EnumeratedNode cannot be constructed from: ' . $enumeratedNodeString); + throw new Exception('EnumeratedNode cannot be constructed from: ' . $enumeratedNodeString); } return new self( $tmp['contextPath'], @@ -99,28 +90,22 @@ public function jsonSerialize(): array ]; } - public function getSiteNodeNameFromContextPath(): string + public function getNodeAddress(): NodeAddress { - if (preg_match('#^/sites/([^/@]*)#', $this->contextPath, $matches)) { - return $matches[1]; - } else { - throw new \Exception( - 'Could not get site node name from context path "' . $this->contextPath . '"', - 1495535171, - ); - } + return NodeAddress::fromJsonString($this->contextPath); } + /** + * @return array + */ public function getDimensionsFromContextPath(): array { - $nodePathAndContext = NodePaths::explodeContextPath($this->contextPath); - return $nodePathAndContext['dimensions']; + return NodeAddress::fromJsonString($this->contextPath)->dimensionSpacePoint->coordinates; } public function getWorkspaceNameFromContextPath(): string { - $nodePathAndContext = NodePaths::explodeContextPath($this->contextPath); - return $nodePathAndContext['workspaceName']; + return NodeAddress::fromJsonString($this->contextPath)->workspaceName->value; } public function getNodeIdentifier(): string diff --git a/Classes/NodeEnumeration/Domain/Repository/RedisEnumerationRepository.php b/Classes/NodeEnumeration/Domain/Repository/RedisEnumerationRepository.php index 8ea0c3a..b7f9e6f 100644 --- a/Classes/NodeEnumeration/Domain/Repository/RedisEnumerationRepository.php +++ b/Classes/NodeEnumeration/Domain/Repository/RedisEnumerationRepository.php @@ -13,24 +13,15 @@ use Flowpack\DecoupledContentStore\Utility\GeneratorUtility; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RedisEnumerationRepository +#[Flow\Scope('singleton')] +final readonly class RedisEnumerationRepository { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + ) {} - public function clearDocumentNodesEnumeration(ContentReleaseIdentifier $releaseIdentifier) + public function clearDocumentNodesEnumeration(ContentReleaseIdentifier $releaseIdentifier): void { $this->redisClientManager->getPrimaryRedis()->del($this->redisKeyService->getRedisKeyForPostfix( $releaseIdentifier, @@ -41,7 +32,7 @@ public function clearDocumentNodesEnumeration(ContentReleaseIdentifier $releaseI public function addDocumentNodesToEnumeration( ContentReleaseIdentifier $releaseIdentifier, EnumeratedNode ...$enumeration, - ) { + ): void { $convertedEnumeration = array_map(function (EnumeratedNode $node) { return json_encode($node); }, $enumeration); diff --git a/Classes/NodeEnumeration/Domain/Service/DocumentNodeFilter.php b/Classes/NodeEnumeration/Domain/Service/DocumentNodeFilter.php index 927636e..7b50abb 100644 --- a/Classes/NodeEnumeration/Domain/Service/DocumentNodeFilter.php +++ b/Classes/NodeEnumeration/Domain/Service/DocumentNodeFilter.php @@ -4,10 +4,10 @@ namespace Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Service; -use Neos\ContentRepository\Domain\Model\NodeInterface; -use Neos\ContentRepository\Domain\Projection\Content\TraversableNodeInterface; -use Neos\ContentRepository\Exception\NodeException; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry; use Neos\Flow\Annotations as Flow; +use Neos\Neos\Domain\SubtreeTagging\NeosSubtreeTag; /** * Decides which document nodes end up in a content release. @@ -17,7 +17,7 @@ * a filter string and as a check for a single node. */ #[Flow\Scope('singleton')] -final class DocumentNodeFilter +final readonly class DocumentNodeFilter { /** * Used when "nodeRendering.nodeTypeWhitelist" configures no node type to include. @@ -25,13 +25,15 @@ final class DocumentNodeFilter private const DEFAULT_NODE_TYPE = 'Neos.Neos:Document'; /** - * @var array + * @param array $nodeTypeWhitelist */ - #[Flow\InjectConfiguration('nodeRendering.nodeTypeWhitelist')] - protected array $nodeTypeWhitelist; - - #[Flow\InjectConfiguration('nodeRendering.recurseHiddenContent')] - protected bool $recurseHiddenContent; + public function __construct( + private ContentRepositoryRegistry $contentRepositoryRegistry, + #[Flow\InjectConfiguration('nodeRendering.nodeTypeWhitelist')] + protected array $nodeTypeWhitelist, + #[Flow\InjectConfiguration('nodeRendering.recurseHiddenContent')] + protected bool $recurseHiddenContent, + ) {} /** * Builds a FlowQuery filter string from the node type whitelist, @@ -57,9 +59,13 @@ public function flowQueryNodeTypeFilter(): string * Concatenated FlowQuery filter parts are ANDed, so a node has to be of every included node type - not of any * of them. */ - public function matchesNodeTypeWhitelist(NodeInterface $node): bool + public function matchesNodeTypeWhitelist(Node $node): bool { - $nodeType = $node->getNodeType(); + $contentRepository = $this->contentRepositoryRegistry->get($node->contentRepositoryId); + $nodeType = $contentRepository->getNodeTypeManager()->getNodeType($node->nodeTypeName); + if ($nodeType === null) { + return false; + } $partitionedNodeTypes = self::partitionNodeTypeWhitelist($this->nodeTypeWhitelist); foreach ($partitionedNodeTypes['excludes'] as $excludedNodeType) { @@ -84,16 +90,11 @@ public function matchesNodeTypeWhitelist(NodeInterface $node): bool * passing it through the FlowQuery filter, and both enumerators would change behaviour if that were tightened * as a side effect. Callers which resolve nodes by identifier check {@see matchesNodeTypeWhitelist()} themselves. */ - public function skipReason(NodeInterface $node, NodeInterface $siteNode): ?string + public function skipReason(Node $node): ?string { - // the site node has no parent inside the site, so it can never be orphaned - if ($node !== $siteNode && self::isOrphaned($node, $siteNode)) { - return 'orphaned'; - } - - // isVisible() rather than isHidden(), so that a page hidden by "hiddenBeforeDateTime" or - // "hiddenAfterDateTime" counts as hidden as well - it is hidden to a visitor just the same - if (!$node->isVisible()) { + // only the node's own tag: an inherited one means a page above it is hidden, which the full enumeration + // decides by its traversal and {@see skipReasonForNamedNode()} by "recurseHiddenContent" + if ($node->tags->withoutInherited()->contain(NeosSubtreeTag::disabled())) { return 'hidden'; } @@ -107,79 +108,36 @@ public function skipReason(NodeInterface $node, NodeInterface $siteNode): ?strin * which was named by hand did not come out of the FlowQuery filter and was not reached by descending from the * site node, so nothing else checked either of them. */ - public function skipReasonForNamedNode(NodeInterface $node, NodeInterface $siteNode): ?string + public function skipReasonForNamedNode(Node $node): ?string { - $skipReason = $this->skipReason($node, $siteNode); - if ($skipReason !== null) { - return $skipReason; - } - - // "recurseHiddenContent" is what the full enumeration descends into hidden pages with, so where it is set a - // document below one is part of an ordinary release and has to be part of a quick release just the same - if (!$this->recurseHiddenContent && self::hasHiddenAncestor($node)) { - return 'below a hidden page'; - } - - return $this->matchesNodeTypeWhitelist($node) ? null : 'not of a node type which is published'; + return ( + $this->visibilitySkipReasonForNamedNode($node) + ?? ($this->matchesNodeTypeWhitelist($node) ? null : 'not of a node type which is published') + ); } /** - * Whether one of the pages above the node is hidden, by its flag or by its hidden-before/after dates. + * Everything {@see skipReasonForNamedNode()} answers apart from the node type, which needs the content repository. * - * Only asked about a node named by identifier, which is resolved in a context that shows hidden nodes so that - * "it is hidden" can be reported instead of "it does not exist". The full enumeration needs no such check: it - * descends from the site node in a context built from "recurseHiddenContent", and therefore never reaches a - * document below a hidden page unless that setting says it should - publishing one from a quick release would - * put a page live which the next full release removes again. The walk goes past the site node, because a hidden - * site node keeps its whole site out of a full release just as well. + * A node named by identifier is resolved in a subgraph that shows disabled nodes, so that "it is hidden" can be + * reported instead of "it does not exist". The full enumeration needs no check for the pages above: it descends + * from the site node in a subgraph built from "recurseHiddenContent", and therefore never reaches a document + * below a hidden page unless that setting says it should - publishing one from a quick release would put a page + * live which the next full release removes again. Inherited tags include the site node's, because a hidden site + * node keeps its whole site out of a full release just as well. */ - private static function hasHiddenAncestor(NodeInterface $node): bool + private function visibilitySkipReasonForNamedNode(Node $node): ?string { - $parentNode = self::getParentNodeOrNull($node); - while ($parentNode !== null) { - if (!$parentNode->isVisible()) { - return true; - } - $parentNode = self::getParentNodeOrNull($parentNode); - } - - return false; - } - - private static function isOrphaned(NodeInterface $node, NodeInterface $siteNode): bool - { - $parentNode = self::getParentNodeOrNull($node); - while ($parentNode !== $siteNode) { - if ($parentNode === null) { - return true; - } - $parentNode = self::getParentNodeOrNull($parentNode); - } - - return false; - } - - /** - * The parent of a node, or NULL where the walk up leaves the tree. - * - * Walking up needs findParentNode(), which belongs to TraversableNodeInterface - a different interface from the - * NodeInterface the rest of this class works with, implemented side by side by the content repository's node - * class. Both conversions live here so that callers compare nodes of one type, and so that "left the tree" - * stays a NULL rather than an exception. - */ - private static function getParentNodeOrNull(NodeInterface $node): ?NodeInterface - { - if (!$node instanceof TraversableNodeInterface) { - return null; + $skipReason = $this->skipReason($node); + if ($skipReason !== null) { + return $skipReason; } - try { - $parentNode = $node->findParentNode(); - } catch (NodeException) { - return null; + if (!$this->recurseHiddenContent && $node->tags->onlyInherited()->contain(NeosSubtreeTag::disabled())) { + return 'below a hidden page'; } - return $parentNode instanceof NodeInterface ? $parentNode : null; + return null; } /** diff --git a/Classes/NodeEnumeration/Domain/Service/NodeContextCombinator.php b/Classes/NodeEnumeration/Domain/Service/NodeContextCombinator.php index 567d429..f22b807 100644 --- a/Classes/NodeEnumeration/Domain/Service/NodeContextCombinator.php +++ b/Classes/NodeEnumeration/Domain/Service/NodeContextCombinator.php @@ -4,126 +4,61 @@ namespace Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Service; -use Flowpack\DecoupledContentStore\Exception\NodeNotFoundException; use Generator; -use Neos\ContentRepository\Domain\Model\NodeInterface; -use Neos\ContentRepository\Domain\Projection\Content\TraversableNodeInterface; -use Neos\ContentRepository\Domain\Service\ContentDimensionCombinator; -use Neos\ContentRepository\Domain\Service\ContextFactoryInterface; +use Neos\ContentRepository\Core\Feature\Security\Exception\AccessDenied; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\ContentRepository\ContentRepositoryId; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAggregateId; +use Neos\ContentRepository\Core\SharedModel\Workspace\WorkspaceName; +use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry; use Neos\Flow\Annotations as Flow; use Neos\Neos\Domain\Model\Site; use Neos\Neos\Domain\Repository\SiteRepository; +use Neos\Neos\Domain\Service\NodeTypeNameFactory; +use Neos\Neos\Domain\SubtreeTagging\NeosVisibilityConstraints; -class NodeContextCombinator +final class NodeContextCombinator { - /** - * @Flow\Inject - * @var ContentDimensionCombinator - */ - protected $contentDimensionCombinator; + #[Flow\Inject] + protected SiteRepository $siteRepository; - /** - * @Flow\Inject - * @var SiteRepository - */ - protected $siteRepository; + #[Flow\InjectConfiguration('nodeRendering.recurseHiddenContent')] + protected bool $recurseHiddenContent; - /** - * @Flow\Inject - * @var ContextFactoryInterface - */ - protected $contextFactory; + #[Flow\Inject] + protected ContentRepositoryRegistry $contentRepositoryRegistry; /** - * @Flow\InjectConfiguration(path="nodeRendering.recurseHiddenContent", package="Flowpack.DecoupledContentStore") - * @var ContextFactoryInterface - */ - protected $recurseHiddenContent; - - /** - * Iterate over the node with the given identifier and site in contexts for all available presets (if it exists as a variant) + * Iterate over the node with the given identifier in every dimension it exists in. * - * @return Generator - * @throws NodeNotFoundException + * An identifier which is no valid node aggregate id yields nothing. + * + * @return Generator + * @throws AccessDenied */ - public function nodeInContexts(string $nodeIdentifier, Site $site, string $workspaceName = 'live'): Generator + public function nodeVariants(string $nodeIdentifier, string $workspaceName = 'live'): Generator { - $nodeFound = false; - - /** @var NodeInterface $siteNode */ - foreach ($this->siteNodeInContexts($site, $workspaceName) as $siteNode) { - $node = $siteNode->getContext()->getNodeByIdentifier($nodeIdentifier); - - if ($node instanceof NodeInterface) { - $nodeFound = true; - yield $node; - } + $nodeAggregateId = NodeAggregateId::tryFromString($nodeIdentifier); + if ($nodeAggregateId === null) { + return; } - if (!$nodeFound) { - throw new NodeNotFoundException( - 'Could not find node by identifier ' . $nodeIdentifier . ' in any context', - 1467285561, - ); - } - } - - /** - * Iterate over the node with the given identifier in every dimension it exists in, together with the site node - * it belongs to. - * - * Unlike {@see nodeInContexts()} this searches every site and hands out the site node as well, which callers - * need for the orphan check. It also does not report "not found" per site: a node is part of one site, so all - * the others not having it is the normal case rather than an error. - * - * @return Generator the site node and the node, in that order - */ - public function nodeVariantsWithSiteNode(string $nodeIdentifier, string $workspaceName = 'live'): Generator - { - foreach ($this->sites() as $site) { - // a flag rather than a plain return after the inner loop: a site which does not contain the node - // yields nothing and has to fall through to the next site, and returning from inside the inner loop - // would cut off the node's remaining dimension variants - $nodeFound = false; + $contentRepository = $this->contentRepositoryRegistry->get(ContentRepositoryId::fromString('default')); + $contentGraph = $contentRepository->getContentGraph(WorkspaceName::fromString($workspaceName)); + foreach ($contentRepository->getVariationGraph()->getDimensionSpacePoints() as $dimensionSpacePoint) { // hidden nodes are shown here regardless of "recurseHiddenContent": somebody named this node by its - // identifier, and "it is hidden" is the answer they need - a context which filters it away could only + // identifier, and "it is hidden" is the answer they need - a subgraph which filters it away could only // report that it does not exist - foreach ($this->siteNodeInContexts($site, $workspaceName, true) as $siteNode) { - $node = $siteNode->getContext()->getNodeByIdentifier($nodeIdentifier); - // getNodeByIdentifier() looks the node up in the whole content repository rather than inside the - // site, so it answers for every site alike and the node has to be matched against the site itself - if ($node instanceof NodeInterface && self::isWithinSiteNode($node, $siteNode)) { - $nodeFound = true; - yield [$siteNode, $node]; - } - } + $subgraph = $contentGraph->getSubgraph($dimensionSpacePoint, NeosVisibilityConstraints::excludeRemoved()); - if ($nodeFound) { - // a node belongs to exactly one site, so the remaining ones cannot contribute further variants - return; + $node = $subgraph->findNodeById($nodeAggregateId); + if ($node !== null) { + yield $node; } } } - /** - * Whether the node is the site node itself or lives below it. - * - * Compared by path rather than by walking up the parents: the walk gives the same answer, while this runs for - * every site the node is looked up in. Nodes without a path cannot be placed in a site and count as outside it. - */ - private static function isWithinSiteNode(NodeInterface $node, NodeInterface $siteNode): bool - { - if (!$node instanceof TraversableNodeInterface || !$siteNode instanceof TraversableNodeInterface) { - return false; - } - - $nodePath = $node->findNodePath(); - $siteNodePath = $siteNode->findNodePath(); - - return $nodePath->equals($siteNodePath) || str_starts_with((string) $nodePath, $siteNodePath . '/'); - } - /** * Iterate over all sites * @@ -139,46 +74,32 @@ public function sites(): Generator } /** - * Iterate over the site node in all available presets (if it exists) + * Iterate over the site node in all dimension space points (if it exists), hiding disabled nodes unless + * "nodeRendering.recurseHiddenContent" is set * - * @param bool|null $invisibleContentShown NULL follows the "nodeRendering.recurseHiddenContent" setting - * @return Generator + * @return Generator + * @throws AccessDenied */ - public function siteNodeInContexts( - Site $site, - string $workspaceName = 'live', - ?bool $invisibleContentShown = null, - ): Generator { - $allowedContextCombinations = $this->contentDimensionCombinator->getAllAllowedCombinations(); - - foreach ($allowedContextCombinations as $dimensionContextCombination) { - $contentContext = $this->contextFactory->create(array( - 'currentSite' => $site, - 'workspaceName' => $workspaceName, - 'dimensions' => $dimensionContextCombination, - 'targetDimensions' => [], - 'invisibleContentShown' => $invisibleContentShown ?? $this->recurseHiddenContent, - )); - - $siteNode = $contentContext->getNode('/sites/' . $site->getNodeName()); - - if ($siteNode instanceof NodeInterface) { - yield $siteNode; - } - } - } - - /** - * Iterate over the given node and all document child nodes recursively - * - * @return Generator - */ - public function recurseDocumentChildNodes(NodeInterface $node): Generator + public function siteNodeInContexts(Site $site, string $workspaceName = 'live'): Generator { - yield $node; + $contentRepository = $this->contentRepositoryRegistry->get($site->getConfiguration()->contentRepositoryId); + $contentGraph = $contentRepository->getContentGraph(WorkspaceName::fromString($workspaceName)); + $visibilityConstraints = $this->recurseHiddenContent + ? NeosVisibilityConstraints::excludeRemoved() + : NeosVisibilityConstraints::excludeRemoved()->merge(NeosVisibilityConstraints::excludeDisabled()); + + foreach ($contentRepository->getVariationGraph()->getDimensionSpacePoints() as $dimensionSpacePoint) { + $subgraph = $contentGraph->getSubgraph($dimensionSpacePoint, $visibilityConstraints); + + $sitesNode = $subgraph->findRootNodeByType(NodeTypeNameFactory::forSites()); + if ($sitesNode === null) { + continue; + } - foreach ($node->getChildNodes('Neos.Neos:Document') as $childNode) { - yield from $this->recurseDocumentChildNodes($childNode); + $siteNode = $subgraph->findNodeByPath($site->getNodeName()->toNodeName(), $sitesNode->aggregateId); + if ($siteNode !== null) { + yield $siteNode; + } } } } diff --git a/Classes/NodeEnumeration/NodeEnumerator.php b/Classes/NodeEnumeration/NodeEnumerator.php index ea5a0e0..1deaf70 100644 --- a/Classes/NodeEnumeration/NodeEnumerator.php +++ b/Classes/NodeEnumeration/NodeEnumerator.php @@ -16,40 +16,22 @@ use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\NodeRenderingExtensionManager; use Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure\RedisContentReleaseService; use Flowpack\DecoupledContentStore\Utility\GeneratorUtility; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; use Neos\Eel\Exception; use Neos\Eel\FlowQuery\FlowQuery; use Neos\Flow\Annotations as Flow; use Neos\Neos\Domain\Model\Site; -class NodeEnumerator +final class NodeEnumerator { - #[Flow\Inject] - protected DocumentNodeFilter $documentNodeFilter; - - /** - * @Flow\Inject - * @var RedisEnumerationRepository - */ - protected $redisEnumerationRepository; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; - - /** - * @Flow\Inject - * @var ConcurrentBuildLockService - */ - protected $concurrentBuildLockService; - - /** - * @Flow\Inject - * @var NodeRenderingExtensionManager - */ - protected $nodeRenderingExtensionManager; + public function __construct( + private readonly RedisEnumerationRepository $redisEnumerationRepository, + private readonly RedisContentReleaseService $redisContentReleaseService, + private readonly ConcurrentBuildLockService $concurrentBuildLockService, + private readonly NodeRenderingExtensionManager $nodeRenderingExtensionManager, + private readonly DocumentNodeFilter $documentNodeFilter, + ) {} public function enumerateAndStoreInRedis( ?Site $site, @@ -71,7 +53,7 @@ public function enumerateAndStoreInRedis( $this->redisEnumerationRepository->clearDocumentNodesEnumeration($releaseIdentifier); foreach (GeneratorUtility::createArrayBatch( - $this->enumerateAll($site, $contentReleaseLogger, $newMetadata->getWorkspaceName()), + $this->enumerateAll($site, $contentReleaseLogger, $newMetadata->workspaceName), 100, ) as $enumeration) { $this->concurrentBuildLockService->assertNoOtherContentReleaseWasStarted($releaseIdentifier); @@ -126,20 +108,20 @@ private function enumerateAll( foreach ($combinator->siteNodeInContexts($site, $workspaceName) as $siteNode) { $startTime = microtime(true); - $dimensionValues = $siteNode->getContext()->getDimensions(); + $dimensionValues = $siteNode->dimensionSpacePoint->coordinates; $contentReleaseLogger->debug('Publishing dimension combination', [ 'dimensionValues' => $dimensionValues, ]); $nodeQuery = new FlowQuery([$siteNode]); - /** @var NodeInterface[] $matchingNodes */ + /** @var Node[] $matchingNodes */ $matchingNodes = $nodeQuery->find($nodeTypeFilter)->add($siteNode)->get(); foreach ($matchingNodes as $nodeToEnumerate) { - $contextPath = $nodeToEnumerate->getContextPath(); + $contextPath = NodeAddress::fromNode($nodeToEnumerate)->toJson(); - $skipReason = $this->documentNodeFilter->skipReason($nodeToEnumerate, $siteNode); + $skipReason = $this->documentNodeFilter->skipReason($nodeToEnumerate); if ($skipReason !== null) { $contentReleaseLogger->debug('Skipping node from publishing, because it is ' . $skipReason, [ 'node' => $contextPath, @@ -185,11 +167,11 @@ private function enumerateAll( * @param ContentReleaseIdentifier $releaseIdentifier * @param ContentReleaseLogger $contentReleaseLogger * @return void - * @Flow\Signal */ + #[Flow\Signal] protected function emitNodeEnumerated( EnumeratedNode $enumeratedNode, ContentReleaseIdentifier $releaseIdentifier, ContentReleaseLogger $contentReleaseLogger, - ) {} + ): void {} } diff --git a/Classes/NodeRendering/Dto/DocumentNodeCacheKey.php b/Classes/NodeRendering/Dto/DocumentNodeCacheKey.php index d32f723..665dab4 100644 --- a/Classes/NodeRendering/Dto/DocumentNodeCacheKey.php +++ b/Classes/NodeRendering/Dto/DocumentNodeCacheKey.php @@ -5,64 +5,41 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Dto; use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto\EnumeratedNode; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; use Neos\Flow\Annotations as Flow; /** * Represents the top-level Fusion Cache identifier for a rendered node - * - * @Flow\Proxy(false) */ -final class DocumentNodeCacheKey +#[Flow\Proxy(false)] +final readonly class DocumentNodeCacheKey { - /** - * @var string - */ - protected $nodeIdentifier; + private array $arguments; - /** - * @var array - */ - protected $dimensions; + private array $dimensions; - /** - * @var string - */ - protected $workspaceName; - - /** - * @var array - */ - protected $arguments; - - private function __construct(string $nodeIdentifier, array $dimensions, string $workspaceName, array $arguments) - { + private function __construct( + private string $nodeIdentifier, + array $dimensions, + array $arguments, + ) { // we need to make this deterministic ksort($arguments); ksort($dimensions); - - $this->nodeIdentifier = $nodeIdentifier; $this->dimensions = $dimensions; - $this->workspaceName = $workspaceName; $this->arguments = $arguments; } - public static function fromNodeAndArguments(NodeInterface $node, array $arguments): self + public static function fromNodeAndArguments(Node $node, array $arguments): self { - return new self( - $node->getIdentifier(), - $node->getContext()->getDimensions(), - $node->getWorkspace()->getName(), - $arguments, - ); + return new self($node->aggregateId->value, $node->dimensionSpacePoint->coordinates, $arguments); } - public static function fromEnumeratedNode(EnumeratedNode $enumeratedNode) + public static function fromEnumeratedNode(EnumeratedNode $enumeratedNode): self { return new self( $enumeratedNode->getNodeIdentifier(), $enumeratedNode->getDimensionsFromContextPath(), - $enumeratedNode->getWorkspaceNameFromContextPath(), $enumeratedNode->getArguments(), ); } diff --git a/Classes/NodeRendering/Dto/DocumentNodeCacheValues.php b/Classes/NodeRendering/Dto/DocumentNodeCacheValues.php index 3a8a333..a8b1bfc 100644 --- a/Classes/NodeRendering/Dto/DocumentNodeCacheValues.php +++ b/Classes/NodeRendering/Dto/DocumentNodeCacheValues.php @@ -5,32 +5,26 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Dto; use Exception; +use JsonSerializable; use Neos\Flow\Annotations as Flow; /** * Represents contents of the top-level Fusion Cache identifier for a rendered node - * - * @Flow\Proxy(false) */ -final class DocumentNodeCacheValues implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class DocumentNodeCacheValues implements JsonSerializable { /** * the root cache identifier which contains the actual content (possibly nested) - * @var string */ - protected $rootIdentifier; + private string $rootIdentifier; /** * the currently rendered URL - * - * @var string */ - protected $url; + private string $url; - /** - * @var array - */ - protected $metadata; + private array $metadata; private function __construct(string $rootIdentifier, string $url, array $metadata) { @@ -52,7 +46,7 @@ public static function create(string $rootIdentifier, string $url): self /** * @throws Exception */ - public static function fromJsonString($jsonString): self + public static function fromJsonString(string $jsonString): self { $tmp = json_decode($jsonString, true); if (!is_array($tmp)) { @@ -84,7 +78,7 @@ public function jsonSerialize(): array /** * Add additional metadata. */ - public function withMetadata(string $key, $value): self + public function withMetadata(string $key, mixed $value): self { $metadata = $this->metadata; $metadata[$key] = $value; diff --git a/Classes/NodeRendering/Dto/NodeRenderingCompletionStatus.php b/Classes/NodeRendering/Dto/NodeRenderingCompletionStatus.php index 9b23b93..f3473d9 100644 --- a/Classes/NodeRendering/Dto/NodeRenderingCompletionStatus.php +++ b/Classes/NodeRendering/Dto/NodeRenderingCompletionStatus.php @@ -4,27 +4,24 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Dto; +use InvalidArgumentException; +use JsonSerializable; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class NodeRenderingCompletionStatus implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class NodeRenderingCompletionStatus implements JsonSerializable { private const SCHEDULED = 'scheduled'; private const RUNNING = 'running'; private const SUCCESS = 'success'; private const FAILED = 'failed'; - /** - * @var string - */ - private $status; + private string $status; private function __construct(string $status) { if (!in_array($status, [self::SCHEDULED, self::RUNNING, self::SUCCESS, self::FAILED])) { - throw new \InvalidArgumentException('NodeRenderingCompletionStatus "' . $status . '" not found.'); + throw new InvalidArgumentException('NodeRenderingCompletionStatus "' . $status . '" not found.'); } $this->status = $status; } @@ -54,7 +51,7 @@ public static function failed(): self return new self(self::FAILED); } - public static function fromJsonString($jsonString): self + public static function fromJsonString(string $jsonString): self { return new self(json_decode($jsonString, true)); } diff --git a/Classes/NodeRendering/Dto/RenderedDocumentFromContentCache.php b/Classes/NodeRendering/Dto/RenderedDocumentFromContentCache.php index b20b8c7..170dd45 100644 --- a/Classes/NodeRendering/Dto/RenderedDocumentFromContentCache.php +++ b/Classes/NodeRendering/Dto/RenderedDocumentFromContentCache.php @@ -4,32 +4,19 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Dto; +use JsonException; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class RenderedDocumentFromContentCache +#[Flow\Proxy(false)] +final readonly class RenderedDocumentFromContentCache { - /** - * @var string - */ - protected $fullContent; + private string $fullContent; - /** - * @var DocumentNodeCacheValues - */ - protected $documentNodeCacheValues; + private DocumentNodeCacheValues $documentNodeCacheValues; - /** - * @var bool - */ - protected $isComplete; + private bool $isComplete; - /** - * @var string - */ - protected $incompleteReason; + private string $incompleteReason; private function __construct( string $fullContent, @@ -81,7 +68,7 @@ public function getMetadata(): array } /** - * @throws \JsonException + * @throws JsonException */ public function getLegacyMetadataString(): string { diff --git a/Classes/NodeRendering/Dto/RendererIdentifier.php b/Classes/NodeRendering/Dto/RendererIdentifier.php index 6fe46a9..ebab030 100644 --- a/Classes/NodeRendering/Dto/RendererIdentifier.php +++ b/Classes/NodeRendering/Dto/RendererIdentifier.php @@ -6,15 +6,10 @@ use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class RendererIdentifier +#[Flow\Proxy(false)] +final readonly class RendererIdentifier { - /** - * @var string - */ - private $identifier; + private string $identifier; private function __construct(string $identifier) { diff --git a/Classes/NodeRendering/Dto/RenderingStatistics.php b/Classes/NodeRendering/Dto/RenderingStatistics.php index f3f850d..b386572 100644 --- a/Classes/NodeRendering/Dto/RenderingStatistics.php +++ b/Classes/NodeRendering/Dto/RenderingStatistics.php @@ -4,33 +4,21 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Dto; +use Exception; use Flowpack\DecoupledContentStore\Utility\Sparkline; +use JsonSerializable; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class RenderingStatistics implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class RenderingStatistics implements JsonSerializable { - /** - * @var int - */ - protected $remainingJobs; + private int $remainingJobs; - /** - * @var int - */ - protected $totalJobs; + private int $totalJobs; - /** - * @var array - */ - protected $renderingsPerSecond; + private array $renderingsPerSecond; - /** - * @var string - */ - protected $svgSparkline; + private string $svgSparkline; /** * @param int $remainingJobs @@ -49,14 +37,14 @@ public static function create(int $remainingJobs, int $totalJobs, array $renderi return new self($remainingJobs, $totalJobs, $renderingsPerSecond); } - public static function fromJsonString($jsonString): self + public static function fromJsonString(mixed $jsonString): self { if (!is_string($jsonString)) { return new self(-1, -1, []); } $tmp = json_decode($jsonString, true); if (!is_array($tmp)) { - throw new \Exception('DocumentNodeCacheValues cannot be constructed from: ' . $jsonString); + throw new Exception('DocumentNodeCacheValues cannot be constructed from: ' . $jsonString); } return new self($tmp['remainingJobs'], $tmp['totalJobs'], $tmp['renderingsPerSecond']); } diff --git a/Classes/NodeRendering/Extensibility/ContentReleaseWriters/GzipWriter.php b/Classes/NodeRendering/Extensibility/ContentReleaseWriters/GzipWriter.php index adf9ffc..46d18aa 100644 --- a/Classes/NodeRendering/Extensibility/ContentReleaseWriters/GzipWriter.php +++ b/Classes/NodeRendering/Extensibility/ContentReleaseWriters/GzipWriter.php @@ -17,19 +17,13 @@ * * This is extensible to control the format of the content releases, and to add additional metadata. */ -class GzipWriter implements ContentReleaseWriterInterface +final class GzipWriter implements ContentReleaseWriterInterface { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; + #[Flow\Inject] + protected RedisClientManager $redisClientManager; - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; + #[Flow\Inject] + protected RedisKeyService $redisKeyService; public function processRenderedDocument( ContentReleaseIdentifier $contentReleaseIdentifier, diff --git a/Classes/NodeRendering/Extensibility/ContentReleaseWriters/LegacyWriter.php b/Classes/NodeRendering/Extensibility/ContentReleaseWriters/LegacyWriter.php index 3d034f2..4c31014 100644 --- a/Classes/NodeRendering/Extensibility/ContentReleaseWriters/LegacyWriter.php +++ b/Classes/NodeRendering/Extensibility/ContentReleaseWriters/LegacyWriter.php @@ -11,6 +11,7 @@ use Flowpack\DecoupledContentStore\NodeRendering\Dto\RenderedDocumentFromContentCache; use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\ContentReleaseWriterInterface; use Neos\Flow\Annotations as Flow; +use Neos\Fusion\Core\Cache\ContentCache; use Ramsey\Uuid\Uuid; /** @@ -18,25 +19,16 @@ * * This is extensible to control the format of the content releases, and to add additional metadata. */ -class LegacyWriter implements ContentReleaseWriterInterface +final class LegacyWriter implements ContentReleaseWriterInterface { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; + #[Flow\Inject] + protected RedisClientManager $redisClientManager; - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; + #[Flow\Inject] + protected RedisKeyService $redisKeyService; - /** - * @Flow\Inject - * @var \Neos\Fusion\Core\Cache\ContentCache - */ - protected $contentCache; + #[Flow\Inject] + protected ContentCache $contentCache; public function processRenderedDocument( ContentReleaseIdentifier $contentReleaseIdentifier, diff --git a/Classes/NodeRendering/Extensibility/DocumentEnumeratorInterface.php b/Classes/NodeRendering/Extensibility/DocumentEnumeratorInterface.php index 246763a..614f4b0 100644 --- a/Classes/NodeRendering/Extensibility/DocumentEnumeratorInterface.php +++ b/Classes/NodeRendering/Extensibility/DocumentEnumeratorInterface.php @@ -5,7 +5,7 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Extensibility; use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto\EnumeratedNode; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; /** * Adjust document enumeration. @@ -22,10 +22,13 @@ */ interface DocumentEnumeratorInterface { + /** + * @param array $options + */ public function __construct(array $options = []); /** * @return iterable */ - public function enumerateDocumentNode(NodeInterface $documentNode): iterable; + public function enumerateDocumentNode(Node $documentNode): iterable; } diff --git a/Classes/NodeRendering/Extensibility/DocumentEnumerators/DefaultEnumerator.php b/Classes/NodeRendering/Extensibility/DocumentEnumerators/DefaultEnumerator.php index 843f461..7ae38ad 100644 --- a/Classes/NodeRendering/Extensibility/DocumentEnumerators/DefaultEnumerator.php +++ b/Classes/NodeRendering/Extensibility/DocumentEnumerators/DefaultEnumerator.php @@ -6,13 +6,13 @@ use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto\EnumeratedNode; use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\DocumentEnumeratorInterface; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; -class DefaultEnumerator implements DocumentEnumeratorInterface +final readonly class DefaultEnumerator implements DocumentEnumeratorInterface { public function __construct(array $options = []) {} - public function enumerateDocumentNode(NodeInterface $documentNode): iterable + public function enumerateDocumentNode(Node $documentNode): iterable { return [ EnumeratedNode::fromNode($documentNode), diff --git a/Classes/NodeRendering/Extensibility/DocumentEnumerators/LimitEnumerator.php b/Classes/NodeRendering/Extensibility/DocumentEnumerators/LimitEnumerator.php index 4f67b52..2bcb950 100644 --- a/Classes/NodeRendering/Extensibility/DocumentEnumerators/LimitEnumerator.php +++ b/Classes/NodeRendering/Extensibility/DocumentEnumerators/LimitEnumerator.php @@ -6,28 +6,32 @@ use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto\EnumeratedNode; use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\DocumentEnumeratorInterface; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry; +use Neos\Flow\Annotations as Flow; /** * An enumerator which only renders the first N pages. very useful for interactive testing. * NOT useful for production. */ -class LimitEnumerator implements DocumentEnumeratorInterface +final class LimitEnumerator implements DocumentEnumeratorInterface { - protected int $i = 0; - private ?int $limit = null; - private ?string $uriPathSegmentFilter = null; - private ?string $nodePathSegmentFilter = null; - - public function __construct( - array $options = [], - ) { + #[Flow\Inject] + protected ContentRepositoryRegistry $contentRepositoryRegistry; + + private int $i = 0; + private readonly ?int $limit; + private readonly ?string $uriPathSegmentFilter; + private readonly ?string $nodePathSegmentFilter; + + public function __construct(array $options = []) + { $this->limit = $options['limit'] ?? null; $this->uriPathSegmentFilter = $options['uriPathSegmentFilter'] ?? null; $this->nodePathSegmentFilter = $options['nodePathSegmentFilter'] ?? null; } - public function enumerateDocumentNode(NodeInterface $documentNode): iterable + public function enumerateDocumentNode(Node $documentNode): iterable { if ( $this->uriPathSegmentFilter !== null @@ -35,10 +39,14 @@ public function enumerateDocumentNode(NodeInterface $documentNode): iterable ) { return []; } + $subgraph = $this->contentRepositoryRegistry->subgraphForNode($documentNode); if ( $this->nodePathSegmentFilter !== null - && str_contains($documentNode->getPath(), $this->nodePathSegmentFilter) === false + && str_contains( + $subgraph->retrieveNodePath($documentNode->aggregateId)->serializeToString(), + $this->nodePathSegmentFilter, + ) === false ) { return []; } diff --git a/Classes/NodeRendering/Extensibility/DocumentMetadataGeneratorInterface.php b/Classes/NodeRendering/Extensibility/DocumentMetadataGeneratorInterface.php index 9101054..5869f0e 100644 --- a/Classes/NodeRendering/Extensibility/DocumentMetadataGeneratorInterface.php +++ b/Classes/NodeRendering/Extensibility/DocumentMetadataGeneratorInterface.php @@ -5,8 +5,8 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Extensibility; use Flowpack\DecoupledContentStore\NodeRendering\Dto\DocumentNodeCacheValues; -use Neos\ContentRepository\Domain\Model\NodeInterface; -use Neos\Flow\Mvc\Controller\ControllerContext; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\Flow\Mvc\ActionRequest; /** * Hook to deeply integrate into the rendering process; at the point where every enumerated document is rendered. @@ -20,9 +20,9 @@ interface DocumentMetadataGeneratorInterface * usually you call return $cacheValues->withMetadata('key', $value) inside this method. Be sure to return the modified cache values passed in. */ public function generateMetadata( - NodeInterface $node, + Node $node, array $arguments, - ControllerContext $controllerContext, + ActionRequest $actionRequest, DocumentNodeCacheValues $cacheValues, ): DocumentNodeCacheValues; } diff --git a/Classes/NodeRendering/Extensibility/DocumentRendererInterface.php b/Classes/NodeRendering/Extensibility/DocumentRendererInterface.php index ef62710..b1944f7 100644 --- a/Classes/NodeRendering/Extensibility/DocumentRendererInterface.php +++ b/Classes/NodeRendering/Extensibility/DocumentRendererInterface.php @@ -9,7 +9,7 @@ use Flowpack\DecoupledContentStore\NodeRendering\Dto\RenderedDocumentFromContentCache; use Flowpack\DecoupledContentStore\NodeRendering\NodeRenderer; use Flowpack\DecoupledContentStore\NodeRendering\NodeRenderOrchestrator; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; /** * Decide how to render a document node. Used throughout {@see NodeRenderOrchestrator} and {@see NodeRenderer} @@ -20,10 +20,12 @@ */ interface DocumentRendererInterface { - public function tryToExtractRenderingForEnumeratedNodeFromContentCache(EnumeratedNode $enumeratedNode): RenderedDocumentFromContentCache; + public function tryToExtractRenderingForEnumeratedNodeFromContentCache( + EnumeratedNode $enumeratedNode, + ): RenderedDocumentFromContentCache; public function renderDocumentNodeVariant( - NodeInterface $node, + Node $node, EnumeratedNode $enumeratedNode, ContentReleaseLogger $contentReleaseLogger, ): void; diff --git a/Classes/NodeRendering/Extensibility/DocumentRenderers/FusionHtmlRenderer.php b/Classes/NodeRendering/Extensibility/DocumentRenderers/FusionHtmlRenderer.php index ccf2227..3a95f60 100644 --- a/Classes/NodeRendering/Extensibility/DocumentRenderers/FusionHtmlRenderer.php +++ b/Classes/NodeRendering/Extensibility/DocumentRenderers/FusionHtmlRenderer.php @@ -11,32 +11,27 @@ use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\DocumentRendererInterface; use Flowpack\DecoupledContentStore\NodeRendering\Infrastructure\RedisContentCacheReader; use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; use Neos\Flow\Annotations as Flow; -class FusionHtmlRenderer implements DocumentRendererInterface +final class FusionHtmlRenderer implements DocumentRendererInterface { - /** - * @Flow\Inject - * @var RedisContentCacheReader - */ - protected $redisContentCacheReader; + #[Flow\Inject] + protected RedisContentCacheReader $redisContentCacheReader; - /** - * @Flow\Inject - * @var DocumentRenderer - */ - protected $documentRenderer; + #[Flow\Inject] + protected DocumentRenderer $documentRenderer; - public function tryToExtractRenderingForEnumeratedNodeFromContentCache(EnumeratedNode $enumeratedNode): RenderedDocumentFromContentCache - { + public function tryToExtractRenderingForEnumeratedNodeFromContentCache( + EnumeratedNode $enumeratedNode, + ): RenderedDocumentFromContentCache { return $this->redisContentCacheReader->tryToExtractRenderingForEnumeratedNodeFromContentCache(DocumentNodeCacheKey::fromEnumeratedNode( $enumeratedNode, )); } public function renderDocumentNodeVariant( - NodeInterface $node, + Node $node, EnumeratedNode $enumeratedNode, ContentReleaseLogger $contentReleaseLogger, ): void { diff --git a/Classes/NodeRendering/Extensibility/NodeRenderingExtensionManager.php b/Classes/NodeRendering/Extensibility/NodeRenderingExtensionManager.php index aa7c28f..caec510 100644 --- a/Classes/NodeRendering/Extensibility/NodeRenderingExtensionManager.php +++ b/Classes/NodeRendering/Extensibility/NodeRenderingExtensionManager.php @@ -9,58 +9,58 @@ use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto\EnumeratedNode; use Flowpack\DecoupledContentStore\NodeRendering\Dto\DocumentNodeCacheValues; use Flowpack\DecoupledContentStore\NodeRendering\Dto\RenderedDocumentFromContentCache; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; use Neos\Flow\Annotations as Flow; -use Neos\Flow\Mvc\Controller\ControllerContext; +use Neos\Flow\Mvc\ActionRequest; +use Neos\Flow\ObjectManagement\ObjectManagerInterface; +use RuntimeException; -/** - * @Flow\Scope("singleton") - */ -class NodeRenderingExtensionManager +#[Flow\Scope('singleton')] +final class NodeRenderingExtensionManager { - /** - * @Flow\InjectConfiguration("extensions.documentRenderers") - * @var array - */ - protected $configuredDocumentRenderers; - /** * cache of the instantiated objects which are configured at {@see configuredDocumentRenderers}.enumeratorClassName * @var DocumentEnumeratorInterface[] */ - protected $documentEnumerators; + private array $documentEnumerators; /** * cache of the instantiated objects which are configured at {@see configuredDocumentRenderers}.rendererClassName * @var DocumentRendererInterface[] */ - protected $documentRenderers; + private array $documentRenderers; /** * cache of the instantiated objects which are configured at {@see configuredDocumentRenderers}.contentReleaseWriters * @var ContentReleaseWriterInterface[][] */ - protected $contentReleaseWriters; + private array $contentReleaseWriters; /** - * @Flow\InjectConfiguration("extensions.documentMetadataGenerators") - * @var array + * cache of the instanciated objects which are configured at {@see $configuredDocumentMetadataGenerators} + * @var DocumentMetadataGeneratorInterface[] */ - protected $configuredDocumentMetadataGenerators; + private array $documentMetadataGenerators; /** - * cache of the instanciated objects which are configured at {@see $configuredDocumentMetadataGenerators} - * @var DocumentMetadataGeneratorInterface[] + * @param array $configuredDocumentRenderers + * @param array $configuredDocumentMetadataGenerators */ - protected $documentMetadataGenerators; + public function __construct( + private readonly ObjectManagerInterface $objectManager, + #[Flow\InjectConfiguration('extensions.documentRenderers')] + protected readonly array $configuredDocumentRenderers, + #[Flow\InjectConfiguration('extensions.documentMetadataGenerators')] + protected readonly array $configuredDocumentMetadataGenerators, + ) {} /** * @return iterable */ - public function enumerateDocumentNode(NodeInterface $documentNode): iterable + public function enumerateDocumentNode(Node $documentNode): iterable { if (!isset($this->documentEnumerators)) { - $this->documentEnumerators = self::instantiateExtensions( + $this->documentEnumerators = $this->instantiateExtensions( $this->configuredDocumentRenderers, DocumentEnumeratorInterface::class, 'enumeratorClassName', @@ -77,25 +77,26 @@ public function enumerateDocumentNode(NodeInterface $documentNode): iterable } } - public function tryToExtractRenderingForEnumeratedNodeFromContentCache(EnumeratedNode $enumeratedNode): RenderedDocumentFromContentCache - { + public function tryToExtractRenderingForEnumeratedNodeFromContentCache( + EnumeratedNode $enumeratedNode, + ): RenderedDocumentFromContentCache { return $this->rendererFor($enumeratedNode)->tryToExtractRenderingForEnumeratedNodeFromContentCache( $enumeratedNode, ); } public function renderDocumentNodeVariant( - NodeInterface $node, + Node $node, EnumeratedNode $enumeratedNode, ContentReleaseLogger $contentReleaseLogger, ): void { $this->rendererFor($enumeratedNode)->renderDocumentNodeVariant($node, $enumeratedNode, $contentReleaseLogger); } - protected function rendererFor(EnumeratedNode $enumeratedNode): DocumentRendererInterface + private function rendererFor(EnumeratedNode $enumeratedNode): DocumentRendererInterface { if (!isset($this->documentRenderers)) { - $this->documentRenderers = self::instantiateExtensions( + $this->documentRenderers = $this->instantiateExtensions( $this->configuredDocumentRenderers, DocumentRendererInterface::class, 'rendererClassName', @@ -103,7 +104,7 @@ protected function rendererFor(EnumeratedNode $enumeratedNode): DocumentRenderer ); } if (!array_key_exists($enumeratedNode->rendererId, $this->documentRenderers)) { - throw new \RuntimeException( + throw new RuntimeException( 'No renderer found for renderer ID ' . $enumeratedNode->rendererId . ' - should never happen!', ); } @@ -113,20 +114,20 @@ protected function rendererFor(EnumeratedNode $enumeratedNode): DocumentRenderer /** * Execute Document Metadata Generators to modify $cacheValues * - * @param NodeInterface $node + * @param Node $node * @param array $arguments - * @param ControllerContext $controllerContext + * @param ActionRequest $actionRequest * @param DocumentNodeCacheValues $cacheValues * @return DocumentNodeCacheValues */ public function runDocumentMetadataGenerators( - NodeInterface $node, + Node $node, array $arguments, - ControllerContext $controllerContext, + ActionRequest $actionRequest, DocumentNodeCacheValues $cacheValues, ): DocumentNodeCacheValues { if (!isset($this->documentMetadataGenerators)) { - $this->documentMetadataGenerators = self::instantiateExtensions( + $this->documentMetadataGenerators = $this->instantiateExtensions( $this->configuredDocumentMetadataGenerators, DocumentMetadataGeneratorInterface::class, ); @@ -136,7 +137,7 @@ public function runDocumentMetadataGenerators( $cacheValues = $documentMetadataGenerator->generateMetadata( $node, $arguments, - $controllerContext, + $actionRequest, $cacheValues, ); } @@ -156,7 +157,7 @@ public function addRenderedDocumentToContentRelease( ContentReleaseLogger $logger, ): void { if (!isset($this->contentReleaseWriters[$enumeratedNode->rendererId])) { - $this->contentReleaseWriters[$enumeratedNode->rendererId] = self::instantiateExtensions( + $this->contentReleaseWriters[$enumeratedNode->rendererId] = $this->instantiateExtensions( $this->configuredDocumentRenderers[$enumeratedNode->rendererId]['contentReleaseWriters'], ContentReleaseWriterInterface::class, optionsKey: 'options', @@ -172,7 +173,11 @@ public function addRenderedDocumentToContentRelease( } } - private static function instantiateExtensions( + /** + * Instances come from the object manager, so extensions can use constructor injection. The options array is + * passed as the first constructor argument; Flow autowires the remaining required arguments. + */ + private function instantiateExtensions( array $configuration, string $extensionInterfaceName, string $classNameKey = 'className', @@ -186,12 +191,12 @@ private static function instantiateExtensions( } $className = $extensionConfig[$classNameKey]; if ($optionsKey !== null) { - $instance = new $className($extensionConfig[$optionsKey] ?? []); + $instance = $this->objectManager->get($className, $extensionConfig[$optionsKey] ?? []); } else { - $instance = new $className(); + $instance = $this->objectManager->get($className); } if (!$instance instanceof $extensionInterfaceName) { - throw new \RuntimeException( + throw new RuntimeException( 'Extension ' . get_class($instance) . ' does not implement ' . $extensionInterfaceName, ); } diff --git a/Classes/NodeRendering/Infrastructure/RedisContentCacheReader.php b/Classes/NodeRendering/Infrastructure/RedisContentCacheReader.php index ae36022..4d784c4 100644 --- a/Classes/NodeRendering/Infrastructure/RedisContentCacheReader.php +++ b/Classes/NodeRendering/Infrastructure/RedisContentCacheReader.php @@ -4,6 +4,7 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Infrastructure; +use Exception; use Flowpack\DecoupledContentStore\NodeRendering\Dto\DocumentNodeCacheKey; use Flowpack\DecoupledContentStore\NodeRendering\Dto\DocumentNodeCacheValues; use Flowpack\DecoupledContentStore\NodeRendering\Dto\RenderedDocumentFromContentCache; @@ -11,39 +12,33 @@ use Neos\Cache\Backend\RedisBackend; use Neos\Cache\Frontend\StringFrontend; use Neos\Flow\Annotations as Flow; -use Neos\Flow\ObjectManagement\ObjectManagerInterface; use Neos\Flow\Package\Exception\UnknownPackageException; use Neos\Flow\Package\PackageManager; use Neos\Fusion\Core\Cache\ContentCache; - -/** - * @Flow\Scope("singleton") - */ -class RedisContentCacheReader +use Redis; +use RedisException; +use ReflectionProperty; +use RuntimeException; +use Sandstorm\OptimizedRedisCacheBackend\OptimizedRedisCacheBackend; + +#[Flow\Scope('singleton')] +final class RedisContentCacheReader { - /** - * @Flow\Inject - * @var StringFrontend - */ - protected $contentCache; - - /** - * @Flow\Inject - * @var ObjectManagerInterface - */ - protected $objectManager; + #[Flow\Inject] + protected StringFrontend $contentCache; - /** - * @Flow\InjectConfiguration(path="cache.applicationIdentifier", package="Neos.Flow") - * @var string - */ - protected $applicationIdentifier; + private ?string $scriptSha1 = null; + private ?Redis $redis = null; - protected ?string $scriptSha1 = null; - protected ?\Redis $redis = null; + public function __construct( + private readonly PackageManager $packageManager, + #[Flow\InjectConfiguration('cache.applicationIdentifier', 'Neos.Flow')] + protected readonly string $applicationIdentifier, + ) {} - public function tryToExtractRenderingForEnumeratedNodeFromContentCache(DocumentNodeCacheKey $documentNodeCacheKey): RenderedDocumentFromContentCache - { + public function tryToExtractRenderingForEnumeratedNodeFromContentCache( + DocumentNodeCacheKey $documentNodeCacheKey, + ): RenderedDocumentFromContentCache { /** * @see AbstractBackend::setCache() */ @@ -67,7 +62,7 @@ public function tryToExtractRenderingForEnumeratedNodeFromContentCache(DocumentN return RenderedDocumentFromContentCache::createWithFullContent($content, $documentNodeCacheValues); } - protected function executeRedisCall(array $params): array + private function executeRedisCall(array $params): array { $redis = $this->getRedis(); @@ -78,20 +73,20 @@ protected function executeRedisCall(array $params): array $error = $redis->getLastError(); if ($error !== null) { - throw new \RuntimeException('Redis error: ' . $error); + throw new RuntimeException('Redis error: ' . $error); } - } catch (\Exception $e) { - throw new \RuntimeException('Redis script execution error: ' . $e->getMessage()); + } catch (Exception $e) { + throw new RuntimeException('Redis script execution error: ' . $e->getMessage()); } if (!is_array($res) || count($res) !== 2) { - throw new \RuntimeException('Result is no array of length 2, but: ' . count($res)); + throw new RuntimeException('Result is no array of length 2, but: ' . count($res)); } return $res; } - protected function prepareRedisScript(): void + private function prepareRedisScript(): void { $redis = $this->getRedis(); @@ -105,12 +100,12 @@ protected function prepareRedisScript(): void $script = $this->buildRedisScript(); $this->scriptSha1 = $redis->script('load', $script); } - } catch (\RedisException $e) { - throw new \RuntimeException('Redis Error: ' . $e->getMessage()); + } catch (RedisException $e) { + throw new RuntimeException('Redis Error: ' . $e->getMessage()); } } - protected function buildRedisScript(): string + private function buildRedisScript(): string { $maxNestLevel = ContentCache::MAXIMUM_NESTING_LEVEL; $contentCacheStartToken = ContentCache::CACHE_SEGMENT_START_TOKEN; @@ -171,37 +166,31 @@ protected function buildRedisScript(): string /** * @throws UnknownPackageException */ - protected function getRedis(): \Redis + private function getRedis(): Redis { if ($this->redis) { return $this->redis; } - $packageManager = $this->objectManager->get(PackageManager::class); - $flowPackage = $packageManager->getPackage('Neos.Flow'); + $flowPackage = $this->packageManager->getPackage('Neos.Flow'); preg_match('/^(\d+\.\d+)/', $flowPackage->getInstalledVersion(), $versionMatches); $flowMajorVersion = (int) ($versionMatches[1] ?? '0'); $backend = $this->contentCache->getBackend(); if ($flowMajorVersion >= 8 && $backend instanceof RedisBackend) { - $reflProp = new \ReflectionProperty(RedisBackend::class, 'redis'); - $reflProp->setAccessible(true); + $reflProp = new ReflectionProperty(RedisBackend::class, 'redis'); $this->redis = $reflProp->getValue($backend); return $this->redis; } if (get_class($backend) === 'Sandstorm\OptimizedRedisCacheBackend\OptimizedRedisCacheBackend') { - $reflProp = new \ReflectionProperty( - \Sandstorm\OptimizedRedisCacheBackend\OptimizedRedisCacheBackend::class, - 'redis', - ); - $reflProp->setAccessible(true); + $reflProp = new ReflectionProperty(OptimizedRedisCacheBackend::class, 'redis'); $this->redis = $reflProp->getValue($backend); return $this->redis; } - throw new \RuntimeException( + throw new RuntimeException( 'The cache backend for "Neos_Fusion_Content" must be an OptimizedRedisCacheBackend, but is ' . get_class($backend), 1622570000, diff --git a/Classes/NodeRendering/Infrastructure/RedisRenderingErrorManager.php b/Classes/NodeRendering/Infrastructure/RedisRenderingErrorManager.php index 05b9695..04a5b72 100644 --- a/Classes/NodeRendering/Infrastructure/RedisRenderingErrorManager.php +++ b/Classes/NodeRendering/Infrastructure/RedisRenderingErrorManager.php @@ -4,6 +4,7 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Infrastructure; +use Exception; use Flowpack\DecoupledContentStore\Core\Domain\Dto\ContentReleaseBatchResult; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; @@ -12,27 +13,18 @@ use Flowpack\DecoupledContentStore\Utility\GeneratorUtility; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RedisRenderingErrorManager +#[Flow\Scope('singleton')] +final readonly class RedisRenderingErrorManager { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + ) {} public function registerRenderingError( ContentReleaseIdentifier $contentReleaseIdentifier, array $additionalData, - \Exception $exception, + Exception $exception, ): void { $this->redisClientManager->getPrimaryRedis()->sAdd( $this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'renderingErrors'), diff --git a/Classes/NodeRendering/Infrastructure/RedisRenderingQueue.php b/Classes/NodeRendering/Infrastructure/RedisRenderingQueue.php index d56fa5b..9b50157 100644 --- a/Classes/NodeRendering/Infrastructure/RedisRenderingQueue.php +++ b/Classes/NodeRendering/Infrastructure/RedisRenderingQueue.php @@ -4,37 +4,30 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Infrastructure; +use Exception; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Infrastructure\RedisClientManager; use Flowpack\DecoupledContentStore\Core\RedisKeyService; use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto\EnumeratedNode; use Flowpack\DecoupledContentStore\NodeRendering\Dto\RendererIdentifier; +use JsonException; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RedisRenderingQueue +#[Flow\Scope('singleton')] +final readonly class RedisRenderingQueue { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + ) {} /** - * @throws \JsonException + * @throws JsonException */ public function appendRenderingJob( ContentReleaseIdentifier $contentReleaseIdentifier, EnumeratedNode $enumeratedNode, - ) { + ): void { $encodedNode = json_encode($enumeratedNode, JSON_THROW_ON_ERROR); $this->redisClientManager->getPrimaryRedis()->rPush( $this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'renderingJobQueue'), @@ -44,9 +37,12 @@ public function appendRenderingJob( public function numberOfQueuedJobs(ContentReleaseIdentifier $contentReleaseIdentifier): int { - return $this->redisClientManager - ->getPrimaryRedis() - ->lLen($this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'renderingJobQueue')) ?? 0; + return ( + $this->redisClientManager + ->getPrimaryRedis() + ->lLen($this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'renderingJobQueue')) + ?? 0 + ); } public function numberOfRenderingsInProgress(ContentReleaseIdentifier $contentReleaseIdentifier): int @@ -54,10 +50,8 @@ public function numberOfRenderingsInProgress(ContentReleaseIdentifier $contentRe return ( $this->redisClientManager ->getPrimaryRedis() - ->hLen($this->redisKeyService->getRedisKeyForPostfix( - $contentReleaseIdentifier, - 'inProgressRenderings', - )) ?? 0 + ->hLen($this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'inProgressRenderings')) + ?? 0 ); } @@ -93,7 +87,7 @@ public function fetchAndReserveNextRenderingJob( 2, ); if ($nextEntry === false && $redis->getLastError() !== null) { - throw new \Exception('Redis operation EVAL failed: ' . $redis->getLastError(), 1471442667); + throw new Exception('Redis operation EVAL failed: ' . $redis->getLastError(), 1471442667); } if ($nextEntry === false) { @@ -110,7 +104,7 @@ public function fetchAndReserveNextRenderingJob( * A node which is handed out more than once means the previous rendering did not lead to a complete content * cache entry, {@see \Flowpack\DecoupledContentStore\NodeRendering\NodeRenderOrchestrator}. * - * @throws \JsonException + * @throws JsonException */ public function registerRenderingAttempt( ContentReleaseIdentifier $contentReleaseIdentifier, @@ -130,7 +124,7 @@ public function registerRenderingAttempt( * Call this before {@see removeRenderingJobFromReservedList()}: the orchestrator stops waiting as soon as no * rendering is in progress anymore, and then drains this list a last time. * - * @throws \JsonException + * @throws JsonException */ public function reportRenderedJob( ContentReleaseIdentifier $contentReleaseIdentifier, @@ -159,7 +153,7 @@ public function fetchNextRenderedJob(ContentReleaseIdentifier $contentReleaseIde * @param EnumeratedNode $enumeratedNode * @param RendererIdentifier $rendererIdentifier * @return bool TRUE if removal was successful or element was not found, FALSE if element was claimed by another renderer in the meantime (however this has happened) - * @throws \JsonException + * @throws JsonException */ public function removeRenderingJobFromReservedList( ContentReleaseIdentifier $contentReleaseIdentifier, @@ -196,7 +190,7 @@ public function removeRenderingJobFromReservedList( ); } - public function flush(ContentReleaseIdentifier $contentReleaseIdentifier) + public function flush(ContentReleaseIdentifier $contentReleaseIdentifier): void { $this->redisClientManager->getPrimaryRedis()->del( $this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'renderingJobQueue'), diff --git a/Classes/NodeRendering/Infrastructure/RedisRenderingTimeStatisticsStore.php b/Classes/NodeRendering/Infrastructure/RedisRenderingTimeStatisticsStore.php index 52d68fd..5015962 100644 --- a/Classes/NodeRendering/Infrastructure/RedisRenderingTimeStatisticsStore.php +++ b/Classes/NodeRendering/Infrastructure/RedisRenderingTimeStatisticsStore.php @@ -13,27 +13,18 @@ use Flowpack\DecoupledContentStore\Utility\GeneratorUtility; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RedisRenderingTimeStatisticsStore +#[Flow\Scope('singleton')] +final readonly class RedisRenderingTimeStatisticsStore { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + ) {} public function addStatisticsIteration( ContentReleaseIdentifier $contentReleaseIdentifier, ?RenderingStatistics $renderingStatistics, - ) { + ): void { $this->redisClientManager->getPrimaryRedis()->rPush( $this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'renderingStatistics'), json_encode($renderingStatistics), @@ -43,7 +34,7 @@ public function addStatisticsIteration( public function replaceLastStatisticsIteration( ContentReleaseIdentifier $contentReleaseIdentifier, RenderingStatistics $renderingStatistics, - ) { + ): void { $this->redisClientManager ->getPrimaryRedis() ->rPop($this->redisKeyService->getRedisKeyForPostfix($contentReleaseIdentifier, 'renderingStatistics')); @@ -61,7 +52,7 @@ public function getRenderingStatistics( ); } - public function flush(ContentReleaseIdentifier $contentReleaseIdentifier) + public function flush(ContentReleaseIdentifier $contentReleaseIdentifier): void { $this->redisClientManager->getPrimaryRedis()->del($this->redisKeyService->getRedisKeyForPostfix( $contentReleaseIdentifier, diff --git a/Classes/NodeRendering/InterruptibleProcessRuntime.php b/Classes/NodeRendering/InterruptibleProcessRuntime.php index c3f890e..d5e223d 100644 --- a/Classes/NodeRendering/InterruptibleProcessRuntime.php +++ b/Classes/NodeRendering/InterruptibleProcessRuntime.php @@ -5,7 +5,10 @@ namespace Flowpack\DecoupledContentStore\NodeRendering; use Flowpack\DecoupledContentStore\NodeRendering\ProcessEvents\ExitEvent; +use Generator; use Neos\Flow\Annotations as Flow; +use ReflectionClass; +use RuntimeException; /** * Our long-lived processes, especially {@see NodeRenderOrchestrator} and {@see NodeRenderer} are kind of hard to test, @@ -38,19 +41,18 @@ * instead of calling exit(), you should `yield ExitEvent::createWithStatusCode()` instead. * * For this to work, - * - * @Flow\Proxy(false) */ +#[Flow\Proxy(false)] final class InterruptibleProcessRuntime { - private \Generator $generator; + private readonly Generator $generator; - private bool $inTestingMode; + private readonly bool $inTestingMode; private bool $encounteredExitEvent = false; private bool $generatorIsPaused = false; - private function __construct(\Generator $generator, bool $inTestingMode) + private function __construct(Generator $generator, bool $inTestingMode) { $this->generator = $generator; $this->inTestingMode = $inTestingMode; @@ -59,10 +61,10 @@ private function __construct(\Generator $generator, bool $inTestingMode) /** * Generate a new Process Runtime in production mode * - * @param \Generator $generator + * @param Generator $generator * @return InterruptibleProcessRuntime */ - public static function create(\Generator $generator): self + public static function create(Generator $generator): self { return new self($generator, false); } @@ -70,10 +72,10 @@ public static function create(\Generator $generator): self /** * Generate a new Process Runtime in testing mode, where {@see ExitEvent} won't trigger an exit() call. * - * @param \Generator $generator + * @param Generator $generator * @return InterruptibleProcessRuntime */ - public static function createForTesting(\Generator $generator): self + public static function createForTesting(Generator $generator): self { return new self($generator, true); } @@ -94,7 +96,7 @@ public function runUntilEnd(): void public function runUntilEventEncountered(string ...$eventClassNames): ?InterruptibleProcessRuntimeEventInterface { if ($this->encounteredExitEvent) { - throw new \RuntimeException('Cannot continue running the Process, as we received an Exit Event already.'); + throw new RuntimeException('Cannot continue running the Process, as we received an Exit Event already.'); } if ($this->generatorIsPaused) { @@ -109,7 +111,7 @@ public function runUntilEventEncountered(string ...$eventClassNames): ?Interrupt // stop iterating the iterator in all cases return $this->handleExitEvent($currentEvent); } - $shortName = (new \ReflectionClass($currentEvent))->getShortName(); + $shortName = new ReflectionClass($currentEvent)->getShortName(); foreach ($eventClassNames as $eventClassName) { if ($eventClassName === $shortName || is_a($currentEvent, $eventClassName)) { // stop here, can be restarted lateron. We still need to continue to the next event here. diff --git a/Classes/NodeRendering/NodeRenderOrchestrator.php b/Classes/NodeRendering/NodeRenderOrchestrator.php index 8d84aff..e57b8f4 100644 --- a/Classes/NodeRendering/NodeRenderOrchestrator.php +++ b/Classes/NodeRendering/NodeRenderOrchestrator.php @@ -4,6 +4,8 @@ namespace Flowpack\DecoupledContentStore\NodeRendering; +use DateTimeImmutable; +use Exception; use Flowpack\DecoupledContentStore\Core\ConcurrentBuildLockService; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; @@ -22,9 +24,11 @@ use Flowpack\DecoupledContentStore\NodeRendering\ProcessEvents\RenderingQueueFilledEvent; use Flowpack\DecoupledContentStore\PrepareContentRelease\Dto\ContentReleaseMetadata; use Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure\RedisContentReleaseService; +use Generator; use Neos\Flow\Annotations as Flow; use Neos\Fusion\Core\Cache\ContentCache; -use Neos\Neos\Fusion\Helper\CachingHelper; +use Neos\Neos\Fusion\Cache\CacheTag; +use RuntimeException; /** * TODO: explain concept of Working Set @@ -48,68 +52,10 @@ * SCHWIERIGER: URL Segment wird geändert von Node. * -> Eventually consistent, kurzzeitig broken link. * ALTERNATIVE: Logik hier im Orchestrator ändern - * - * @Flow\Scope("singleton") */ -class NodeRenderOrchestrator +#[Flow\Scope('singleton')] +final readonly class NodeRenderOrchestrator { - /** - * @Flow\Inject - * @var RedisEnumerationRepository - */ - protected $redisEnumerationRepository; - - /** - * @Flow\Inject - * @var RedisRenderingQueue - */ - protected $redisRenderingQueue; - - /** - * @Flow\Inject - * @var RedisRenderingErrorManager - */ - protected $redisRenderingErrorManager; - - /** - * @Flow\Inject - * @var RedisRenderingTimeStatisticsStore - */ - protected $redisRenderingStatisticsStore; - - /** - * @Flow\Inject - * @var NodeRenderingExtensionManager - */ - protected $nodeRenderingExtensionManager; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; - - /** - * @Flow\Inject - * @var ConcurrentBuildLockService - */ - protected $concurrentBuildLockService; - - /** - * @Flow\Inject - * @var RedisContentReleaseSizeService - */ - protected $redisContentReleaseSizeService; - - #[Flow\Inject] - protected ContentCache $contentCache; - - #[Flow\Inject] - protected CachingHelper $cachingHelper; - - #[Flow\InjectConfiguration('nodeRendering.flushDocumentCacheOnRetry')] - protected bool $flushDocumentCacheOnRetry; - private const EXIT_ERRORSTATUSCODE_RELEASE_ALREADY_COMPLETED = 1; private const EXIT_ERRORSTATUSCODE_EMPTY_ENUMERATION = 2; private const EXIT_ERRORSTATUSCODE_RETRY_LIMIT_REACHED = 3; @@ -122,6 +68,20 @@ class NodeRenderOrchestrator */ private const MAX_ITERATIONS_WITHOUT_PROGRESS = 3; + public function __construct( + private RedisEnumerationRepository $redisEnumerationRepository, + private RedisRenderingQueue $redisRenderingQueue, + private RedisRenderingErrorManager $redisRenderingErrorManager, + private RedisRenderingTimeStatisticsStore $redisRenderingStatisticsStore, + private NodeRenderingExtensionManager $nodeRenderingExtensionManager, + private RedisContentReleaseService $redisContentReleaseService, + private ConcurrentBuildLockService $concurrentBuildLockService, + private RedisContentReleaseSizeService $redisContentReleaseSizeService, + private ContentCache $contentCache, + #[Flow\InjectConfiguration('nodeRendering.flushDocumentCacheOnRetry')] + protected bool $flushDocumentCacheOnRetry, + ) {} + /** * !!! You need to wrap this in the {@see InterruptibleProcessRuntime} so that it works correctly. * @@ -131,15 +91,15 @@ class NodeRenderOrchestrator public function renderContentRelease( ContentReleaseIdentifier $contentReleaseIdentifier, ContentReleaseLogger $contentReleaseLogger, - ): \Generator { + ): Generator { $releaseMetadata = $this->redisContentReleaseService->fetchMetadataForContentRelease($contentReleaseIdentifier); if ($releaseMetadata === null) { - throw new \RuntimeException(sprintf( + throw new RuntimeException(sprintf( 'No metadata found for content release %s.', $contentReleaseIdentifier->getIdentifier(), )); } - $renderStatus = $releaseMetadata->getStatus(); + $renderStatus = $releaseMetadata->status; if ($renderStatus->hasCompleted()) { $contentReleaseLogger->error( @@ -267,7 +227,7 @@ public function renderContentRelease( $this->redisRenderingErrorManager->registerRenderingError( $contentReleaseIdentifier, ['node' => $enumeratedNode->debugString()], - new \Exception(sprintf( + new Exception(sprintf( 'This node was scheduled for rendering %d times in a row without ever becoming complete in the content cache. Check the render worker logs for this node - most likely no "doc--..." mapping entry is written for it.', self::MAX_ITERATIONS_WITHOUT_PROGRESS, )), @@ -434,13 +394,12 @@ private function flushContentCacheForRetry( ): void { $tags = []; foreach ($nodesScheduledForRendering as $enumeratedNode) { - $tags[] = - 'Node_' - . $this->cachingHelper->renderWorkspaceTagForContextNode( - $enumeratedNode->getWorkspaceNameFromContextPath(), - ) - . '_' - . $enumeratedNode->getNodeIdentifier(); + $nodeAddress = $enumeratedNode->getNodeAddress(); + $tags[] = CacheTag::forNodeAggregate( + $nodeAddress->contentRepositoryId, + $nodeAddress->workspaceName, + $nodeAddress->aggregateId, + )->value; } foreach (array_unique($tags) as $tag) { @@ -458,7 +417,7 @@ private function completeContentRelease( ContentReleaseLogger $contentReleaseLogger, ContentReleaseMetadata $releaseMetadata, int $startTime, - ): \Generator { + ): Generator { $contentReleaseLogger->info(sprintf( 'Everything rendered completely in %d seconds. Finishing RenderOrchestrator', time() - $startTime, @@ -477,7 +436,7 @@ private function completeContentRelease( $contentReleaseIdentifier, $releaseMetadata ->withStatus(NodeRenderingCompletionStatus::success()) - ->withEndTime(new \DateTimeImmutable()) + ->withEndTime(new DateTimeImmutable()) ->withContentReleaseSize($contentReleaseSize), RedisInstanceIdentifier::primary(), ); diff --git a/Classes/NodeRendering/NodeRenderer.php b/Classes/NodeRendering/NodeRenderer.php index ec6443a..51d384a 100644 --- a/Classes/NodeRendering/NodeRenderer.php +++ b/Classes/NodeRendering/NodeRenderer.php @@ -4,12 +4,14 @@ namespace Flowpack\DecoupledContentStore\NodeRendering; +use Exception; use Flowpack\DecoupledContentStore\ContentReleaseManager; use Flowpack\DecoupledContentStore\Core\ConcurrentBuildLockService; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger; use Flowpack\DecoupledContentStore\Exception\RenderingException; use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Dto\EnumeratedNode; +use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Service\NodeContextCombinator; use Flowpack\DecoupledContentStore\NodeRendering\Dto\RendererIdentifier; use Flowpack\DecoupledContentStore\NodeRendering\Extensibility\NodeRenderingExtensionManager; use Flowpack\DecoupledContentStore\NodeRendering\Infrastructure\RedisRenderingErrorManager; @@ -17,15 +19,21 @@ use Flowpack\DecoupledContentStore\NodeRendering\ProcessEvents\DocumentRenderedEvent; use Flowpack\DecoupledContentStore\NodeRendering\ProcessEvents\ExitEvent; use Flowpack\DecoupledContentStore\NodeRendering\ProcessEvents\QueueEmptyEvent; -use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer; use Flowpack\DecoupledContentStore\NodeRendering\Tracing\RenderTracerInterface; use Flowpack\DecoupledContentStore\NodeRendering\Tracing\RenderTracerProvider; use Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure\RedisContentReleaseService; -use Neos\ContentRepository\Domain\Model\NodeInterface; -use Neos\ContentRepository\Domain\Service\ContextFactoryInterface; +use Generator; +use Neos\ContentRepository\Core\Projection\ContentGraph\Filter\FindAncestorNodesFilter; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAggregateId; +use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry; use Neos\Flow\Annotations as Flow; use Neos\Flow\Persistence\PersistenceManagerInterface; -use Neos\Neos\Domain\Repository\SiteRepository; +use Neos\Flow\Property\Exception as PropertyException; +use Neos\Neos\Domain\NodeLabel\NodeLabelGeneratorInterface; +use Neos\Neos\Domain\SubtreeTagging\NeosVisibilityConstraints; +use RuntimeException; /** * Not called directly, but through Scripts/renderWorker.sh. @@ -41,10 +49,9 @@ * * If an editor publishes in that window and the publish flushes cache tags of the just-rendered page, the copy finds * holes in the content cache and the page is rendered again in the next iteration. - * - * @Flow\Scope("singleton") */ -class NodeRenderer +#[Flow\Scope('singleton')] +final readonly class NodeRenderer { protected const RESTART_AFTER_RENDER_COUNT = 20; protected const CHECK_FOR_CONCURRENT_RELEASES_RENDER_COUNT = 5; @@ -61,86 +68,46 @@ class NodeRenderer */ public const SPAN_DOCUMENT_PREFIX = 'Content Release Document: '; - /** - * @Flow\Inject - * @var DocumentRenderer - */ - protected $documentRenderer; - - /** - * @Flow\Inject - * @var RedisRenderingQueue - */ - protected $redisRenderingQueue; - - /** - * @Flow\Inject - * @var RedisRenderingErrorManager - */ - protected $redisRenderingErrorManager; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; - - /** - * @Flow\Inject - * @var SiteRepository - */ - protected $siteRepository; - - /** - * @Flow\Inject - * @var ContextFactoryInterface - */ - protected $contextFactory; - - /** - * @Flow\Inject - * @var ContentReleaseManager - */ - protected $contentReleaseManager; - - /** - * @Flow\Inject - * @var PersistenceManagerInterface - */ - protected $persistenceManager; - - /** - * @Flow\Inject - * @var ConcurrentBuildLockService - */ - protected $concurrentBuildLockService; - - /** - * @Flow\Inject - * @var NodeRenderingExtensionManager - */ - protected $nodeRenderingExtensionManager; - - #[Flow\Inject] - protected RenderTracerProvider $renderTracerProvider; + public function __construct( + private RedisRenderingQueue $redisRenderingQueue, + private RedisRenderingErrorManager $redisRenderingErrorManager, + private RedisContentReleaseService $redisContentReleaseService, + private ContentReleaseManager $contentReleaseManager, + private PersistenceManagerInterface $persistenceManager, + private ConcurrentBuildLockService $concurrentBuildLockService, + private NodeRenderingExtensionManager $nodeRenderingExtensionManager, + private RenderTracerProvider $renderTracerProvider, + private ContentRepositoryRegistry $contentRepositoryRegistry, + private NodeLabelGeneratorInterface $nodeLabelGenerator, + #[Flow\InjectConfiguration('nodeRendering.recurseHiddenContent')] + protected bool $recurseHiddenContent, + ) {} public function render( ContentReleaseIdentifier $contentReleaseIdentifier, ContentReleaseLogger $contentReleaseLogger, RendererIdentifier $rendererIdentifier, - ) { + ): Generator { $contentReleaseLogger = $contentReleaseLogger->withRenderer($rendererIdentifier); - $this->renderTracerProvider->getTracer()->describeRun([ - RenderTracerInterface::META_CONTENT_RELEASE => $contentReleaseIdentifier->getIdentifier(), - RenderTracerInterface::META_RENDERER => $rendererIdentifier->string(), - ]); + $this->renderTracerProvider + ->getTracer() + ->describeRun([ + RenderTracerInterface::META_CONTENT_RELEASE => $contentReleaseIdentifier->getIdentifier(), + RenderTracerInterface::META_RENDERER => $rendererIdentifier->string(), + ]); $i = 0; while (true) { - $renderStatus = $this->redisContentReleaseService - ->fetchMetadataForContentRelease($contentReleaseIdentifier) - ->getStatus(); + $releaseMetadata = + $this->redisContentReleaseService->fetchMetadataForContentRelease($contentReleaseIdentifier); + if ($releaseMetadata === null) { + throw new RuntimeException(sprintf( + 'No metadata found for content release %s.', + $contentReleaseIdentifier->getIdentifier(), + )); + } + $renderStatus = $releaseMetadata->status; if ($renderStatus->hasCompleted()) { $contentReleaseLogger->info('Content release completed; so we terminate ourselves gracefully.'); yield ExitEvent::createWithStatusCode(0); @@ -200,10 +167,7 @@ public function render( $i++; - if ( - static::CHECK_FOR_CONCURRENT_RELEASES_RENDER_COUNT > 0 - && ($i % static::CHECK_FOR_CONCURRENT_RELEASES_RENDER_COUNT) === 0 - ) { + if (($i % static::CHECK_FOR_CONCURRENT_RELEASES_RENDER_COUNT) === 0) { $this->concurrentBuildLockService->assertNoOtherContentReleaseWasStarted($contentReleaseIdentifier); } @@ -237,25 +201,26 @@ public function render( * @param integer $releaseIdentifier * @param int $renderingAttempt Number of the current attempt for this node within this content release (1 = first attempt) */ - protected function renderDocumentNodeVariant( + private function renderDocumentNodeVariant( EnumeratedNode $enumeratedNode, ContentReleaseIdentifier $contentReleaseIdentifier, ContentReleaseLogger $contentReleaseLogger, int $renderingAttempt = 1, - ) { + ): void { $nodeWasFound = false; try { $node = $this->fetchRenderableNode($enumeratedNode); - if (!$node instanceof NodeInterface) { + if (!$node instanceof Node) { // This could happen because a deleted node was queued after publishing $nodeWasFound = false; } else { $nodeWasFound = true; $contentReleaseLogger->debug('Rendering document node variant', [ - 'node' => $node->getContextPath(), - 'nodeIdentifier' => $node->getIdentifier(), + 'node' => NodeAddress::fromNode($node)->toJson(), + 'nodeLabel' => $this->renderLabelPath($node), + 'nodeIdentifier' => $node->aggregateId->value, 'workspaceName' => $enumeratedNode->getWorkspaceNameFromContextPath(), 'dimensions' => $enumeratedNode->getDimensionsFromContextPath(), 'arguments' => $enumeratedNode->getArguments(), @@ -264,13 +229,12 @@ protected function renderDocumentNodeVariant( $tracer = $this->renderTracerProvider->getTracer(); $spanParams = [ - 'node' => $node->getContextPath(), - 'site' => $enumeratedNode->getSiteNodeNameFromContextPath(), + 'node' => NodeAddress::fromNode($node)->toJson(), 'dimensions' => $enumeratedNode->getDimensionsFromContextPath(), 'arguments' => $enumeratedNode->getArguments(), ]; $tracer->openSpan(self::SPAN_RENDER_DOCUMENT, $spanParams); - $tracer->openSpan(self::SPAN_DOCUMENT_PREFIX . $node->getContextPath(), $spanParams); + $tracer->openSpan(self::SPAN_DOCUMENT_PREFIX . NodeAddress::fromNode($node)->toJson(), $spanParams); try { $this->nodeRenderingExtensionManager->renderDocumentNodeVariant( $node, @@ -287,7 +251,7 @@ protected function renderDocumentNodeVariant( // all pages in the full iteration (and then, if errors exist, we stop). // This is to gain better visibility into all errors currently happening; and thus maybe being able to see // patterns among the errors. - } catch (\Neos\Flow\Property\Exception $exception) { + } catch (PropertyException $exception) { $contentReleaseLogger->logException( $exception->getPrevious(), 'Exception getting document node variant for rendering', @@ -307,16 +271,16 @@ protected function renderDocumentNodeVariant( 'Exception while rendering document node variant', array( 'node' => $enumeratedNode->debugString(), - 'nodeUri' => $exception->getNodeUri(), + 'nodeUri' => $exception->nodeUri, ), ); $this->redisRenderingErrorManager->registerRenderingError( $contentReleaseIdentifier, - ['node' => $enumeratedNode->debugString(), 'nodeUri' => $exception->getNodeUri()], + ['node' => $enumeratedNode->debugString(), 'nodeUri' => $exception->nodeUri], $exception->getPrevious(), ); - } catch (\Exception $exception) { + } catch (Exception $exception) { $contentReleaseLogger->logException($exception, 'Exception while rendering document node variant', array( 'node' => $enumeratedNode->debugString(), )); @@ -338,7 +302,7 @@ protected function renderDocumentNodeVariant( $this->redisRenderingErrorManager->registerRenderingError( $contentReleaseIdentifier, ['node' => $enumeratedNode->debugString()], - new \Exception( + new Exception( 'We could not load a node which was part of the enumeration. At this point, the content release will definitely fail with no further possibility of recovery. Thus, we are exiting the rendering with an error', ), ); @@ -347,20 +311,42 @@ protected function renderDocumentNodeVariant( } /** - * @param EnumeratedNode $enumeratedNode - * @return NodeInterface|null - * @throws \Exception + * Looks the node up by its identifier, not by the stored address as a whole: the node may have moved since the + * enumeration. Visibility follows {@see NodeContextCombinator::siteNodeInContexts()}, so a document which was + * hidden after the enumeration is not found. + */ + private function fetchRenderableNode(EnumeratedNode $enumeratedNode): ?Node + { + $nodeAddress = $enumeratedNode->getNodeAddress(); + $visibilityConstraints = $this->recurseHiddenContent + ? NeosVisibilityConstraints::excludeRemoved() + : NeosVisibilityConstraints::excludeRemoved()->merge(NeosVisibilityConstraints::excludeDisabled()); + + return $this->contentRepositoryRegistry + ->get($nodeAddress->contentRepositoryId) + ->getContentGraph($nodeAddress->workspaceName) + ->getSubgraph($nodeAddress->dimensionSpacePoint, $visibilityConstraints) + ->findNodeById(NodeAggregateId::fromString($enumeratedNode->getNodeIdentifier())); + } + + /** + * Node labels from the site node down to $node, matching the clicks needed in the Neos document tree. */ - protected function fetchRenderableNode(EnumeratedNode $enumeratedNode): ?NodeInterface + private function renderLabelPath(Node $node): string { - $site = $this->siteRepository->findOneByNodeName($enumeratedNode->getSiteNodeNameFromContextPath()); - - $context = $this->contextFactory->create([ - 'workspaceName' => $enumeratedNode->getWorkspaceNameFromContextPath(), - 'currentSite' => $site, - 'currentDomain' => $site->getFirstActiveDomain(), - 'dimensions' => $enumeratedNode->getDimensionsFromContextPath(), - ]); - return $context->getNodeByIdentifier($enumeratedNode->getNodeIdentifier()); + $ancestors = $this->contentRepositoryRegistry + ->subgraphForNode($node) + ->findAncestorNodes($node->aggregateId, FindAncestorNodesFilter::create()) + ->reverse(); + + $labels = []; + foreach ($ancestors as $ancestor) { + if (!$ancestor->classification->isRoot()) { + $labels[] = $this->nodeLabelGenerator->getLabel($ancestor); + } + } + $labels[] = $this->nodeLabelGenerator->getLabel($node); + + return implode(' > ', $labels); } } diff --git a/Classes/NodeRendering/NodeRenderingUriService.php b/Classes/NodeRendering/NodeRenderingUriService.php index 0af8708..7a654d1 100644 --- a/Classes/NodeRendering/NodeRenderingUriService.php +++ b/Classes/NodeRendering/NodeRenderingUriService.php @@ -9,9 +9,11 @@ use Flowpack\DecoupledContentStore\NodeRendering\Render\DocumentRenderer; use Flowpack\DecoupledContentStore\Transfer\Resource\Target\MultisiteFileSystemSymlinkTarget; use GuzzleHttp\Psr7\ServerRequest; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Filter\FindClosestNodeFilter; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; +use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry; use Neos\Flow\Annotations as Flow; -use Neos\Flow\Configuration\ConfigurationManager; use Neos\Flow\Http\BaseUriProvider; use Neos\Flow\Http\Helper\RequestInformationHelper; use Neos\Flow\Http\ServerRequestAttributes; @@ -24,51 +26,43 @@ use Neos\Flow\ResourceManagement\ResourceManager; use Neos\Flow\Security\Context as SecurityContext; use Neos\Neos\Domain\Model\Site; -use Neos\Neos\Service\LinkingService; +use Neos\Neos\Domain\Repository\SiteRepository; +use Neos\Neos\Domain\Service\NodeTypeNameFactory; +use Neos\Neos\FrontendRouting\SiteDetection\SiteDetectionResult; use Neos\Utility\ObjectAccess; /** * Helper which is able to render a Node URI in headless / CLI mode. Required usually inside * {@see DocumentRendererInterface::renderDocumentNodeVariant()} */ -final class NodeRenderingUriService +final readonly class NodeRenderingUriService { - #[Flow\Inject] - protected ConfigurationManager $configurationManager; + public function __construct( + private BaseUriProvider $baseUriProvider, + private SecurityContext $securityContext, + private ResourceManager $resourceManager, + private ContentRepositoryRegistry $contentRepositoryRegistry, + private SiteRepository $siteRepository, + #[Flow\InjectConfiguration('nodeRendering.useRelativeResourceUris')] + protected bool $useRelativeResourceUris, + ) {} /** - * NOTE: we need to use EAGER injection here, because in buildControllerContextAndSetBaseUri(), we - * directly set a property of the BaseUriProvider using ObjectAccess::setProperty() with forceDirectAccess. - */ - #[Flow\Inject(lazy: false)] - protected BaseUriProvider $baseUriProvider; - - #[Flow\Inject] - protected LinkingService $linkingService; - - #[Flow\Inject] - protected SecurityContext $securityContext; - - #[Flow\Inject] - protected ResourceManager $resourceManager; - - #[Flow\InjectConfiguration('nodeRendering.useRelativeResourceUris')] - protected bool $useRelativeResourceUris; - - /** - * @param NodeInterface $node + * @param Node $node * @param array $arguments * @return string The resolved URI for the given node - * @throws \Exception + * @throws Exception */ - public function buildNodeUri(NodeInterface $node, array $arguments): string + public function buildNodeUri(Node $node, array $arguments): string { - /** @var Site $currentSite */ - $currentSite = $node->getContext()->getCurrentSite(); - if (!$currentSite->hasActiveDomains()) { + $currentSite = $this->findSiteForNode($node) ?? throw new Exception( + sprintf('No site node found for node %s', $node->aggregateId->value), + 1762862400, + ); + $primaryDomain = $currentSite->getPrimaryDomain(); + if (!$currentSite->hasActiveDomains() || $primaryDomain === null) { throw new Exception(sprintf('Site %s has no active domain', $currentSite->getNodeName()), 1666684522); } - $primaryDomain = $currentSite->getPrimaryDomain(); if ((string) $primaryDomain->getScheme() === '') { throw new Exception( sprintf( @@ -89,19 +83,17 @@ public function buildNodeUri(NodeInterface $node, array $arguments): string $arguments, ); $format = $arguments['@format'] ?? 'html'; - $uri = $this->linkingService->createNodeUri( - $baseControllerContext, - $node, - null, - $format, - true, - $arguments, - '', - false, - [], - false, - ); - return self::removeQueryPartFromUri($uri); + $uri = $baseControllerContext + ->getUriBuilder() + ->reset() + ->setArguments($arguments) + ->setFormat($format) + ->setCreateAbsoluteUri(true) + ->uriFor('show', ['node' => NodeAddress::fromNode($node)->toJson()], 'Frontend\\Node', 'Neos.Neos'); + + // remove query from uri + $uriData = explode('?', $uri); + return $uriData[0]; } /** @@ -109,10 +101,9 @@ public function buildNodeUri(NodeInterface $node, array $arguments): string */ public function buildControllerContextAndSetBaseUri( string $uri, - NodeInterface $node, + Node $node, array $arguments = [], - ): ControllerContext - { + ): ControllerContext { $request = $this->buildFakeRequest($uri, $node); if (isset($arguments['@format'])) { $request->setFormat($arguments['@format']); @@ -121,10 +112,13 @@ public function buildControllerContextAndSetBaseUri( // NASTY SIDE-EFFECT: we not only build the controller context, but we also need to inject the "current" base URL to BaseUriProvider, // as this is now (Flow 6.x) used in the UriBuilder to determine the domain. $baseUri = rtrim(RequestInformationHelper::generateBaseUri($request->getHttpRequest())->__toString(), '/'); - ObjectAccess::setProperty($this->baseUriProvider, 'configuredBaseUri', $baseUri, true); + // ObjectAccess::setProperty() takes the subject by reference, which a readonly property cannot be passed as + $baseUriProvider = $this->baseUriProvider; + ObjectAccess::setProperty($baseUriProvider, 'configuredBaseUri', $baseUri, true); $this->injectResourceBaseUri($node); - ObjectAccess::setProperty($this->securityContext, 'initialized', true, true); + $securityContext = $this->securityContext; + ObjectAccess::setProperty($securityContext, 'initialized', true, true); $this->securityContext->setRequest($request); $uriBuilder = $this->uriBuilderForRequest($request); @@ -140,11 +134,9 @@ public function buildControllerContextAndSetBaseUri( * broken host. Targets that already have an override keep it: callers like DocumentRenderer, or exports that * want relative URIs, set it explicitly. */ - private function injectResourceBaseUri(NodeInterface $node): void + private function injectResourceBaseUri(Node $node): void { - /** @var Site|null $currentSite */ - $currentSite = $node->getContext()->getCurrentSite(); - $domain = $currentSite?->getFirstActiveDomain(); + $domain = $this->findSiteForNode($node)?->getFirstActiveDomain(); if ($domain === null) { return; } @@ -159,48 +151,49 @@ private function injectResourceBaseUri(NodeInterface $node): void } } - private function buildFakeRequest(string $uri, NodeInterface $node): ActionRequest + public function findSiteForNode(Node $node): ?Site + { + $siteNode = $this->contentRepositoryRegistry->subgraphForNode($node)->findClosestNode( + $node->aggregateId, + FindClosestNodeFilter::create(NodeTypeNameFactory::NAME_SITE), + ); + + return $siteNode === null ? null : $this->siteRepository->findSiteBySiteNode($siteNode); + } + + private function buildFakeRequest(string $uri, Node $node): ActionRequest { $_SERVER['FLOW_REWRITEURLS'] = '1'; $httpRequest = new ServerRequest('GET', $uri); - $routingParameters = RouteParameters::createEmpty()->withParameter( + $site = $this->findSiteForNode($node) ?? throw new Exception( + sprintf('No site node found for node %s', $node->aggregateId->value), + 1762862402, + ); + // what the SiteDetectionMiddleware stores for a real request - Neos' frontend routing reads it from here + $routingParameters = SiteDetectionResult::create( + $site->getNodeName(), + $site->getConfiguration()->contentRepositoryId, + )->storeInRouteParameters(RouteParameters::createEmpty()->withParameter( 'requestUriHost', $httpRequest->getUri()->getHost(), - ); + )); $httpRequest = $httpRequest->withAttribute(ServerRequestAttributes::ROUTING_PARAMETERS, $routingParameters); $request = ActionRequest::fromHttpRequest($httpRequest); $request->setControllerObjectName('Neos\Neos\Controller\Frontend\NodeController'); $request->setControllerActionName('show'); $request->setFormat('html'); - $request->setArgument('node', $node->getContextPath()); + $request->setArgument('node', NodeAddress::fromNode($node)->toJson()); return $request; } - /** - * @param ActionRequest $request - * @return UriBuilder - * @throws \Neos\Utility\Exception\PropertyNotAccessibleException - */ private function uriBuilderForRequest(ActionRequest $request): UriBuilder { $uriBuilder = new UriBuilder(); $uriBuilder->setRequest($request); - $routesConfiguration = $this->configurationManager->getConfiguration(ConfigurationManager::CONFIGURATION_TYPE_ROUTES); - $router = ObjectAccess::getProperty($uriBuilder, 'router', true); - - $router->setRoutesConfiguration($routesConfiguration); - return $uriBuilder; } - - private static function removeQueryPartFromUri(string $uri): string - { - $uriData = explode('?', $uri); - - return $uriData[0]; - } } diff --git a/Classes/NodeRendering/ProcessEvents/DocumentRenderedEvent.php b/Classes/NodeRendering/ProcessEvents/DocumentRenderedEvent.php index 0ada521..8d26c90 100644 --- a/Classes/NodeRendering/ProcessEvents/DocumentRenderedEvent.php +++ b/Classes/NodeRendering/ProcessEvents/DocumentRenderedEvent.php @@ -10,10 +10,9 @@ /** * Notification that a document was rendered. Emitted from {@see NodeRenderer} - * - * @Flow\Proxy(false) */ -final class DocumentRenderedEvent implements InterruptibleProcessRuntimeEventInterface +#[Flow\Proxy(false)] +final readonly class DocumentRenderedEvent implements InterruptibleProcessRuntimeEventInterface { public static function create(): self { diff --git a/Classes/NodeRendering/ProcessEvents/ExitEvent.php b/Classes/NodeRendering/ProcessEvents/ExitEvent.php index fc96ba2..1cfbc19 100644 --- a/Classes/NodeRendering/ProcessEvents/ExitEvent.php +++ b/Classes/NodeRendering/ProcessEvents/ExitEvent.php @@ -9,15 +9,11 @@ /** * A process - * - * @Flow\Proxy(false) */ -final class ExitEvent implements InterruptibleProcessRuntimeEventInterface +#[Flow\Proxy(false)] +final readonly class ExitEvent implements InterruptibleProcessRuntimeEventInterface { - /** - * @var int - */ - protected $statusCode; + private int $statusCode; private function __construct(int $statusCode) { diff --git a/Classes/NodeRendering/ProcessEvents/QueueEmptyEvent.php b/Classes/NodeRendering/ProcessEvents/QueueEmptyEvent.php index ade51ee..1f3d00a 100644 --- a/Classes/NodeRendering/ProcessEvents/QueueEmptyEvent.php +++ b/Classes/NodeRendering/ProcessEvents/QueueEmptyEvent.php @@ -7,10 +7,8 @@ use Flowpack\DecoupledContentStore\NodeRendering\InterruptibleProcessRuntimeEventInterface; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class QueueEmptyEvent implements InterruptibleProcessRuntimeEventInterface +#[Flow\Proxy(false)] +final readonly class QueueEmptyEvent implements InterruptibleProcessRuntimeEventInterface { public static function create(): self { diff --git a/Classes/NodeRendering/ProcessEvents/RenderingIterationCompletedEvent.php b/Classes/NodeRendering/ProcessEvents/RenderingIterationCompletedEvent.php index ae895b8..0c25417 100644 --- a/Classes/NodeRendering/ProcessEvents/RenderingIterationCompletedEvent.php +++ b/Classes/NodeRendering/ProcessEvents/RenderingIterationCompletedEvent.php @@ -10,10 +10,9 @@ /** * Notification that the rendering iteration was completed once. Emitted from {@see NodeRenderOrchestrator} - * - * @Flow\Proxy(false) */ -final class RenderingIterationCompletedEvent implements InterruptibleProcessRuntimeEventInterface +#[Flow\Proxy(false)] +final readonly class RenderingIterationCompletedEvent implements InterruptibleProcessRuntimeEventInterface { public static function create(): self { diff --git a/Classes/NodeRendering/ProcessEvents/RenderingQueueFilledEvent.php b/Classes/NodeRendering/ProcessEvents/RenderingQueueFilledEvent.php index efe3400..20a303a 100644 --- a/Classes/NodeRendering/ProcessEvents/RenderingQueueFilledEvent.php +++ b/Classes/NodeRendering/ProcessEvents/RenderingQueueFilledEvent.php @@ -10,10 +10,9 @@ /** * Notification that the rendering queue is fully filled. Emitted from {@see NodeRenderOrchestrator} - * - * @Flow\Proxy(false) */ -final class RenderingQueueFilledEvent implements InterruptibleProcessRuntimeEventInterface +#[Flow\Proxy(false)] +final readonly class RenderingQueueFilledEvent implements InterruptibleProcessRuntimeEventInterface { public static function create(): self { diff --git a/Classes/NodeRendering/Render/CustomFusionView.php b/Classes/NodeRendering/Render/CustomFusionView.php index bf8af7a..5d1e676 100644 --- a/Classes/NodeRendering/Render/CustomFusionView.php +++ b/Classes/NodeRendering/Render/CustomFusionView.php @@ -4,63 +4,78 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Render; -use Neos\ContentRepository\Domain\Projection\Content\TraversableNodeInterface; -use Neos\Fusion\Core\Cache\RuntimeContentCache; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\Flow\Annotations as Flow; +use Neos\Flow\Mvc\Controller\ControllerContext; +use Neos\Fusion\Core\FusionConfiguration; +use Neos\Fusion\Core\FusionGlobals; +use Neos\Fusion\Core\FusionSourceCodeCollection; +use Neos\Fusion\Core\Parser; use Neos\Fusion\Core\Runtime; +use Neos\Fusion\Core\RuntimeConfiguration; +use Neos\Neos\Domain\Model\Site; +use Neos\Neos\Domain\Service\FusionSourceCodeFactory; use Neos\Neos\View\FusionView; +use ReflectionProperty; /** - * This Fusion View improves performance by: - * - re-using merged Fusion Object Tree throughout multiple renderings - * - also re-using the Fusion Runtime with all caches. + * This Fusion View improves performance by re-using, per site, the merged Fusion configuration and the + * Fusion Runtime's path configuration cache across all documents of a content release. * - * This leads to a tremendous speed up; in my local tests the full publish - * before was about 3h; now it is about 1h10. + * The Runtime itself is created per document: its "request" Fusion global is readonly, and the request + * differs for every rendered document (URI, format, base URI). */ -class CustomFusionView extends FusionView +final class CustomFusionView extends FusionView { - private $fusionRuntimePerSiteNode = []; + public static bool $useCustomSiteRootFusionPatternEntryPointForBehavioralTests = false; /** - * @var \ReflectionProperty + * @var array */ - private $controllerContextAccessor; - /** - * @var \ReflectionProperty - */ - private $runtimeContentCacheAccessor; - /** - * @var \ReflectionProperty - */ - private $defaultContextVariablesAccessor; + private array $fusionConfigurationPerSiteNode = []; /** - * @var boolean + * @var array */ - private $contentCacheEnabled = true; + private array $runtimeConfigurationPerSiteNode = []; + + private readonly ReflectionProperty $runtimeConfigurationAccessor; + + private bool $contentCacheEnabled = true; + + #[Flow\Inject] + protected Parser $fusionParser; - public static $useCustomSiteRootFusionPatternEntryPointForBehavioralTests = false; + #[Flow\Inject] + protected FusionSourceCodeFactory $fusionSourceCodeFactory; public function __construct(array $options = []) { parent::__construct($options); - $this->controllerContextAccessor = new \ReflectionProperty(Runtime::class, 'controllerContext'); - $this->controllerContextAccessor->setAccessible(true); - - $this->runtimeContentCacheAccessor = new \ReflectionProperty(Runtime::class, 'runtimeContentCache'); - $this->runtimeContentCacheAccessor->setAccessible(true); + $this->fusionRuntime = null; + $this->runtimeConfigurationAccessor = new ReflectionProperty(Runtime::class, 'runtimeConfiguration'); + } - $this->defaultContextVariablesAccessor = new \ReflectionProperty(Runtime::class, 'defaultContextVariables'); - $this->defaultContextVariablesAccessor->setAccessible(true); + /** + * The view is reused for every document, so the request of the current document has to replace the + * previous one (the parent only sets it once). + */ + public function setControllerContext(ControllerContext $controllerContext): void + { + $this->assignedActionRequest = $controllerContext->getRequest(); } - public function initializeObject() + /** + * The parent resolves the site node lazily and stores it as the "site" variable; with a reused view + * it has to be resolved again for every document, which may belong to another site or dimension. + */ + public function assign(string $key, mixed $value): self { - if (self::$useCustomSiteRootFusionPatternEntryPointForBehavioralTests) { - // for self-contained tests, we read fusion from another folder. - $this->fusionService->setSiteRootFusionPattern('resource://%s/Private/EndToEndTestFusion/Root.fusion'); + if ($key === 'value') { + unset($this->variables['site']); } + return parent::assign($key, $value); } /** @@ -97,11 +112,11 @@ public function initializeObject() * 2. EXISTING FusionRuntime instances (if we call this method, for whatever reason, already * during a rendering). In this case, we can directly set $this->fusionRuntime->setEnableContentCache(false); */ - public function disableCache() + public function disableCache(): void { $this->contentCacheEnabled = false; - if ($this->fusionRuntime) { + if ($this->fusionRuntime !== null) { $this->fusionRuntime->setEnableContentCache(false); } } @@ -109,63 +124,69 @@ public function disableCache() /** * See disableCache() method for detailed documentation. */ - public function enableCache() + public function enableCache(): void { $this->contentCacheEnabled = true; - if ($this->fusionRuntime) { + if ($this->fusionRuntime !== null) { $this->fusionRuntime->setEnableContentCache(true); } } - /** - * @param TraversableNodeInterface $currentSiteNode - * @return \Neos\Fusion\Core\Runtime - */ - protected function getFusionRuntime(TraversableNodeInterface $currentSiteNode) + protected function getFusionRuntime(Node $currentSiteNode): Runtime { - // $this->fusionRuntime is RESET during a call to self::assign() - // so this means for every rendered document, we enter this block again + // $this->fusionRuntime is reset by every assign(), so this block runs for every rendered document. if ($this->fusionRuntime === null) { - $currentSiteNodeContextPath = $currentSiteNode->getContextPath(); - - if (!isset($this->fusionRuntimePerSiteNode[$currentSiteNodeContextPath])) { - // OPTIMIZATION 1: we only want to parse the fusion code ONCE and then reuse it again and again. - // This is done by reusing FusionRuntime again and again. - $fusionObjectTree = $this->fusionService->getMergedFusionObjectTree($currentSiteNode); - - // ... but we need to watch out, as the FusionRuntime also gets $this->controllerContext passed in, - // !!*WHICH CHANGES FOR EVERY DOCUMENT*!! - $this->fusionRuntimePerSiteNode[$currentSiteNodeContextPath] = new Runtime( - $fusionObjectTree, - $this->controllerContext, - ); + $siteNodeKey = $currentSiteNode->contentRepositoryId->value . '|' . $currentSiteNode->aggregateId->value; + + if (!array_key_exists($siteNodeKey, $this->fusionConfigurationPerSiteNode)) { + $site = $this->siteRepository->findSiteBySiteNode($currentSiteNode); + $this->fusionConfigurationPerSiteNode[$siteNodeKey] = + self::$useCustomSiteRootFusionPatternEntryPointForBehavioralTests + ? $this->createEndToEndTestFusionConfiguration($site) + : $this->fusionService->createFusionConfigurationFromSite($site); } - $this->fusionRuntime = $this->fusionRuntimePerSiteNode[$currentSiteNodeContextPath]; - - // Luckily for us, the ControllerContext is only stored at $fusionRuntime->controllerContext; - // so we can simply set it for reflection. - // HOWEVER, controllerContext->getRequest() is additionally cached in Runtime::defaultContextVariables, - // so we need to reset this properly as well (see next block). - $this->controllerContextAccessor->setValue($this->fusionRuntime, $this->controllerContext); - - // getDefaultContextVariables() caches the "request" from the controller context lazily. - // As we need the updated request (e.g. with a different format or base URI), we need to reset - // the defaultContextVariables between renderings. - $this->defaultContextVariablesAccessor->setValue($this->fusionRuntime, null); - - // technically, we do NOT need to replace the RuntimeContentCache (it works as well without the next line) - // but I felt this would be an additional safeguard against problems with the cache (e.g. content leaking through dimensions or pages) - $this->runtimeContentCacheAccessor->setValue( - $this->fusionRuntime, - new RuntimeContentCache($this->fusionRuntime), + + $renderingMode = $this->renderingModeService->findByName($this->getOption('renderingModeName')); + $this->fusionRuntime = $this->runtimeFactory->createFromConfiguration( + $this->fusionConfigurationPerSiteNode[$siteNodeKey], + FusionGlobals::fromArray(array_filter([ + 'request' => $this->assignedActionRequest, + 'renderingMode' => $renderingMode, + ])), ); - // after replacing the RuntimeContentCache, we again need to enable the content cache explicitly. - // Otherwise, we do not get any contents into the content store. + // The path configuration cache only depends on the Fusion configuration, so it is shared by all + // Runtimes of a site instead of being rebuilt for every document. + if (array_key_exists($siteNodeKey, $this->runtimeConfigurationPerSiteNode)) { + $this->runtimeConfigurationAccessor->setValue( + $this->fusionRuntime, + $this->runtimeConfigurationPerSiteNode[$siteNodeKey], + ); + } else { + $this->runtimeConfigurationPerSiteNode[$siteNodeKey] = $this->runtimeConfigurationAccessor->getValue($this->fusionRuntime); + } + // We use the property here as the content cache might currently be disabled. $this->fusionRuntime->setEnableContentCache($this->contentCacheEnabled); } return $this->fusionRuntime; } + + /** + * Self-contained behavioral tests read the site's Fusion from Private/EndToEndTestFusion instead of + * Private/Fusion. + */ + private function createEndToEndTestFusionConfiguration(Site $site): FusionConfiguration + { + return $this->fusionParser->parseFromSource( + $this->fusionSourceCodeFactory + ->createFromNodeTypeDefinitions($site->getConfiguration()->contentRepositoryId) + ->union($this->fusionSourceCodeFactory->createFromAutoIncludes()) + ->union(FusionSourceCodeCollection::fromFilePath(sprintf( + 'resource://%s/Private/EndToEndTestFusion/Root.fusion', + $site->getSiteResourcesPackageKey(), + ))), + ); + } } diff --git a/Classes/NodeRendering/Render/DocumentRenderer.php b/Classes/NodeRendering/Render/DocumentRenderer.php index 69ac7c4..2f14612 100644 --- a/Classes/NodeRendering/Render/DocumentRenderer.php +++ b/Classes/NodeRendering/Render/DocumentRenderer.php @@ -4,78 +4,50 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Render; +use Exception as PhpException; use Flowpack\DecoupledContentStore\Aspects\CacheUrlMappingAspect; use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger; use Flowpack\DecoupledContentStore\Exception; use Flowpack\DecoupledContentStore\NodeRendering\NodeRenderingUriService; use Flowpack\DecoupledContentStore\Transfer\Resource\Target\MultisiteFileSystemSymlinkTarget; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; use Neos\Flow\Annotations as Flow; use Neos\Flow\Http\Helper\ResponseInformationHelper; use Neos\Flow\Mvc\ActionRequest; use Neos\Flow\Mvc\ActionResponse; use Neos\Flow\ResourceManagement\ResourceManager; -use Neos\Neos\Domain\Service\ContentContext; use Psr\Http\Message\ResponseInterface; -/** - * @Flow\Scope("singleton") - */ -class DocumentRenderer +#[Flow\Scope('singleton')] +final class DocumentRenderer { - /** - * @Flow\InjectConfiguration("nodeRendering.useRelativeResourceUris") - * @var bool - */ - protected $useRelativeResourceUris; - - /** - * @Flow\Inject - * @var NodeRenderingUriService - */ - protected $nodeRenderingUriService; - - /** - * Add HTTP message if rendering full content - * - * @Flow\InjectConfiguration("nodeRendering.addHttpMessage") - * @var bool - */ - protected $addHttpMessage; - - /** - * @Flow\Inject - * @var CustomFusionView - */ - protected $fusionView; - - /** - * @Flow\Inject(lazy=false) - * @var ResourceManager - */ - protected $resourceManager; - - /** - * @Flow\Inject - * @var CacheUrlMappingAspect - */ - protected $cacheUrlMappingAspect; - - /** - * @var bool - */ - protected $isRendering = false; + private bool $isRendering = false; + + public function __construct( + private readonly NodeRenderingUriService $nodeRenderingUriService, + private readonly CustomFusionView $fusionView, + private readonly ResourceManager $resourceManager, + private readonly CacheUrlMappingAspect $cacheUrlMappingAspect, + #[Flow\InjectConfiguration('nodeRendering.useRelativeResourceUris')] + protected readonly bool $useRelativeResourceUris, + /** + * Add HTTP message if rendering full content + */ + #[Flow\InjectConfiguration('nodeRendering.addHttpMessage')] + protected readonly bool $addHttpMessage, + ) {} /** * Render a specific node variant * - * @param NodeInterface $node + * @param Node $node * @param array $arguments Request arguments when rendering the node * @return string the rendered document (not needed inside this package, but might be useful for others who want to trigger the rendering) * @throws Exception\RenderingException */ public function renderDocumentNodeVariant( - NodeInterface $node, + Node $node, array $arguments, ContentReleaseLogger $contentReleaseLogger, ): string { @@ -83,16 +55,10 @@ public function renderDocumentNodeVariant( $nodeUri = $this->nodeRenderingUriService->buildNodeUri($node, $arguments); try { - $arguments['node'] = $node->getContextPath(); + $arguments['node'] = NodeAddress::fromNode($node)->toJson(); return $this->renderDocumentView($node, $nodeUri, $arguments, $contentReleaseLogger); - } catch (\Exception $exception) { - throw new Exception\RenderingException( - 'Error rendering document view', - $node, - $nodeUri, - 1491378709, - $exception, - ); + } catch (PhpException $exception) { + throw new Exception\RenderingException('Error rendering document view', $nodeUri, 1491378709, $exception); } finally { $this->cacheUrlMappingAspect->afterDocumentRendering(); } @@ -104,24 +70,27 @@ public function renderDocumentNodeVariant( * This will set up a simulated request for rendering the view. If the output contains a "next link" * it will render * - * @param NodeInterface $node + * @param Node $node * @param string $uri The URI for the node * @param array $requestArguments Plain request arguments (e.g. node by context path), could come from routing match results * @return string the rendered output * @throws Exception\InvalidSiteConfigurationException */ - protected function renderDocumentView( - NodeInterface $node, - $uri, + private function renderDocumentView( + Node $node, + string $uri, array $requestArguments, ContentReleaseLogger $contentReleaseLogger, ): string { $this->isRendering = true; try { - /** @var ContentContext $contentContext */ - $contentContext = $node->getContext(); - $site = $contentContext->getCurrentSite(); + $site = $this->nodeRenderingUriService->findSiteForNode( + $node, + ) ?? throw new Exception\InvalidSiteConfigurationException( + 'No site node found for node ' . $node->aggregateId->value, + 1762862401, + ); $domain = $site->getFirstActiveDomain(); $baseUri = (string) $domain; if ($baseUri === '') { @@ -154,21 +123,17 @@ protected function renderDocumentView( $this->fusionView->assign('value', $node); $output = $this->fusionView->render(); - if ($this->addHttpMessage) { - if ($output instanceof ResponseInterface) { - $output = - implode("\r\n", ResponseInformationHelper::prepareHeaders($output)) - . "\r\n" - . $output->getBody()->getContents(); - } else { - $output = self::wrapInHttpMessage($output, $controllerContext->getResponse()); - } - } else { - if ($output instanceof ResponseInterface) { - $output = $output->getBody()->getContents(); - } + if ($output instanceof ResponseInterface) { + return $this->addHttpMessage + ? implode("\r\n", ResponseInformationHelper::prepareHeaders($output)) + . "\r\n" + . $output->getBody()->getContents() + : $output->getBody()->getContents(); } - return $output; + + return $this->addHttpMessage + ? self::wrapInHttpMessage($output->getContents(), $controllerContext->getResponse()) + : $output->getContents(); } finally { $this->isRendering = false; } @@ -197,17 +162,17 @@ private static function wrapInHttpMessage(string $output, ActionResponse $respon /** * @return bool */ - public function isRendering() + public function isRendering(): bool { return $this->isRendering; } - public function disableCache() + public function disableCache(): void { $this->fusionView->disableCache(); } - public function enableCache() + public function enableCache(): void { $this->fusionView->enableCache(); } diff --git a/Classes/NodeRendering/Render/ExtractedExceptionDto.php b/Classes/NodeRendering/Render/ExtractedExceptionDto.php index e9b2fa2..421b19d 100644 --- a/Classes/NodeRendering/Render/ExtractedExceptionDto.php +++ b/Classes/NodeRendering/Render/ExtractedExceptionDto.php @@ -4,24 +4,15 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Render; -class ExtractedExceptionDto +final readonly class ExtractedExceptionDto { - /** - * @var string - */ - protected $message = ''; + private string $message; - /** - * @var string - */ - protected $stackTrace = ''; + private string $stackTrace; - /** - * @var string - */ - protected $referenceCode = ''; + private string $referenceCode; - public function __construct($message, $stackTrace, $referenceCode) + public function __construct(string $message, string $stackTrace, string $referenceCode) { $this->message = $message; $this->stackTrace = $stackTrace; @@ -52,7 +43,7 @@ public function getReferenceCode(): string return $this->referenceCode; } - public function __toString() + public function __toString(): string { return ( $this->getMessage() diff --git a/Classes/NodeRendering/Render/RenderExceptionExtractor.php b/Classes/NodeRendering/Render/RenderExceptionExtractor.php index 0caab65..dd0c825 100644 --- a/Classes/NodeRendering/Render/RenderExceptionExtractor.php +++ b/Classes/NodeRendering/Render/RenderExceptionExtractor.php @@ -4,9 +4,9 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Render; -class RenderExceptionExtractor +final readonly class RenderExceptionExtractor { - const HTML_MESSAGE_HANDLER_PATTERN = '# + private const string HTML_MESSAGE_HANDLER_PATTERN = '#
\s*

@@ -31,7 +31,7 @@ class RenderExceptionExtractor

#xi'; - const XML_COMMENT_HANDLER_PATTERN = '# + private const string XML_COMMENT_HANDLER_PATTERN = '# #xi'; - /** - * @param string $content - * @return ExtractedExceptionDto - */ - public static function extractRenderingException($content) + public static function extractRenderingException(string $content): ?ExtractedExceptionDto { if ( preg_match(self::HTML_MESSAGE_HANDLER_PATTERN, $content, $matches) diff --git a/Classes/NodeRendering/Tracing/NullTracer.php b/Classes/NodeRendering/Tracing/NullTracer.php index 7674491..fa9a006 100644 --- a/Classes/NodeRendering/Tracing/NullTracer.php +++ b/Classes/NodeRendering/Tracing/NullTracer.php @@ -7,21 +7,13 @@ /** * Used when no performanceTracer is configured, so that the rendering can call the tracer unconditionally. */ -final class NullTracer implements RenderTracerInterface +final readonly class NullTracer implements RenderTracerInterface { - public function openSpan(string $name, array $params = []): void - { - } + public function openSpan(string $name, array $params = []): void {} - public function closeSpan(): void - { - } + public function closeSpan(): void {} - public function mark(string $name, array $params = []): void - { - } + public function mark(string $name, array $params = []): void {} - public function describeRun(array $meta): void - { - } + public function describeRun(array $meta): void {} } diff --git a/Classes/NodeRendering/Tracing/PlumberTracer.php b/Classes/NodeRendering/Tracing/PlumberTracer.php index 3ab53c3..005780f 100644 --- a/Classes/NodeRendering/Tracing/PlumberTracer.php +++ b/Classes/NodeRendering/Tracing/PlumberTracer.php @@ -4,6 +4,7 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Tracing; +use RuntimeException; use Sandstorm\Plumber\Core\Domain\Model\EmptyProfilingRun; /** @@ -29,8 +30,7 @@ final class PlumberTracer implements RenderTracerInterface public function __construct( private readonly EmptyProfilingRun $profilingRun, private readonly float $minimumDurationMs, - ) { - } + ) {} public function openSpan(string $name, array $params = []): void { @@ -41,12 +41,12 @@ public function closeSpan(): void { $span = array_pop($this->openSpans); if ($span === null) { - throw new \RuntimeException('closeSpan() was called without a matching openSpan()', 1756200002); + throw new RuntimeException('closeSpan() was called without a matching openSpan()', 1756200002); } [$name, $params, $startTimestamp] = $span; $stopTimestamp = microtime(true); - if (($stopTimestamp - $startTimestamp) * 1000 < $this->minimumDurationMs) { + if ((($stopTimestamp - $startTimestamp) * 1000) < $this->minimumDurationMs) { return; } diff --git a/Classes/NodeRendering/Tracing/PlumberTracerFactory.php b/Classes/NodeRendering/Tracing/PlumberTracerFactory.php index 35ff8bf..98e07a4 100644 --- a/Classes/NodeRendering/Tracing/PlumberTracerFactory.php +++ b/Classes/NodeRendering/Tracing/PlumberTracerFactory.php @@ -4,18 +4,19 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Tracing; +use RuntimeException; use Sandstorm\Plumber\Core\Profiler; /** * Options: * minimumDocumentDurationMs - documents faster than this are not recorded at all. 0 records everything. */ -final class PlumberTracerFactory implements RenderTracerFactoryInterface +final readonly class PlumberTracerFactory implements RenderTracerFactoryInterface { public function build(array $options): RenderTracerInterface { if (!class_exists(Profiler::class)) { - throw new \RuntimeException( + throw new RuntimeException( 'The configured performanceTracer needs sandstorm/plumber, which is not installed. Either run' . ' "composer require --dev sandstorm/plumber" or comment the performanceTracer setting out again.', 1756200003, @@ -27,7 +28,7 @@ public function build(array $options): RenderTracerInterface // here means the process which renders documents is the only one which produces a profile at all. $profilingRun = Profiler::getInstance()->startIfNotRunning(); - $minimumDocumentDurationMs = (float)($options['minimumDocumentDurationMs'] ?? 0); + $minimumDocumentDurationMs = (float) ($options['minimumDocumentDurationMs'] ?? 0); if ($minimumDocumentDurationMs > 0) { // A render worker restarts every twenty documents and each restart writes a profile, so a full // release leaves ~1800 of them behind and /plumber cannot open that many. With a threshold set, diff --git a/Classes/NodeRendering/Tracing/RenderTracerProvider.php b/Classes/NodeRendering/Tracing/RenderTracerProvider.php index 8802f7d..a0c2522 100644 --- a/Classes/NodeRendering/Tracing/RenderTracerProvider.php +++ b/Classes/NodeRendering/Tracing/RenderTracerProvider.php @@ -5,6 +5,7 @@ namespace Flowpack\DecoupledContentStore\NodeRendering\Tracing; use Neos\Flow\Annotations as Flow; +use RuntimeException; /** * Builds the configured tracer once per process. @@ -13,15 +14,17 @@ * factory or it does not. This follows the performanceTracer slot of the Neos 9 ContentRepositoryRegistry. */ #[Flow\Scope('singleton')] -class RenderTracerProvider +final class RenderTracerProvider { + private ?RenderTracerInterface $tracer = null; + /** - * @var array{factoryObjectName: ?string, options: ?array{minimumDocumentDurationMs: int}}|null + * @param array{factoryObjectName?: ?string, options?: ?array{minimumDocumentDurationMs: int}}|null $configuration */ - #[Flow\InjectConfiguration('nodeRendering.performanceTracer')] - protected ?array $configuration = null; - - protected ?RenderTracerInterface $tracer = null; + public function __construct( + #[Flow\InjectConfiguration('nodeRendering.performanceTracer')] + protected readonly ?array $configuration, + ) {} public function getTracer(): RenderTracerInterface { @@ -41,7 +44,7 @@ private function buildTracer(): RenderTracerInterface $factory = new $factoryObjectName(); if (!$factory instanceof RenderTracerFactoryInterface) { - throw new \RuntimeException( + throw new RuntimeException( sprintf( 'The configured performanceTracer factory %s does not implement %s', $factoryObjectName, diff --git a/Classes/Package.php b/Classes/Package.php index cdb1315..5e3cc3b 100644 --- a/Classes/Package.php +++ b/Classes/Package.php @@ -4,26 +4,29 @@ namespace Flowpack\DecoupledContentStore; -use Neos\ContentRepository\Domain\Model\Workspace; use Neos\Flow\Core\Bootstrap; use Neos\Flow\Mvc\Controller\ControllerInterface; use Neos\Flow\Package\Package as BasePackage; +use Neos\Media\Domain\Service\AssetService; -class Package extends BasePackage +final class Package extends BasePackage { /** * @param Bootstrap $bootstrap The current bootstrap * @return void */ - public function boot(Bootstrap $bootstrap) + public function boot(Bootstrap $bootstrap): void { $dispatcher = $bootstrap->getSignalSlotDispatcher(); + // Neos.Neos connects its own AssetChangeHandlerForCacheFlushing first (it boots before this package), so the + // cache tags are already collected when this slot runs. $dispatcher->connect( - Workspace::class, - 'afterNodePublishing', - IncrementalContentReleaseHandler::class, - 'nodePublished', + AssetService::class, + 'assetUpdated', + AssetChangeContentReleaseHandler::class, + 'assetUpdated', + false, ); // NASTY WORKAROUND - explanation follows. @@ -41,7 +44,8 @@ public function boot(Bootstrap $bootstrap) $controller, ) use ($bootstrap) { if ($controller instanceof ControllerInterface) { - $bootstrap->getObjectManager() + $bootstrap + ->getObjectManager() ->get(IncrementalContentReleaseHandler::class) ->startContentReleaseIfNodesWerePublishedBefore(); } diff --git a/Classes/PrepareContentRelease/Dto/ContentReleaseMetadata.php b/Classes/PrepareContentRelease/Dto/ContentReleaseMetadata.php index 2c4fc93..0b14e03 100644 --- a/Classes/PrepareContentRelease/Dto/ContentReleaseMetadata.php +++ b/Classes/PrepareContentRelease/Dto/ContentReleaseMetadata.php @@ -4,75 +4,39 @@ namespace Flowpack\DecoupledContentStore\PrepareContentRelease\Dto; +use DateTime; +use DateTimeImmutable; +use DateTimeInterface; +use Exception; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\PrunnerJobId; use Flowpack\DecoupledContentStore\NodeRendering\Dto\NodeRenderingCompletionStatus; +use JsonSerializable; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Proxy(false) - */ -final class ContentReleaseMetadata implements \JsonSerializable +#[Flow\Proxy(false)] +final readonly class ContentReleaseMetadata implements JsonSerializable { - private PrunnerJobId $prunnerJobId; - - /** - * @var \DateTimeInterface|null - */ - private $startTime; - - /** - * @var \DateTimeInterface|null - */ - private $endTime; - /** - * @var \DateTimeInterface|null + * @param PrunnerJobId[] $manualTransferJobIds + * @param float|null $contentReleaseSize size of the content release in Redis, in megabytes. Determined once + * when the release is finished, as calculating it is expensive. */ - private $switchTime; - - /** - * @var PrunnerJobId[] - */ - private $manualTransferJobIds; - - private NodeRenderingCompletionStatus $status; - - private ?string $workspaceName; - - private ?string $accountId; - - /** - * Size of the content release in Redis, in megabytes. Determined once when the release is finished, - * as calculating it is expensive. - */ - private ?float $contentReleaseSize; - private function __construct( - PrunnerJobId $prunnerJobId, - ?\DateTimeInterface $startTime, - ?\DateTimeInterface $endTime, - ?\DateTimeInterface $switchTime, - ?NodeRenderingCompletionStatus $status, - ?array $manualTransferJobIds = [], - string $workspaceName = 'live', - ?string $accountId = 'cli', - ?float $contentReleaseSize = null, - ) { - $this->prunnerJobId = $prunnerJobId; - $this->startTime = $startTime; - $this->endTime = $endTime; - $this->switchTime = $switchTime; - $this->status = $status ?: NodeRenderingCompletionStatus::scheduled(); - $this->manualTransferJobIds = $manualTransferJobIds; - $this->workspaceName = $workspaceName; - $this->accountId = $accountId; - $this->contentReleaseSize = $contentReleaseSize; - } + public PrunnerJobId $prunnerJobId, + public ?DateTimeInterface $startTime, + public ?DateTimeInterface $endTime, + public ?DateTimeInterface $switchTime, + public NodeRenderingCompletionStatus $status, + public array $manualTransferJobIds = [], + public string $workspaceName = 'live', + public ?string $accountId = 'cli', + public ?float $contentReleaseSize = null, + ) {} public static function create( PrunnerJobId $prunnerJobId, - \DateTimeInterface $startTime, + DateTimeInterface $startTime, string $workspace = 'live', string $accountId = 'cli', ): self { @@ -88,30 +52,34 @@ public static function create( ); } - public static function fromJsonString($metadataEncoded, ContentReleaseIdentifier $contentReleaseIdentifier): self - { + /** + * @throws Exception + */ + public static function fromJsonString( + mixed $metadataEncoded, + ContentReleaseIdentifier $contentReleaseIdentifier, + ): self { if (!is_string($metadataEncoded)) { - throw new \Exception('Metadata is no string for ' . $contentReleaseIdentifier->getIdentifier()); + throw new Exception('Metadata is no string for ' . $contentReleaseIdentifier->getIdentifier()); } $tmp = json_decode($metadataEncoded, true); if (!is_array($tmp)) { - throw new \Exception('ContentReleaseMetadata cannot be constructed from: ' . $metadataEncoded); + throw new Exception('ContentReleaseMetadata cannot be constructed from: ' . $metadataEncoded); } return new self( PrunnerJobId::fromString($tmp['prunnerJobId']), $tmp['startTime'] !== null - ? \DateTimeImmutable::createFromFormat(\DateTime::RFC3339_EXTENDED, $tmp['startTime']) + ? DateTimeImmutable::createFromFormat(DateTime::RFC3339_EXTENDED, $tmp['startTime']) : null, $tmp['endTime'] !== null - ? \DateTimeImmutable::createFromFormat(\DateTime::RFC3339_EXTENDED, $tmp['endTime']) + ? DateTimeImmutable::createFromFormat(DateTime::RFC3339_EXTENDED, $tmp['endTime']) : null, $tmp['switchTime'] !== null - ? \DateTimeImmutable::createFromFormat(\DateTime::RFC3339_EXTENDED, $tmp['switchTime']) + ? DateTimeImmutable::createFromFormat(DateTime::RFC3339_EXTENDED, $tmp['switchTime']) : null, NodeRenderingCompletionStatus::fromString($tmp['status']), - isset($tmp['manualTransferJobIds']) - ? array_map(function (string $item) { + isset($tmp['manualTransferJobIds']) ? array_map(function (string $item) { return PrunnerJobId::fromString($item); }, json_decode($tmp['manualTransferJobIds'])) : [], $tmp['workspaceName'] ?? 'live', @@ -124,9 +92,9 @@ public function jsonSerialize(): array { return [ 'prunnerJobId' => $this->prunnerJobId->getIdentifier(), - 'startTime' => $this->startTime ? $this->startTime->format(\DateTime::RFC3339_EXTENDED) : null, - 'endTime' => $this->endTime ? $this->endTime->format(\DateTime::RFC3339_EXTENDED) : null, - 'switchTime' => $this->switchTime ? $this->switchTime->format(\DateTime::RFC3339_EXTENDED) : null, + 'startTime' => $this->startTime?->format(DateTime::RFC3339_EXTENDED), + 'endTime' => $this->endTime?->format(DateTime::RFC3339_EXTENDED), + 'switchTime' => $this->switchTime?->format(DateTime::RFC3339_EXTENDED), 'status' => $this->status, 'manualTransferJobIds' => json_encode($this->manualTransferJobIds), 'workspaceName' => $this->workspaceName, @@ -135,7 +103,7 @@ public function jsonSerialize(): array ]; } - public function withEndTime(\DateTimeInterface $endTime): self + public function withEndTime(DateTimeInterface $endTime): self { return new self( $this->prunnerJobId, @@ -150,7 +118,7 @@ public function withEndTime(\DateTimeInterface $endTime): self ); } - public function withSwitchTime(\DateTimeInterface $switchTime): self + public function withSwitchTime(DateTimeInterface $switchTime): self { return new self( $this->prunnerJobId, @@ -182,7 +150,7 @@ public function withStatus(NodeRenderingCompletionStatus $status): self public function withAdditionalManualTransferJobId(PrunnerJobId $prunnerJobId): self { - $manualTransferIdArray = $this->getManualTransferJobIds(); + $manualTransferIdArray = $this->manualTransferJobIds; $manualTransferIdArray[] = $prunnerJobId; return new self( $this->prunnerJobId, @@ -211,55 +179,4 @@ public function withContentReleaseSize(float $contentReleaseSize): self $contentReleaseSize, ); } - - public function getPrunnerJobId(): PrunnerJobId - { - return $this->prunnerJobId; - } - - public function getStartTime(): ?\DateTimeInterface - { - return $this->startTime; - } - - public function getEndTime(): ?\DateTimeInterface - { - return $this->endTime; - } - - public function getSwitchTime(): ?\DateTimeInterface - { - return $this->switchTime; - } - - public function getStatus(): NodeRenderingCompletionStatus - { - return $this->status; - } - - /** - * @return PrunnerJobId[] - */ - public function getManualTransferJobIds(): ?array - { - return $this->manualTransferJobIds; - } - - public function getWorkspaceName(): ?string - { - return $this->workspaceName; - } - - public function getAccountId(): ?string - { - return $this->accountId; - } - - /** - * @return float|null size of the content release in megabytes, or NULL if it was not determined (yet) - */ - public function getContentReleaseSize(): ?float - { - return $this->contentReleaseSize; - } } diff --git a/Classes/PrepareContentRelease/Infrastructure/RedisContentReleaseService.php b/Classes/PrepareContentRelease/Infrastructure/RedisContentReleaseService.php index 7106c6a..ccb237d 100644 --- a/Classes/PrepareContentRelease/Infrastructure/RedisContentReleaseService.php +++ b/Classes/PrepareContentRelease/Infrastructure/RedisContentReleaseService.php @@ -4,6 +4,8 @@ namespace Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure; +use DateTimeImmutable; +use Exception; use Flowpack\DecoupledContentStore\Core\Domain\Dto\ContentReleaseBatchResult; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\PrunnerJobId; @@ -14,29 +16,15 @@ use Flowpack\DecoupledContentStore\PrepareContentRelease\Dto\ContentReleaseMetadata; use Flowpack\DecoupledContentStore\Utility\GeneratorUtility; use Neos\Flow\Annotations as Flow; +use RuntimeException; -/** - * @Flow\Scope("singleton") - */ -class RedisContentReleaseService +#[Flow\Scope('singleton')] +final readonly class RedisContentReleaseService { - /** - * @Flow\Inject - * @var RedisClientManager - */ - protected $redisClientManager; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + ) {} public function createContentRelease( ContentReleaseIdentifier $contentReleaseIdentifier, @@ -57,7 +45,7 @@ public function createContentRelease( 'Content Release "%s" already exists', $contentReleaseIdentifier->getIdentifier(), )); - throw new \RuntimeException( + throw new RuntimeException( sprintf( 'Content Release "%s" already exists, cannot create a release with the same identifier', $contentReleaseIdentifier->getIdentifier(), @@ -66,7 +54,7 @@ public function createContentRelease( ); } - $metadata = ContentReleaseMetadata::create($prunnerJobId, new \DateTimeImmutable(), $workspaceName, $accountId); + $metadata = ContentReleaseMetadata::create($prunnerJobId, new DateTimeImmutable(), $workspaceName, $accountId); $redis->multi(); try { @@ -76,7 +64,7 @@ public function createContentRelease( json_encode($metadata), ); $redis->exec(); - } catch (\Exception $e) { + } catch (Exception $e) { $redis->discard(); throw $e; } @@ -119,7 +107,7 @@ public function registerManualTransferJob( /** * @return ContentReleaseIdentifier[] - * @throws \Exception + * @throws Exception */ public function fetchAllReleaseIds(RedisInstanceIdentifier $redisInstanceIdentifier): array { diff --git a/Classes/QuickPublish/ContentReleaseScope.php b/Classes/QuickPublish/ContentReleaseScope.php index 74d9643..a9b12ac 100644 --- a/Classes/QuickPublish/ContentReleaseScope.php +++ b/Classes/QuickPublish/ContentReleaseScope.php @@ -18,16 +18,15 @@ * over unchanged from a release that was validated already. */ #[Flow\Scope('singleton')] -final class ContentReleaseScope +final readonly class ContentReleaseScope { private const CHANGED_URLS_POSTFIX = 'quickPublish:changedUrls'; private const URLS_POSTFIX = 'meta:urls'; - #[Flow\Inject] - protected RedisClientManager $redisClientManager; - - #[Flow\Inject] - protected RedisKeyService $redisKeyService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + ) {} /** * The URLs a quick content release re-rendered, or NULL for a release which was rendered as a whole - meaning diff --git a/Classes/QuickPublish/Dto/NodeIdentifiers.php b/Classes/QuickPublish/Dto/NodeIdentifiers.php index a5bcd74..20129ee 100644 --- a/Classes/QuickPublish/Dto/NodeIdentifiers.php +++ b/Classes/QuickPublish/Dto/NodeIdentifiers.php @@ -5,7 +5,10 @@ namespace Flowpack\DecoupledContentStore\QuickPublish\Dto; use Flowpack\DecoupledContentStore\Exception; +use IteratorAggregate; +use JsonSerializable; use Neos\Flow\Annotations as Flow; +use Traversable; /** * The node identifiers a quick content release was asked to publish. @@ -17,7 +20,7 @@ * @implements \IteratorAggregate */ #[Flow\Proxy(false)] -final class NodeIdentifiers implements \IteratorAggregate, \JsonSerializable +final readonly class NodeIdentifiers implements IteratorAggregate, JsonSerializable { private const IDENTIFIER_PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i'; @@ -86,9 +89,9 @@ private static function fromTokens(array $tokens): self } /** - * @return \Traversable + * @return Traversable */ - public function getIterator(): \Traversable + public function getIterator(): Traversable { yield from $this->identifiers; } diff --git a/Classes/QuickPublish/Dto/QuickPublishPreviewRow.php b/Classes/QuickPublish/Dto/QuickPublishPreviewRow.php index 4c03333..7e7448e 100644 --- a/Classes/QuickPublish/Dto/QuickPublishPreviewRow.php +++ b/Classes/QuickPublish/Dto/QuickPublishPreviewRow.php @@ -13,7 +13,7 @@ * identifiers wants to see which of them is the wrong one, not just that one of them is. */ #[Flow\Proxy(false)] -final class QuickPublishPreviewRow +final readonly class QuickPublishPreviewRow { private string $nodeIdentifier; diff --git a/Classes/QuickPublish/Infrastructure/RedisReleaseCopyService.php b/Classes/QuickPublish/Infrastructure/RedisReleaseCopyService.php index bfb36c5..fa970cf 100644 --- a/Classes/QuickPublish/Infrastructure/RedisReleaseCopyService.php +++ b/Classes/QuickPublish/Infrastructure/RedisReleaseCopyService.php @@ -24,27 +24,23 @@ * the client and back, which is what makes copying a release cheaper than rendering it. */ #[Flow\Scope('singleton')] -final class RedisReleaseCopyService +final readonly class RedisReleaseCopyService { /** * COPY exists since Redis 6.2, while the rest of this package runs on older servers as well. */ - private const MINIMUM_REDIS_VERSION = '6.2.0'; - - #[Flow\Inject] - protected RedisClientManager $redisClientManager; - - #[Flow\Inject] - protected RedisKeyService $redisKeyService; - - #[Flow\Inject] - protected RedisContentReleaseService $redisContentReleaseService; + private const string MINIMUM_REDIS_VERSION = '6.2.0'; /** - * @var array + * @param array $redisKeyPostfixesForEachReleaseConfiguration */ - #[Flow\InjectConfiguration('redisKeyPostfixesForEachRelease')] - protected array $redisKeyPostfixesForEachReleaseConfiguration; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + private RedisContentReleaseService $redisContentReleaseService, + #[Flow\InjectConfiguration('redisKeyPostfixesForEachRelease')] + protected array $redisKeyPostfixesForEachReleaseConfiguration, + ) {} /** * @throws Exception if the source release cannot be built upon, or the server is too old for COPY @@ -180,13 +176,13 @@ private function assertSourceReleaseCanBeBuiltUpon( ); } - if (!$metadata->getStatus()->isSuccessful()) { + if (!$metadata->status->isSuccessful()) { throw new InvalidReleaseException( sprintf( 'Content release %s has the status "%s" instead of "success", so it cannot be copied. Run a full ' . 'content release instead.', $sourceContentReleaseIdentifier->getIdentifier(), - $metadata->getStatus()->getStatus(), + $metadata->status->getStatus(), ), 1786953589, ); diff --git a/Classes/QuickPublish/QuickPublishNodeEnumerator.php b/Classes/QuickPublish/QuickPublishNodeEnumerator.php index ebb1d85..5475c75 100644 --- a/Classes/QuickPublish/QuickPublishNodeEnumerator.php +++ b/Classes/QuickPublish/QuickPublishNodeEnumerator.php @@ -21,7 +21,8 @@ use Flowpack\DecoupledContentStore\PrepareContentRelease\Infrastructure\RedisContentReleaseService; use Flowpack\DecoupledContentStore\QuickPublish\Dto\NodeIdentifiers; use Flowpack\DecoupledContentStore\Utility\GeneratorUtility; -use Neos\ContentRepository\Domain\Model\NodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; use Neos\Flow\Annotations as Flow; use Neos\Fusion\Core\Cache\ContentCache; use Neos\Neos\Fusion\Helper\CachingHelper; @@ -31,40 +32,21 @@ * there is: everything else comes from the release this one was copied from. */ #[Flow\Scope('singleton')] -final class QuickPublishNodeEnumerator +final readonly class QuickPublishNodeEnumerator { - #[Flow\Inject] - protected RedisEnumerationRepository $redisEnumerationRepository; - - #[Flow\Inject] - protected RedisContentReleaseService $redisContentReleaseService; - - #[Flow\Inject] - protected ConcurrentBuildLockService $concurrentBuildLockService; - - #[Flow\Inject] - protected NodeRenderingExtensionManager $nodeRenderingExtensionManager; - - #[Flow\Inject] - protected NodeContextCombinator $nodeContextCombinator; - - #[Flow\Inject] - protected NodeEnumerator $nodeEnumerator; - - #[Flow\Inject] - protected DocumentNodeFilter $documentNodeFilter; - - #[Flow\Inject] - protected ContentCache $contentCache; - - #[Flow\Inject] - protected CachingHelper $cachingHelper; - - #[Flow\Inject] - protected NodeRenderingUriService $nodeRenderingUriService; - - #[Flow\Inject] - protected ContentReleaseScope $contentReleaseScope; + public function __construct( + private RedisEnumerationRepository $redisEnumerationRepository, + private RedisContentReleaseService $redisContentReleaseService, + private ConcurrentBuildLockService $concurrentBuildLockService, + private NodeRenderingExtensionManager $nodeRenderingExtensionManager, + private NodeContextCombinator $nodeContextCombinator, + private NodeEnumerator $nodeEnumerator, + private DocumentNodeFilter $documentNodeFilter, + private ContentCache $contentCache, + private CachingHelper $cachingHelper, + private NodeRenderingUriService $nodeRenderingUriService, + private ContentReleaseScope $contentReleaseScope, + ) {} /** * @throws Exception if nothing is left to render @@ -102,7 +84,7 @@ public function enumerateGivenNodesAndStoreInRedis( $nodesToRender = $this->enumerateGivenNodes( $nodeIdentifiers, $contentReleaseLogger, - $newMetadata->getWorkspaceName() ?? 'live', + $newMetadata->workspaceName, ); // a quick release which renders nothing publishes exactly the release it was copied from - which looks like @@ -145,7 +127,7 @@ public function enumerateGivenNodesAndStoreInRedis( * marks the security context as initialized as a side effect, which would change what the node lookups of the * remaining identifiers are allowed to see. * - * @param array $nodesToRender + * @param array $nodesToRender */ private function writeChangedUrls( array $nodesToRender, @@ -167,7 +149,7 @@ private function writeChangedUrls( /** * The node variants to render, skipping every given identifier which must not or cannot be published. * - * @return array + * @return array */ private function enumerateGivenNodes( NodeIdentifiers $nodeIdentifiers, @@ -179,17 +161,16 @@ private function enumerateGivenNodes( foreach ($nodeIdentifiers as $nodeIdentifier) { $contentCacheFlushed = false; - $variants = $this->nodeContextCombinator->nodeVariantsWithSiteNode($nodeIdentifier, $workspaceName); - foreach ($variants as [$siteNode, $nodeToEnumerate]) { + foreach ($this->nodeContextCombinator->nodeVariants($nodeIdentifier, $workspaceName) as $nodeToEnumerate) { if (!$contentCacheFlushed) { // the tags carry the node identifier and the workspace, so one flush covers every dimension $this->flushContentCacheForNode($nodeToEnumerate, $nodeIdentifier, $contentReleaseLogger); $contentCacheFlushed = true; } - $contextPath = $nodeToEnumerate->getContextPath(); + $contextPath = NodeAddress::fromNode($nodeToEnumerate)->toJson(); - $skipReason = $this->documentNodeFilter->skipReasonForNamedNode($nodeToEnumerate, $siteNode); + $skipReason = $this->documentNodeFilter->skipReasonForNamedNode($nodeToEnumerate); if ($skipReason !== null) { // warn rather than debug: somebody asked for this node by hand and will not see it change $contentReleaseLogger->warn('Skipping node from publishing, because it is ' . $skipReason, [ @@ -212,10 +193,9 @@ private function enumerateGivenNodes( // lists an identifier which resolves nowhere as one row among the others, so somebody publishing // five documents of which one was deleted in the meantime gets the other four. A list in which // nothing at all can be published still fails, in enumerateGivenNodesAndStoreInRedis() - $contentReleaseLogger->warn( - 'Skipping node from publishing, because it is not found in any site and dimension', - ['node' => $nodeIdentifier], - ); + $contentReleaseLogger->warn('Skipping node from publishing, because it is not found in any site and dimension', [ + 'node' => $nodeIdentifier, + ]); } } @@ -228,7 +208,7 @@ private function enumerateGivenNodes( * it copied - the editor's change would be missing without a single error anywhere. */ private function flushContentCacheForNode( - NodeInterface $node, + Node $node, string $nodeIdentifier, ContentReleaseLogger $contentReleaseLogger, ): void { diff --git a/Classes/QuickPublish/QuickPublishPreviewService.php b/Classes/QuickPublish/QuickPublishPreviewService.php index 4f1e330..3f01c7d 100644 --- a/Classes/QuickPublish/QuickPublishPreviewService.php +++ b/Classes/QuickPublish/QuickPublishPreviewService.php @@ -8,10 +8,12 @@ use Flowpack\DecoupledContentStore\NodeEnumeration\Domain\Service\NodeContextCombinator; use Flowpack\DecoupledContentStore\QuickPublish\Dto\NodeIdentifiers; use Flowpack\DecoupledContentStore\QuickPublish\Dto\QuickPublishPreviewRow; -use Neos\ContentRepository\Domain\Model\NodeInterface; -use Neos\ContentRepository\Domain\Projection\Content\TraversableNodeInterface; +use Neos\ContentRepository\Core\Projection\ContentGraph\Node; +use Neos\ContentRepository\Core\SharedModel\Node\NodeAddress; +use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry; use Neos\Flow\Annotations as Flow; use Neos\Flow\Mvc\Controller\ControllerContext; +use Neos\Neos\Domain\NodeLabel\NodeLabelGeneratorInterface; /** * Resolves the node identifiers of a quick release into what the confirmation page shows. @@ -21,13 +23,14 @@ * the pipeline then skips. */ #[Flow\Scope('singleton')] -final class QuickPublishPreviewService +final readonly class QuickPublishPreviewService { - #[Flow\Inject] - protected NodeContextCombinator $nodeContextCombinator; - - #[Flow\Inject] - protected DocumentNodeFilter $documentNodeFilter; + public function __construct( + private NodeContextCombinator $nodeContextCombinator, + private DocumentNodeFilter $documentNodeFilter, + private NodeLabelGeneratorInterface $nodeLabelGenerator, + private ContentRepositoryRegistry $contentRepositoryRegistry, + ) {} /** * @return array one row per dimension variant of every given identifier @@ -39,16 +42,19 @@ public function preview(NodeIdentifiers $nodeIdentifiers, ControllerContext $con foreach ($nodeIdentifiers as $nodeIdentifier) { $nodeFound = false; - foreach ($this->nodeContextCombinator->nodeVariantsWithSiteNode($nodeIdentifier) as [$siteNode, $node]) { + foreach ($this->nodeContextCombinator->nodeVariants($nodeIdentifier) as $node) { $nodeFound = true; $rows[] = QuickPublishPreviewRow::forNode( $nodeIdentifier, - $node->getLabel(), - $node instanceof TraversableNodeInterface ? (string) $node->findNodePath() : '', + $this->nodeLabelGenerator->getLabel($node), + $this->contentRepositoryRegistry + ->subgraphForNode($node) + ->retrieveNodePath($node->aggregateId) + ->serializeToString(), self::describeDimensions($node), - $node->getNodeType()->getName(), + $node->nodeTypeName->value, $this->backendUri($node, $controllerContext), - $this->documentNodeFilter->skipReasonForNamedNode($node, $siteNode), + $this->documentNodeFilter->skipReasonForNamedNode($node), ); } @@ -68,18 +74,19 @@ public function countPublishedRows(array $rows): int return count(array_filter($rows, static fn(QuickPublishPreviewRow $row): bool => $row->isPublished())); } - private function backendUri(NodeInterface $node, ControllerContext $controllerContext): string + private function backendUri(Node $node, ControllerContext $controllerContext): string { - return $controllerContext->getUriBuilder() + return $controllerContext + ->getUriBuilder() ->reset() - ->uriFor('index', ['node' => $node->getContextPath()], 'Backend', 'Neos.Neos.Ui'); + ->uriFor('index', ['node' => NodeAddress::fromNode($node)->toJson()], 'Backend', 'Neos.Neos.Ui'); } - private static function describeDimensions(NodeInterface $node): string + private static function describeDimensions(Node $node): string { $dimensions = []; - foreach ($node->getContext()->getDimensions() as $dimensionName => $dimensionValues) { - $dimensions[] = $dimensionName . ': ' . implode(', ', $dimensionValues); + foreach ($node->dimensionSpacePoint->coordinates as $dimensionName => $dimensionValue) { + $dimensions[] = $dimensionName . ': ' . $dimensionValue; } return implode(' | ', $dimensions); diff --git a/Classes/ReleaseSwitch/Infrastructure/RedisReleaseSwitchService.php b/Classes/ReleaseSwitch/Infrastructure/RedisReleaseSwitchService.php index 2663946..f530049 100644 --- a/Classes/ReleaseSwitch/Infrastructure/RedisReleaseSwitchService.php +++ b/Classes/ReleaseSwitch/Infrastructure/RedisReleaseSwitchService.php @@ -4,6 +4,7 @@ namespace Flowpack\DecoupledContentStore\ReleaseSwitch\Infrastructure; +use DateTimeImmutable; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\ContentReleaseIdentifier; use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; use Flowpack\DecoupledContentStore\Core\Infrastructure\ContentReleaseLogger; @@ -13,46 +14,28 @@ use Flowpack\DecoupledContentStore\Transfer\Dto\RedisKeyPostfixesForEachRelease; use Neos\Flow\Annotations as Flow; -/** - * @Flow\Scope("singleton") - */ -class RedisReleaseSwitchService +#[Flow\Scope('singleton')] +final readonly class RedisReleaseSwitchService { /** - * @Flow\Inject - * @var RedisClientManager + * @param array $redisKeyPostfixesForEachReleaseConfiguration + * @param array $configEpochSettings */ - protected $redisClient; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; - - /** - * @Flow\InjectConfiguration("redisKeyPostfixesForEachRelease") - * @var array - */ - protected $redisKeyPostfixesForEachReleaseConfiguration; - - /** - * @Flow\InjectConfiguration("configEpoch") - * @var array - */ - protected $configEpochSettings; + public function __construct( + private RedisClientManager $redisClient, + private RedisContentReleaseService $redisContentReleaseService, + private RedisKeyService $redisKeyService, + #[Flow\InjectConfiguration('redisKeyPostfixesForEachRelease')] + protected array $redisKeyPostfixesForEachReleaseConfiguration, + #[Flow\InjectConfiguration('configEpoch')] + protected array $configEpochSettings, + ) {} public function switchContentRelease( RedisInstanceIdentifier $redisInstanceIdentifier, ContentReleaseIdentifier $contentReleaseIdentifier, ContentReleaseLogger $contentReleaseLogger, - ) { + ): void { $redis = $this->redisClient->getRedis($redisInstanceIdentifier); $current = $redis->get('contentStore:current'); @@ -98,7 +81,7 @@ public function switchContentRelease( $releaseMetadata = $this->redisContentReleaseService->fetchMetadataForContentRelease($contentReleaseIdentifier); $this->redisContentReleaseService->setContentReleaseMetadata( $contentReleaseIdentifier, - $releaseMetadata->withSwitchTime(new \DateTimeImmutable()), + $releaseMetadata->withSwitchTime(new DateTimeImmutable()), $redisInstanceIdentifier, ); diff --git a/Classes/Transfer/ContentReleaseCleaner.php b/Classes/Transfer/ContentReleaseCleaner.php index fe81fc3..b7e9d4d 100644 --- a/Classes/Transfer/ContentReleaseCleaner.php +++ b/Classes/Transfer/ContentReleaseCleaner.php @@ -15,47 +15,23 @@ use Flowpack\DecoupledContentStore\ReleaseSwitch\Infrastructure\RedisReleaseSwitchService; use Flowpack\DecoupledContentStore\Transfer\Dto\RedisKeyPostfixesForEachRelease; use Neos\Flow\Annotations as Flow; +use RuntimeException; -/** - * @Flow\Scope("singleton") - */ -class ContentReleaseCleaner +#[Flow\Scope('singleton')] +final readonly class ContentReleaseCleaner { /** - * @Flow\Inject - * @var RedisClientManager + * @param array $redisKeyPostfixesForEachReleaseConfiguration */ - protected $redisClientManager; - - /** - * @Flow\InjectConfiguration("redisKeyPostfixesForEachRelease") - * @var array - */ - protected $redisKeyPostfixesForEachReleaseConfiguration; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; - - /** - * @Flow\Inject - * @var RedisReleaseSwitchService - */ - protected $redisReleaseSwitchService; - - /** - * @Flow\Inject - * @var RedisRenderingErrorManager - */ - protected $redisRenderingErrorManager; - - /** - * @Flow\Inject - * @var RedisContentReleaseService - */ - protected $redisContentReleaseService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + private RedisReleaseSwitchService $redisReleaseSwitchService, + private RedisRenderingErrorManager $redisRenderingErrorManager, + private RedisContentReleaseService $redisContentReleaseService, + #[Flow\InjectConfiguration('redisKeyPostfixesForEachRelease')] + protected array $redisKeyPostfixesForEachReleaseConfiguration, + ) {} public function removeOldReleases( RedisInstanceIdentifier $redisInstanceIdentifier, @@ -80,7 +56,7 @@ public function removeOldReleases( $contentReleasesToKeep = $this->redisClientManager->getRetentionCount($redisInstanceIdentifier); if ($contentReleasesToKeep < 2) { - throw new \RuntimeException('contentReleaseRetentionCount must be at least 2, found: ' + throw new RuntimeException('contentReleaseRetentionCount must be at least 2, found: ' . $contentReleasesToKeep); } @@ -104,7 +80,7 @@ public function removeOldReleases( if ( $this->redisContentReleaseService->fetchMetadataForContentRelease( $id, - )->getStatus()->getStatus() === NodeRenderingCompletionStatus::success()->getStatus() + )?->status->getStatus() === NodeRenderingCompletionStatus::success()->getStatus() && count($this->redisRenderingErrorManager->getRenderingErrors($id)) === 0 ) { $healthyReleaseCounter++; diff --git a/Classes/Transfer/ContentReleaseSynchronizer.php b/Classes/Transfer/ContentReleaseSynchronizer.php index 98713b4..7857c0a 100644 --- a/Classes/Transfer/ContentReleaseSynchronizer.php +++ b/Classes/Transfer/ContentReleaseSynchronizer.php @@ -11,29 +11,21 @@ use Flowpack\DecoupledContentStore\Core\RedisKeyService; use Flowpack\DecoupledContentStore\Transfer\Dto\RedisKeyPostfixesForEachRelease; use Neos\Flow\Annotations as Flow; +use Redis; +use RuntimeException; -/** - * @Flow\Scope("singleton") - */ -class ContentReleaseSynchronizer +#[Flow\Scope('singleton')] +final readonly class ContentReleaseSynchronizer { /** - * @Flow\Inject - * @var RedisClientManager + * @param array $redisKeyPostfixesForEachReleaseConfiguration */ - protected $redisClientManager; - - /** - * @Flow\InjectConfiguration("redisKeyPostfixesForEachRelease") - * @var array - */ - protected $redisKeyPostfixesForEachReleaseConfiguration; - - /** - * @Flow\Inject - * @var RedisKeyService - */ - protected $redisKeyService; + public function __construct( + private RedisClientManager $redisClientManager, + private RedisKeyService $redisKeyService, + #[Flow\InjectConfiguration('redisKeyPostfixesForEachRelease')] + protected array $redisKeyPostfixesForEachReleaseConfiguration, + ) {} public function syncToTarget( RedisInstanceIdentifier $targetRedisIdentifier, @@ -97,12 +89,12 @@ public function syncToTarget( * * @param string $keyToTransfer */ - protected function transferKey( - \Redis $sourceRedis, - \Redis $targetRedis, + private function transferKey( + Redis $sourceRedis, + Redis $targetRedis, string $keyToTransfer, ContentReleaseLogger $contentReleaseLogger, - ) { + ): void { $contentReleaseLogger->debug('SYNC: Attempting to transfer ' . $keyToTransfer); if (!$sourceRedis->exists($keyToTransfer)) { @@ -134,12 +126,12 @@ protected function transferKey( )); } - protected function transferHashKeyIncrementally( - \Redis $sourceRedis, - \Redis $targetRedis, + private function transferHashKeyIncrementally( + Redis $sourceRedis, + Redis $targetRedis, string $keyToTransfer, ContentReleaseLogger $contentReleaseLogger, - ) { + ): void { $contentReleaseLogger->debug('SYNC: (INCREMENTAL) Attempting to transfer ' . $keyToTransfer); if (!$sourceRedis->exists($keyToTransfer)) { @@ -156,14 +148,14 @@ protected function transferHashKeyIncrementally( ); } - if ($sourceRedis->type($keyToTransfer) !== \Redis::REDIS_HASH) { + if ($sourceRedis->type($keyToTransfer) !== Redis::REDIS_HASH) { $contentReleaseLogger->error( 'SYNC: (INCREMENTAL) !!! transferHashKeyIncrementally should only be used with hashes, but ' . $keyToTransfer . ' is of type ' . $sourceRedis->type($keyToTransfer), ); - throw new \RuntimeException( + throw new RuntimeException( '!!! transferHashKeyIncrementally should only be used with hashes, but ' . $keyToTransfer . ' is of type ' @@ -174,7 +166,7 @@ protected function transferHashKeyIncrementally( $expectedNumberOfHashItems = $sourceRedis->hLen($keyToTransfer); // Don't ever return an empty array until we're done iterating (so that our while loop does not abort early) - $sourceRedis->setOption(\Redis::OPT_SCAN, \Redis::SCAN_RETRY); + $sourceRedis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY); // we have approx 80 000 entries (as of Mar 2021) in the "data" part // and it takes between 1 and 10; or at max 40 seconds to import them @@ -205,7 +197,7 @@ protected function transferHashKeyIncrementally( . ', actual: ' . $actualNumberOfHashItems, ); - throw new \RuntimeException( + throw new RuntimeException( '!!!! Number of hash items mismatch for key ' . $keyToTransfer . ' - expected ' diff --git a/Classes/Transfer/Dto/RedisKeyPostfixForEachRelease.php b/Classes/Transfer/Dto/RedisKeyPostfixForEachRelease.php index 1766ecf..ded822f 100644 --- a/Classes/Transfer/Dto/RedisKeyPostfixForEachRelease.php +++ b/Classes/Transfer/Dto/RedisKeyPostfixForEachRelease.php @@ -7,21 +7,20 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; use Flowpack\DecoupledContentStore\Exception\InvalidTransferConfigException; use Neos\Flow\Annotations as Flow; +use RuntimeException; -/** - * @Flow\Proxy(false) - */ -final class RedisKeyPostfixForEachRelease +#[Flow\Proxy(false)] +final readonly class RedisKeyPostfixForEachRelease { private const TRANSFER_MODE_HASH_INCREMENTAL = 'hash_incremental'; private const TRANSFER_MODE_DUMP = 'dump'; - protected string $redisKeyPostfix; - protected array $transfer; - protected string $transferMode; - protected bool $isRequired; - protected bool $copyOnQuickRelease; - protected bool $keepAfterRemoval; + private string $redisKeyPostfix; + private array $transfer; + private string $transferMode; + private bool $isRequired; + private bool $copyOnQuickRelease; + private bool $keepAfterRemoval; /** * @param string $redisKeyPostfix @@ -33,14 +32,14 @@ final class RedisKeyPostfixForEachRelease */ private function __construct( string $redisKeyPostfix, - $transfer, + bool|array $transfer, string $transferMode, bool $isRequired, bool $copyOnQuickRelease, bool $keepAfterRemoval, ) { if (!in_array($transferMode, [self::TRANSFER_MODE_HASH_INCREMENTAL, self::TRANSFER_MODE_DUMP])) { - throw new \RuntimeException('TransferMode ' . $transferMode . ' not supported.'); + throw new RuntimeException('TransferMode ' . $transferMode . ' not supported.'); } if (is_bool($transfer)) { diff --git a/Classes/Transfer/Dto/RedisKeyPostfixesForEachRelease.php b/Classes/Transfer/Dto/RedisKeyPostfixesForEachRelease.php index 3f098b4..7dfed55 100644 --- a/Classes/Transfer/Dto/RedisKeyPostfixesForEachRelease.php +++ b/Classes/Transfer/Dto/RedisKeyPostfixesForEachRelease.php @@ -6,12 +6,12 @@ use Flowpack\DecoupledContentStore\Core\Domain\ValueObject\RedisInstanceIdentifier; -class RedisKeyPostfixesForEachRelease +final readonly class RedisKeyPostfixesForEachRelease { /** * @var RedisKeyPostfixForEachRelease[] */ - protected array $redisKeyPostfixes; + private array $redisKeyPostfixes; /** * @param RedisKeyPostfixForEachRelease[] $redisKeyPostfixes diff --git a/Classes/Transfer/Resource/RemoteResourceSynchronizer.php b/Classes/Transfer/Resource/RemoteResourceSynchronizer.php index ca67df9..3bb3aee 100644 --- a/Classes/Transfer/Resource/RemoteResourceSynchronizer.php +++ b/Classes/Transfer/Resource/RemoteResourceSynchronizer.php @@ -10,16 +10,16 @@ use Neos\Flow\Annotations as Flow; use Neos\Utility\Files; -/** - * @Flow\Scope("singleton") - */ -class RemoteResourceSynchronizer +#[Flow\Scope('singleton')] +final readonly class RemoteResourceSynchronizer { /** - * @Flow\InjectConfiguration(path="resourceSync.targets") - * @var array + * @param array $targets */ - protected $targets = array(); + public function __construct( + #[Flow\InjectConfiguration('resourceSync.targets')] + protected array $targets, + ) {} /** * @throws Exception diff --git a/Classes/Transfer/Resource/Target/MultisiteFileSystemSymlinkTarget.php b/Classes/Transfer/Resource/Target/MultisiteFileSystemSymlinkTarget.php index 2e7737b..36def2f 100644 --- a/Classes/Transfer/Resource/Target/MultisiteFileSystemSymlinkTarget.php +++ b/Classes/Transfer/Resource/Target/MultisiteFileSystemSymlinkTarget.php @@ -4,10 +4,12 @@ namespace Flowpack\DecoupledContentStore\Transfer\Resource\Target; +use Neos\Flow\ResourceManagement\Collection; use Neos\Flow\ResourceManagement\ResourceManager; use Neos\Flow\ResourceManagement\Target\FileSystemSymlinkTarget; +use Neos\Utility\Exception\PropertyNotAccessibleException; -class MultisiteFileSystemSymlinkTarget extends FileSystemSymlinkTarget +final class MultisiteFileSystemSymlinkTarget extends FileSystemSymlinkTarget { /** * @var string @@ -21,17 +23,17 @@ class MultisiteFileSystemSymlinkTarget extends FileSystemSymlinkTarget * a "current" base URI. It's also needed to render nodes for multiple sites. * * @param string $baseUri - * @throws \Neos\Utility\Exception\PropertyNotAccessibleException + * @throws PropertyNotAccessibleException */ public static function injectBaseUriIntoRelevantResourcePublishingTargets( string $baseUri, ResourceManager $resourceManager, - ) { + ): void { // Make sure the base URI ends with a slash $baseUri = rtrim($baseUri, '/') . '/'; $collections = $resourceManager->getCollections(); - /** @var \Neos\Flow\ResourceManagement\Collection $collection */ + /** @var Collection $collection */ foreach ($collections as $collection) { $target = $collection->getTarget(); if ($target instanceof MultisiteFileSystemSymlinkTarget) { @@ -43,7 +45,7 @@ public static function injectBaseUriIntoRelevantResourcePublishingTargets( /** * @return string */ - protected function getResourcesBaseUri() + protected function getResourcesBaseUri(): string { if ($this->overrideHttpBaseUri === null) { return parent::getResourcesBaseUri(); @@ -59,7 +61,7 @@ public function hasOverrideHttpBaseUri(): bool /** * @param string $overrideHttpBaseUri */ - public function setOverrideHttpBaseUri(string $overrideHttpBaseUri) + public function setOverrideHttpBaseUri(string $overrideHttpBaseUri): void { $this->overrideHttpBaseUri = $overrideHttpBaseUri; } diff --git a/Classes/Utility/GeneratorUtility.php b/Classes/Utility/GeneratorUtility.php index 8dc4f7f..92d50fb 100644 --- a/Classes/Utility/GeneratorUtility.php +++ b/Classes/Utility/GeneratorUtility.php @@ -4,7 +4,7 @@ namespace Flowpack\DecoupledContentStore\Utility; -class GeneratorUtility +final readonly class GeneratorUtility { /** * @template T diff --git a/Classes/Utility/Sparkline.php b/Classes/Utility/Sparkline.php index 67c3cd1..021201f 100644 --- a/Classes/Utility/Sparkline.php +++ b/Classes/Utility/Sparkline.php @@ -5,7 +5,7 @@ namespace Flowpack\DecoupledContentStore\Utility; // taken and adapted from https://raw.githubusercontent.com/jxxe/sparkline/master/sparkline.php -class Sparkline +final readonly class Sparkline { /** * Generate SVG sparklines with PHP @@ -14,7 +14,7 @@ class Sparkline * @license MIT * @link https://github.com/jxxe/sparkline/ */ - private static function getY($max, $height, $diff, $value) + private static function getY(int|float $max, int|float $height, int|float $diff, int|float $value): float { // prevent division by zero if ($max === 0) { @@ -24,7 +24,10 @@ private static function getY($max, $height, $diff, $value) return round(floatval($height - (($value * $height) / $max) + $diff), 2); } - private static function buildElement($tag, $attrs) + /** + * @param array $attrs + */ + private static function buildElement(string $tag, array $attrs): string { $element = '<' . $tag . ' '; foreach ($attrs as $attr => $value) { @@ -34,12 +37,16 @@ private static function buildElement($tag, $attrs) return $element; } + /** + * @param array $values + * @param array{strokeWidth: int|float, width: int|float, height: int|float}|null $options + */ public static function sparkline( - $svgClass, - $values, - $lineColor = '#aaa', - $fillColor = 'none', - $options = null, + string $svgClass, + array $values, + string $lineColor = '#aaa', + string $fillColor = 'none', + ?array $options = null, ): string { if (count($values) <= 1) { return ''; diff --git a/Configuration/Settings.yaml b/Configuration/Settings.yaml index 6f5e062..dc3face 100644 --- a/Configuration/Settings.yaml +++ b/Configuration/Settings.yaml @@ -262,8 +262,6 @@ Neos: javascript: 'Flowpack.DecoupledContentStore:AutomaticReleaseWarning': resource: 'resource://Flowpack.DecoupledContentStore/Public/ContentModule/AutomaticReleaseWarning.js' - # Before the UI host and without "defer", because the host reads the inlined _NEOS_UI_* globals once and - # deletes them - the script has to capture the route table before that happens. position: 'before Neos.Neos.UI:Host' stylesheets: 'Flowpack.DecoupledContentStore:AutomaticReleaseWarning': @@ -292,6 +290,14 @@ Neos: 'Flowpack.DecoupledContentStore': position: 'before Neos.Neos' + ContentRepositoryRegistry: + presets: + 'default': + contentGraphProjection: + catchUpHooks: + 'Flowpack.DecoupledContentStore:IncrementalContentRelease': + factoryObjectName: Flowpack\DecoupledContentStore\IncrementalContentReleaseCatchUpHookFactory + Fusion: defaultContext: Flowpack.DecoupledContentStore: Flowpack\DecoupledContentStore\Eel\ModuleHelper diff --git a/Configuration/Testing/Behat/Objects.yaml b/Configuration/Testing/Behat/Objects.yaml deleted file mode 100644 index 2f76f3d..0000000 --- a/Configuration/Testing/Behat/Objects.yaml +++ /dev/null @@ -1,27 +0,0 @@ -# Normally, content dimension presets get injected from the Neos.ContentRepository.contentDimensions Setting. -# For running the Behat tests, we do not want the settings to be merged together, because we want to fully -# control all active content dimensions. -# If we would not do this here, the content dimensions of this package (for testing) would be merged -# with the content dimensions of other site packages, leading to indeterministic tests. -'Neos\ContentRepository\Domain\Service\ConfigurationContentDimensionPresetSource': - properties: - configuration: &contentDimensionPresets - value: - language: - default: en_US - defaultPreset: en_US - presets: - en_US: - label: 'English (US)' - values: - - en_US - uriSegment: en - de: - label: 'DE' - values: - - de - uriSegment: de - -Neos\Neos\Domain\Service\ConfigurationContentDimensionPresetSource: - properties: - configuration: *contentDimensionPresets diff --git a/Configuration/Testing/Behat/Settings.yaml b/Configuration/Testing/Behat/Settings.yaml index 0bbff78..9b0d6b2 100644 --- a/Configuration/Testing/Behat/Settings.yaml +++ b/Configuration/Testing/Behat/Settings.yaml @@ -21,3 +21,31 @@ Flowpack: # the key is written by documentMetadataGenerators, and the test setup registers none - so nothing that # requires every registered key to exist could ever pass here isRequired: false + +Neos: + ContentRepositoryRegistry: + contentRepositories: + # The scenarios declare node types and dimensions themselves (see FeatureContext), and the release code reads + # the "default" content repository. + default: + authProvider: + factoryObjectName: Neos\ContentRepository\TestSuite\Fakes\FakeAuthProviderFactory + nodeTypeManager: + factoryObjectName: Neos\ContentRepository\TestSuite\Fakes\FakeNodeTypeManagerFactory + contentDimensionSource: + factoryObjectName: Neos\ContentRepository\TestSuite\Fakes\FakeContentDimensionSourceFactory + + Neos: + sites: + 'test': + preset: default + uriPathSuffix: '' + contentDimensions: + resolver: + factoryClassName: Neos\Neos\FrontendRouting\DimensionResolution\Resolver\UriPathResolverFactory + options: + segments: + - + dimensionIdentifier: language + dimensionValueMapping: + de: de diff --git a/Documentation/Concepts/QuickContentReleases.md b/Documentation/Concepts/QuickContentReleases.md index 145b65a..41b4442 100644 --- a/Documentation/Concepts/QuickContentReleases.md +++ b/Documentation/Concepts/QuickContentReleases.md @@ -175,7 +175,7 @@ the release which was copied while the document itself is re-rendered, so a page go live disagreeing with each other. They are not written into `quickPublish:changedUrls`, though, which only knows the documents that were named — a scoped validator does not see them. -The hidden / orphaned / node-type guards are shared with the full enumeration through +The hidden / node-type guards are shared with the full enumeration through `NodeEnumeration/Domain/Service/DocumentNodeFilter`, which expresses `nodeTypeWhitelist` twice: as the FlowQuery filter string the full enumeration passes to `find()`, and as a check for a single node, which is what an enumerator starting from identifiers needs. The node-type check is deliberately **not** part of the shared `skipReason()`: @@ -192,34 +192,32 @@ The identifiers are a value object, `QuickPublish/Dto/NodeIdentifiers`, which re This is not cosmetic: the list travels through a pipeline variable into a shell command, so unvalidated input is a command-injection hole. The check lives at the point where the list is read, not only in the backend form. -Variants of a node are resolved through `NodeContextCombinator::nodeVariantsWithSiteNode()` — via `sites()` and -`siteNodeInContexts()` rather than `nodeInContexts()`, because the orphan check needs the site node. -`getNodeByIdentifier()` searches the whole content repository rather than one site, so it answers for every site -alike: each candidate is matched against the site node by its `findNodePath()` before it is handed out, or a -multi-site installation would pair every node with the first site and report it as orphaned. Once a site has claimed -the node the remaining ones are skipped, since a node belongs to exactly one site. +Variants of a node are resolved through `NodeContextCombinator::nodeVariants()`: one `findNodeById()` per dimension +space point of the content repository. There is no site lookup and no orphan check — the content graph only holds a +node in a dimension space point where its parent is covered as well, so every node it hands out sits below a site node. -That lookup shows invisible content regardless of `nodeRendering.recurseHiddenContent`, which defaults to `false`. +That lookup shows disabled nodes regardless of `nodeRendering.recurseHiddenContent`, which defaults to `false`. The setting is about recursing into hidden content while walking the tree; applied to a lookup by identifier it makes a hidden page indistinguishable from one which does not exist, and the first hidden page tried reported "not found in -any site and dimension". `siteNodeInContexts()` therefore takes an `$invisibleContentShown` override, `NULL` keeping -the configured behaviour for the full enumeration. Hidden pages are still not published — the skip reason says -"hidden", on the confirmation page and in the pipeline log alike. +any site and dimension". `nodeVariants()` therefore uses its own visibility constraints (soft-removed nodes excluded, +disabled ones shown), while `siteNodeInContexts()` builds the full enumeration's subgraphs from the setting. Hidden +pages are still not published — the skip reason says "hidden", on the confirmation page and in the pipeline log alike. -Because of that override, `skipReasonForNamedNode()` also has to walk the pages **above** the node, which -`skipReason()` does not: with `recurseHiddenContent` at its default the full enumeration descends from the site node -in a context which hides them, so a document below a hidden page is not in the content store at all. Naming it in a -quick release would resolve, render and publish it — a page live until the next full release quietly removes it -again. The skip reason for that is "below a hidden page". +Because of that, `skipReasonForNamedNode()` also has to look at the pages **above** the node, which `skipReason()` +does not: with `recurseHiddenContent` at its default the full enumeration descends from the site node in a subgraph +which hides them, so a document below a hidden page is not in the content store at all. Naming it in a quick release +would resolve, render and publish it — a page live until the next full release quietly removes it again. The skip +reason for that is "below a hidden page". -That walk is therefore gated on the very setting which decides the traversal: where `recurseHiddenContent` is `true` +That check is therefore gated on the very setting which decides the traversal: where `recurseHiddenContent` is `true` the full enumeration does reach such a document, and skipping it in a quick release would be the same mismatch the other way round. The hidden page itself stays unpublished either way — that is `skipReason()`, which the setting does not touch. -Both levels ask `isVisible()` rather than `isHidden()`, so a page hidden by `hiddenBeforeDateTime` / -`hiddenAfterDateTime` counts as hidden as well: it is hidden to a visitor just the same, and the context of the full -enumeration filters it on exactly that measure. +Both levels read the `disabled` subtree tag: `skipReason()` the node's own, `skipReasonForNamedNode()` the inherited +one, which the content graph already carries on every node below a disabled one — no walk up the tree is needed. A +page hidden by `enableAfterDateTime` / `disableAfterDateTime` counts as hidden only once +`neos/timeable-node-visibility` has disabled it, which is also when the full enumeration stops seeing it. ## 6. Validation scoped to the changed URLs @@ -291,16 +289,14 @@ administrators inside the Content Store module. The state is published as a Neos the backend module: `ModulePrivilege` expands internally into a method privilege over every action of the module controller, so a status action there would be readable only by the people who already have module access — precisely not the editors the warning is for. Data sources are granted to `Neos.Neos:AbstractEditor` by Neos itself, need no -route of their own, and the script reaches them through `_NEOS_UI_routes.core.service.dataSource`, so no URI is +route of their own, and the script reaches them through `routes.core.service.dataSource`, so no URI is hardcoded. The data source returns nothing but the flag, the timestamp, the account and the counter, so widening its access costs nothing. It must not be `final`: Neos instantiates data sources with `new`, and an unproxied class gets no property injection. -Two constraints on the script which registers under `Neos.Neos.Ui.resources.javascript`, both learned the hard way: -it must run **before** `Neos.Neos.UI:Host` and **without `defer`**. The UI host reads the inlined `_NEOS_UI_*` -globals through `getInlinedData()`, which does `delete window[...]` immediately after reading, so a deferred script -finds `_NEOS_UI_routes` already gone and cannot build the endpoint URI. The script therefore captures the route table -at evaluation time and waits for `DOMContentLoaded` before touching the DOM. +The script registers under `Neos.Neos.Ui.resources.javascript` and reads the route table from the JSON the UI inlines +into `