Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
e62cb5f
FEATURE: Command to delete stale workspaces
sachera Mar 12, 2026
6a2f20e
TASK: Move stale workspace detection logic to WorkspaceService
sachera Apr 2, 2026
09c92e2
TASK: Refactor checking if a workspace has workspaces depending on them
sachera Apr 2, 2026
97836c2
TASK: Remove `@throws` annotations which have no effect on a Flow CLI…
mhsdesign Apr 2, 2026
3db6be5
TASK: Keep time calculation logic in command controller to have Works…
mhsdesign Apr 2, 2026
5e6100a
TASK: Use static `PHPUnit\Framework\Assert` as in other places
mhsdesign Apr 2, 2026
865bea7
TASK: Simplify api of `getStaleWorkspaceNames()` to not include unuse…
mhsdesign Apr 2, 2026
adaa2bc
TASK: Introduce typed collections for `WorkspaceNames` and `UserIds`
mhsdesign Apr 2, 2026
8e7240b
TASK: Rename `getStaleWorkspaceNames` to `getStalePersonalWorkspaceNa…
mhsdesign Apr 2, 2026
e350988
TASK: countable WorkspaceNames
mhsdesign Apr 2, 2026
28a9527
TASK: Move feature from `ContentRepository` context to own `User` con…
mhsdesign Apr 2, 2026
e0e8d44
TASK: Ensure WorkspaceService fully encapsulates stale workspace dele…
mhsdesign Apr 2, 2026
64f9112
WIP: Add failing test that `createPersonalWorkspaceForUserIfMissing()…
mhsdesign Apr 2, 2026
321a7ef
TASK: Do not force specific order in tests for stale workspaces and u…
sachera Apr 7, 2026
336be2f
TASK: Allow any order for set of existing workspaces in tests
sachera Apr 8, 2026
5e988ab
TASK: Recreate personal Workspaces if Metadata still exists but the W…
sachera Apr 8, 2026
be9a9d4
TASK: Run WorkspaceMetadata Cleanup after test rather than before to …
sachera Apr 8, 2026
70e390d
WIP: Add testcase to show stale workspace recreation works for "live"…
sachera Apr 8, 2026
445a6eb
Task: Fix linting errors
sachera Apr 8, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Neos.Neos/Classes/Command/WorkspaceCommandController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@

namespace Neos\Neos\Command;

use DateInterval;
use Neos\ContentRepository\Core\Feature\Security\Exception\AccessDenied;
use Neos\ContentRepository\Core\Feature\WorkspaceCreation\Exception\WorkspaceAlreadyExists;
use Neos\ContentRepository\Core\Feature\WorkspaceModification\Command\DeleteWorkspace;
use Neos\ContentRepository\Core\Feature\WorkspaceRebase\Dto\RebaseErrorHandlingStrategy;
use Neos\ContentRepository\Core\Feature\WorkspaceRebase\Exception\WorkspaceRebaseFailed;
use Neos\ContentRepository\Core\Service\WorkspaceMaintenanceServiceFactory;
Expand Down Expand Up @@ -524,6 +527,35 @@ public function showCommand(string $workspace, string $contentRepository = 'defa
]);
}

/**
* Removes all stale personal workspaces.
*
* A personal workspace is considered stale if it has no pending changes, no other workspace uses it as a base
* workspace and the owner of the workspace did not log in for the time specified.
*
* @param string $contentRepository The name of the content repository. (Default: 'default')
* @param string $dateInterval The time interval a user had to be inactive for its workspaces to be considered stale. (Default: '7 days')
* @throws AccessDenied
* @throws \DateInvalidOperationException
*/
public function removeStaleCommand(string $contentRepository = 'default', string $dateInterval = '7 days'): void

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest a different naming for the command. The command sounds it removes any stale workspace, but the comment correctly explains its only certain user workspaces. Though a note on their automatic recreation would also be helpful here in the comment.

