Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

declare(strict_types=1);

namespace Neos\ContentRepository\Core\SharedModel\Workspace;

/**
* @implements \IteratorAggregate<int,WorkspaceName>
* @api
*/
final readonly class WorkspaceNames implements \IteratorAggregate, \Countable
{
/** @param array<string,WorkspaceName> $items */
private function __construct(
private array $items
) {
}

public static function create(
WorkspaceName ...$items
): self {
$indexed = [];
foreach ($items as $item) {
$indexed[$item->value] = $item;
}
return new self(
$indexed
);
}

public static function fromWorkspaces(Workspaces $workspaces): self
{
return WorkspaceNames::create(...$workspaces->map(fn (Workspace $workspace) => $workspace->workspaceName));
}

public function contain(WorkspaceName $workspaceName): bool
{
return array_key_exists($workspaceName->value, $this->items);
}

/** @return list<string> */
public function toStringArray(): array
{
return array_keys($this->items);
}

public function getIterator(): \Traversable
{
yield from array_values($this->items);
}

public function count(): int
{
return count($this->items);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?php

declare(strict_types=1);

namespace Neos\ContentRepository\Core\Tests\Unit\SharedModel\Workspace;

use Neos\ContentRepository\Core\SharedModel\Workspace\ContentStreamId;
use Neos\ContentRepository\Core\SharedModel\Workspace\Workspace;
use Neos\ContentRepository\Core\SharedModel\Workspace\WorkspaceName;
use Neos\ContentRepository\Core\SharedModel\Workspace\WorkspaceNames;
use Neos\ContentRepository\Core\SharedModel\Workspace\Workspaces;
use Neos\ContentRepository\Core\SharedModel\Workspace\WorkspaceStatus;
use PHPUnit\Framework\TestCase;

class WorkspaceNamesTest extends TestCase
{
/**
* @test
*/
public function contain()
{
$workspaceNames = WorkspaceNames::create(
$nameInstance = WorkspaceName::fromString('foo'),
WorkspaceName::fromString('bar'),
);

self::assertTrue($workspaceNames->contain($nameInstance));
self::assertTrue($workspaceNames->contain(WorkspaceName::fromString('foo')));
self::assertFalse($workspaceNames->contain(WorkspaceName::fromString('not-included')));
}

/**
* @test
*/
public function fromWorkspaces()
{
$workspaces = Workspaces::fromArray([
self::workspace('root', null),
self::workspace('regular', 'root'),
self::workspace('other-root', null),
]);

self::assertEquals(
WorkspaceNames::create(
WorkspaceName::fromString('root'),
WorkspaceName::fromString('regular'),
WorkspaceName::fromString('other-root'),
),
WorkspaceNames::fromWorkspaces($workspaces)
);
}

private static function workspace(string $name): Workspace
{
return Workspace::create(
WorkspaceName::fromString($name),
null,
ContentStreamId::create(),
WorkspaceStatus::UP_TO_DATE,
false
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -136,16 +136,24 @@ public function iExpectTheFollowingWorkspaces(TableNode $payloadTable): void
{
$actualComparableHash = [];
$workspaces = $this->currentContentRepository->findWorkspaces();

// if not specified, ignore
$compareContentStream = in_array('content stream', $payloadTable->getRow(0), true);

foreach ($workspaces as $workspace) {
$actualComparableHash[] = array_map(json_encode(...), [
'name' => $workspace->workspaceName,
'base workspace' => $workspace->baseWorkspaceName,
'status' => $workspace->status,
'content stream' => $workspace->currentContentStreamId,
'publishable changes' => $workspace->hasPublishableChanges()
...($compareContentStream ? ['content stream' => $workspace->currentContentStreamId] : []),
...['publishable changes' => $workspace->hasPublishableChanges()]
]);
}
Assert::assertSame($payloadTable->getHash(), $actualComparableHash);
// ensure the check result does not depend on the workspace ordering
$expected = $payloadTable->getHash();
usort($expected, fn($a, $b) => $a['name'] <=> $b['name']);
usort($actualComparableHash, fn($a, $b) => $a['name'] <=> $b['name']);
Assert::assertSame($expected, $actualComparableHash);
}

/**
Expand Down
37 changes: 37 additions & 0 deletions Neos.Neos/Classes/Command/WorkspaceCommandController.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
namespace Neos\Neos\Command;

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 All @@ -26,6 +27,7 @@
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cli\CommandController;
use Neos\Flow\Cli\Exception\StopCommandException;
use Neos\Flow\Utility\Now;
use Neos\Neos\Domain\Model\WorkspaceClassification;
use Neos\Neos\Domain\Model\WorkspaceDescription;
use Neos\Neos\Domain\Model\WorkspaceRole;
Expand Down Expand Up @@ -56,6 +58,9 @@ class WorkspaceCommandController extends CommandController
#[Flow\Inject]
protected WorkspaceService $workspaceService;

#[Flow\Inject]
protected Now $now;

/**
* Publish changes of a workspace
*
Expand Down Expand Up @@ -524,6 +529,38 @@ 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')
*/
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();
}

$ownerUserNotLoggedInAfter = $this->now->sub($interval);
if ($this->now <= $ownerUserNotLoggedInAfter) {
$this->outputLine('Date interval must not be negative or zero "%s".', [$dateInterval]);
$this->quit();
}

$staleWorkspaceNames = $this->workspaceService->getStalePersonalWorkspaceNames($contentRepositoryId, $ownerUserNotLoggedInAfter);
$this->outputLine('Found %d stale workspaces for users not logged in after %s.', [count($staleWorkspaceNames), $ownerUserNotLoggedInAfter->format('Y-m-d')]);

$this->workspaceService->deleteStalePersonalWorkspaces($contentRepositoryId, $staleWorkspaceNames);
}

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

private function buildWorkspaceRoleSubject(WorkspaceRoleSubjectType $subjectType, string $usernameOrRoleIdentifier): WorkspaceRoleSubject
Expand Down
45 changes: 45 additions & 0 deletions Neos.Neos/Classes/Domain/Model/UserIds.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

namespace Neos\Neos\Domain\Model;

/**
* @implements \IteratorAggregate<int,UserId>
*/
final readonly class UserIds implements \IteratorAggregate
{
/** @param array<string,UserId> $items */
private function __construct(
private array $items
) {
}

public static function create(
UserId ...$items
): self {
$indexed = [];
foreach ($items as $item) {
$indexed[$item->value] = $item;
}
return new self(
$indexed
);
}

public function contain(UserId $userId): bool
{
return array_key_exists($userId->value, $this->items);
}

/** @return list<string> */
public function toStringArray(): array
{
return array_keys($this->items);
}

public function getIterator(): \Traversable
{
yield from array_values($this->items);
}
}
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
23 changes: 23 additions & 0 deletions Neos.Neos/Classes/Domain/Service/UserService.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
use Neos\Neos\Domain\Exception;
use Neos\Neos\Domain\Model\User;
use Neos\Neos\Domain\Model\UserId;
use Neos\Neos\Domain\Model\UserIds;
use Neos\Neos\Domain\Repository\UserRepository;
use Neos\Neos\Domain\Repository\WorkspaceMetadataAndRoleRepository;
use Neos\Party\Domain\Model\AbstractParty;
Expand Down Expand Up @@ -775,6 +776,28 @@ public function getAllRoles(User $user): array
return $roles;
}

public function findUserIdsNotLoggedInAfter(\DateTimeInterface $dateTime): UserIds
{
$userIds = [];
/** @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) {
$userIds[] = $user->getId();
}
}
return UserIds::create(...$userIds);
}

/**
* @param User $user
* @param bool $keepCurrentSession
Expand Down
Loading
Loading