If we hopefully soonish can extend the removal to other types of workspaces with potential different rules, we have a naming clash. Or what did you think about future future extensions?

{
$contentRepositoryId = ContentRepositoryId::fromString($contentRepository);
$contentRepositoryInstance = $this->contentRepositoryRegistry->get($contentRepositoryId);

$interval = DateInterval::createFromDateString($dateInterval);
if ($interval === false) {
$this->outputLine('Unable to parse date interval "%s".', [$dateInterval]);
$this->quit();
}

$staleWorkspaces = $this->workspaceService->getStaleWorkspaceNames($contentRepositoryId, $interval);

foreach ($staleWorkspaces as $workspace) {
$contentRepositoryInstance->handle(DeleteWorkspace::create($workspace));
}
}

// -----------------------

private function buildWorkspaceRoleSubject(WorkspaceRoleSubjectType $subjectType, string $usernameOrRoleIdentifier): WorkspaceRoleSubject
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,30 @@ classification = :personalWorkspaceClassification
}
}

/**
* @return \Traversable<UserId,WorkspaceName>
*/
public function findAllPersonalWorkspaceNamesByContentRepositoryId(ContentRepositoryId $contentRepositoryId): \Traversable
{
$tableMetadata = self::TABLE_NAME_WORKSPACE_METADATA;
$query = <<<SQL
SELECT
owner_user_id, content_repository_id, workspace_name
FROM
{$tableMetadata}
WHERE
classification = :personalWorkspaceClassification
AND content_repository_id = :contentRepositoryId
SQL;
$rows = $this->dbal->fetchAllAssociative($query, [
'personalWorkspaceClassification' => WorkspaceClassification::PERSONAL->value,
'contentRepositoryId' => $contentRepositoryId->value,
]);
foreach ($rows as $row) {
yield UserId::fromString($row['owner_user_id']) => WorkspaceName::fromString($row['workspace_name']);
}
}

/**
* @param \Closure(): void $fn
* @return void
Expand Down
25 changes: 25 additions & 0 deletions Neos.Neos/Classes/Domain/Service/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

namespace Neos\Neos\Domain\Service;

use DateTimeInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Persistence\Exception\IllegalObjectTypeException;
use Neos\Flow\Persistence\PersistenceManagerInterface;
Expand Down Expand Up @@ -775,6 +776,30 @@ public function getAllRoles(User $user): array
return $roles;
}

/**
* @param DateTimeInterface $dateTime
* @return \Traversable<UserId>
*/
public function findUserIdsNotLoggedInAfter(DateTimeInterface $dateTime): \Traversable
{
/** @var User $user */
foreach ($this->getUsers() as $user) {
$accounts = $user->getAccounts();
$loggedIn = false;
foreach ($accounts as $account) {
$lastSuccessfulAuthenticationDate = $account->getLastSuccessfulAuthenticationDate();
if ($lastSuccessfulAuthenticationDate != null && $lastSuccessfulAuthenticationDate > $dateTime) {
$loggedIn = true;
break;
}
}

if (!$loggedIn) {
yield $user->getId();
}
}
}

/**
* @param User $user
* @param bool $keepCurrentSession
Expand Down
37 changes: 37 additions & 0 deletions Neos.Neos/Classes/Domain/Service/WorkspaceService.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

namespace Neos\Neos\Domain\Service;

use DateInterval;
use Neos\ContentRepository\Core\Feature\Security\Exception\AccessDenied;
use Neos\ContentRepository\Core\Feature\WorkspaceCreation\Command\CreateRootWorkspace;
use Neos\ContentRepository\Core\Feature\WorkspaceCreation\Command\CreateWorkspace;
Expand All @@ -27,6 +28,7 @@
use Neos\ContentRepositoryRegistry\ContentRepositoryRegistry;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Security\Context as SecurityContext;
use Neos\Flow\Utility\Now;
use Neos\Neos\Domain\Model\User;
use Neos\Neos\Domain\Model\UserId;
use Neos\Neos\Domain\Model\WorkspaceClassification;
Expand Down Expand Up @@ -56,6 +58,7 @@
private ContentRepositoryAuthorizationService $authorizationService,
private SecurityContext $securityContext,
private SoftRemovalGarbageCollector $softRemovalGarbageCollector,
private Now $now,
) {
}

Expand Down Expand Up @@ -301,6 +304,40 @@
throw new \RuntimeException(sprintf('Failed to find unique workspace name for "%s" after %d attempts.', $candidate, $attempt - 1), 1725975479);
}

/**
* @param ContentRepositoryId $contentRepositoryId
* @param DateInterval $interval
* @return \Traversable<UserId,WorkspaceName>
* @throws \DateInvalidOperationException
*/
public function getStaleWorkspaceNames(ContentRepositoryId $contentRepositoryId, DateInterval $interval): \Traversable

Check failure on line 313 in Neos.Neos/Classes/Domain/Service/WorkspaceService.php

View workflow job for this annotation

GitHub Actions / PHP 8.2 Test linting-unit-functionaltests-mysql (deps: highest)

PHPDoc tag @throws with type DateInvalidOperationException is not subtype of Throwable
{
$contentRepositoryInstance = $this->contentRepositoryRegistry->get($contentRepositoryId);

$workspaces = $contentRepositoryInstance->findWorkspaces();
$probablyStaleWorkspaceNames = array_flip(iterator_to_array(
$workspaces
->filter(fn($workspace) => !$workspace->hasPublishableChanges() &&
$workspaces->getDependantWorkspacesRecursively($workspace->workspaceName)->isEmpty())
->map(fn($workspace) => $workspace->workspaceName->value)
));

$inactiveUserIds = array_flip(array_map(
fn($userId) => $userId->value,
iterator_to_array($this->userService->findUserIdsNotLoggedInAfter($this->now->sub($interval)))
));

$personalWorkspaces = $this->metadataAndRoleRepository->findAllPersonalWorkspaceNamesByContentRepositoryId($contentRepositoryId);
foreach ($personalWorkspaces as $userId => $personalWorkspace) {
if (
array_key_exists($personalWorkspace->value, $probablyStaleWorkspaceNames) &&
array_key_exists($userId->value, $inactiveUserIds)
) {
yield $userId => $personalWorkspace;
}
}
}

// ------------------

/**
Expand Down
44 changes: 44 additions & 0 deletions Neos.Neos/Tests/Behavior/Features/Bootstrap/UserServiceTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
use Neos\Neos\Domain\Service\UserService;
use Neos\Party\Domain\Model\PersonName;
use Neos\Utility\ObjectAccess;
use function PHPUnit\Framework\assertEmpty;
use function PHPUnit\Framework\assertSameSize;
use function PHPUnit\Framework\assertTrue;

/**
* Step implementations for UserService related tests inside Neos.Neos
Expand Down Expand Up @@ -72,6 +75,47 @@ public function theFollowingNeosUsersExist(TableNode $usersTable): void
}
}

/**
* @When Neos user :username last logged in :days days ago
*/
public function neosUserLastLoggedInDaysAgo(string $username, int $days): void
{
$userService = $this->getObject(UserService::class);
$user = $userService->getUser($username);
$lastLoginDate = (new \DateTime())->sub(new \DateInterval('P' . $days . 'D'));
$user->getAccounts()->map(function($account) use ($lastLoginDate) {
$refLastSuccessfulAuthenticationDate = new ReflectionProperty(\Neos\Flow\Security\Account::class, 'lastSuccessfulAuthenticationDate');
$refLastSuccessfulAuthenticationDate->setAccessible(true);
$refLastSuccessfulAuthenticationDate->setValue($account, $lastLoginDate);
});
$userService->updateUser($user);
}

/**
* @Then the following users did not log in within :days days:
*/
public function theFollowingUsersDidNotLogInWithinXDays(int $days, TableNode $usersTable): void
{
/**
* @var array<string> $expected
*/
$expected = [];
foreach ($usersTable->getHash() as $userData) {
$expected[$userData['Id']] = true;
}

$userService = $this->getObject(UserService::class);
$cutoffDate = (new \DateTime())->sub(new \DateInterval('P' . $days . 'D'));
$actual = iterator_to_array($userService->findUserIdsNotLoggedInAfter($cutoffDate));

foreach ($actual as $userId) {
$userIdString = $userId->value;
assertTrue(isset($expected[$userIdString]), "User \"$userIdString\" did no login within $days days, but was expected to.");
unset($expected[$userIdString]);
}
assertEmpty($expected, "The following users were missing from user not logged in within $days days: " . join(', ', $expected));
}

private function createUser(string $username, ?string $firstName = null, ?string $lastName = null, ?array $roleIdentifiers = null, ?string $id = null): void
{
$userService = $this->getObject(UserService::class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

use Behat\Gherkin\Node\TableNode;
use Neos\ContentRepository\Core\Feature\WorkspaceCreation\Command\CreateRootWorkspace;
use Neos\ContentRepository\Core\SharedModel\ContentRepository\ContentRepositoryId;
use Neos\ContentRepository\Core\SharedModel\Exception\WorkspaceDoesNotExist;
use Neos\ContentRepository\Core\SharedModel\Workspace\ContentStreamId;
use Neos\ContentRepository\Core\SharedModel\Workspace\WorkspaceName;
Expand Down Expand Up @@ -359,6 +360,35 @@ public function theNeosUserShouldHaveNoPermissionsForWorkspace(string $username,
Assert::assertFalse($permissions->manage);
}

/**
* @Then the following stale workspaces exist in content repository :contentRepositoryId:
*/
public function theFollowingStaleWorkspacesExistInContentRepository(string $contentRepositoryId, TableNode $workspacesAndUsernames): void
{
$expectedWorkspaces = [];
foreach ($workspacesAndUsernames->getColumnsHash() as $workspaceAndUsername) {
$expectedWorkspaces[$workspaceAndUsername["Userid"]] = $workspaceAndUsername["WorkspaceName"];
}

$actualWorkspaces = $this->getObject(WorkspaceService::class)->getStaleWorkspaceNames(
ContentRepositoryId::fromString($contentRepositoryId),
new DateInterval('P7D'),
);

$count = 0;
foreach ($actualWorkspaces as $userId => $workspace) {
$count++;
$userIdString = $userId->value;
$workspaceString = $workspace->value;
Assert::assertTrue(array_key_exists($userIdString, $expectedWorkspaces), "Found unexpected workspace $workspaceString for UserId $userIdString");

$workspaceForId = $expectedWorkspaces[$userIdString];
Assert::assertEquals($workspaceForId, $workspace->value, "workspace for userId $workspaceForId is $workspaceString but was expected to be $workspaceForId");
}
$expectedCount = count($expectedWorkspaces);
Assert::assertEquals($expectedCount, $count, "Expected $expectedCount personal workspaces, but found $count");
}

private function userIdForUsername(string $username): UserId
{
$user = $this->getObject(UserService::class)->getUser($username);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
@flowEntities
Feature: Neos UserService related features

Background:
Given using no content dimensions
And using the following node types:
"""yaml
'Neos.ContentRepository:Root': {}
"""
And using identifier "default", I define a content repository
And I am in content repository "default"
And the following Neos users exist:
| Id | Username | First name | Last name | Roles |
| janedoe | jane.doe | Jane | Doe | Neos.Neos:Administrator |
| johndoe | john.doe | John | Doe | Neos.Neos:RestrictedEditor,Neos.Neos:UserManager |
| editor | editor | Edward | Editor | Neos.Neos:Editor |

Scenario: List user accounts not logged in for some time
When Neos user "jane.doe" last logged in 9 days ago
And Neos user "john.doe" last logged in 6 days ago
And Neos user "editor" last logged in 5 days ago
Then the following users did not log in within 7 days:
| Id |
| janedoe |
And the following users did not log in within 6 days:
| Id |
| janedoe |
| johndoe |
And the following users did not log in within 3 days:
| Id |
| janedoe |
| johndoe |
| editor |
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Feature: Neos WorkspaceService related features
Given using no content dimensions
And using the following node types:
"""yaml
'Neos.ContentRepository:Root': {}
'Neos.ContentRepository.Testing:Node': {}
"""
And using identifier "default", I define a content repository
And I am in content repository "default"
Expand Down Expand Up @@ -291,3 +291,37 @@ Feature: Neos WorkspaceService related features
Then the Neos user "jane.doe" should have the permissions "read,write,manage" for workspace "some-root-workspace"
And the Neos user "john.doe" should have no permissions for workspace "some-root-workspace"
And the Neos user "editor" should have no permissions for workspace "some-root-workspace"

Scenario: Personal Workspaces without change and without user login within 7 days are stale
When the root workspace "some-root-workspace" is created
Then the following stale workspaces exist in content repository "default":
| WorkspaceName | Userid |

When the personal workspace "janedoe-user-workspace" is created with the target workspace "some-root-workspace" for user "jane.doe"
And Neos user "jane.doe" last logged in 9 days ago
And the personal workspace "johndoe-user-workspace" is created with the target workspace "some-root-workspace" for user "john.doe"
And Neos user "john.doe" last logged in 8 days ago
And the personal workspace "editor-user-workspace" is created with the target workspace "some-root-workspace" for user "editor"
And Neos user "editor" last logged in 5 days ago
Then the following stale workspaces exist in content repository "default":
| WorkspaceName | Userid |
| janedoe-user-workspace | janedoe |
| johndoe-user-workspace | johndoe |

Scenario: Workspaces with changes are not stale
Given the root workspace "some-root-workspace" is created
And I am in workspace "some-root-workspace"
And the command CreateRootNodeAggregateWithNode is executed with payload:
| Key | Value |
| nodeAggregateId | "lady-eleonode-rootford" |
| nodeTypeName | "Neos.ContentRepository:Root" |

When the personal workspace "janedoe-user-workspace" is created with the target workspace "some-root-workspace" for user "jane.doe"
And I am in workspace "janedoe-user-workspace"
And the following CreateNodeAggregateWithNode commands are executed:
| nodeAggregateId | nodeName | parentNodeAggregateId | nodeTypeName | initialPropertyValues |
| sir-david-nodenborough | node | lady-eleonode-rootford | Neos.ContentRepository.Testing:Node | {} |
And Neos user "jane.doe" last logged in 9 days ago

Then the following stale workspaces exist in content repository "default":
| WorkspaceName | Userid |
8 changes: 8 additions & 0 deletions phpstan-baseline.neon
Original file line number Diff line number Diff line change
Expand Up @@ -214,3 +214,11 @@ parameters:
message: "#^Return type \\(void\\) of method Neos\\\\Neos\\\\ResourceManagement\\\\NodeTypesStreamWrapper\\:\\:removeDirectory\\(\\) should be compatible with return type \\(bool\\) of method Neos\\\\Flow\\\\ResourceManagement\\\\Streams\\\\StreamWrapperInterface\\:\\:removeDirectory\\(\\)$#"
count: 1
path: Neos.Neos/Classes/ResourceManagement/NodeTypesStreamWrapper.php

-
# DateInvalidOperationException was introduced in PHP 8.3 - on PHP 8.2 the class does not exist and PHPStan reports throws.notThrowable
message: "#^PHPDoc tag @throws with type DateInvalidOperationException(\\|[^ ]+)? is not subtype of Throwable$#"
count: 1
path: Neos.Neos/Classes/Command/WorkspaceCommandController.php
# on PHP 8.3 and newer this ignore is unmatched and therefore would be reported as such
reportUnmatched: false
Loading