Add cron job for removing expired stored objects

Introduced `RemoveExpiredStoredObjectCronJob` to automate the deletion of expired stored objects every 7 days. Enhanced associated tests and updated relevant interfaces and classes to support the new cron job functionality.
This commit is contained in:
2024-08-28 11:41:43 +02:00
parent c38f7c1179
commit 0db2652f08
10 changed files with 344 additions and 12 deletions

View File

@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\DocStoreBundle\Service\StoredObjectCleaner;
use Chill\DocStoreBundle\Repository\StoredObjectRepositoryInterface;
use Chill\MainBundle\Cron\CronJobInterface;
use Chill\MainBundle\Entity\CronJobExecution;
use Symfony\Component\Clock\ClockInterface;
use Symfony\Component\Messenger\MessageBusInterface;
/**
* Represents a cron job that removes expired stored objects.
*
* This cronjob is executed every 7days, to remove expired stored object. For every
* expired stored object, every version is sent to message bus for async deletion.
*/
final class RemoveExpiredStoredObjectCronJob implements CronJobInterface
{
public const string KEY = 'remove-expired-stored-object';
private const string LAST_DELETED_KEY = 'last-deleted-stored-object-id';
public function __construct(
private readonly ClockInterface $clock,
private readonly MessageBusInterface $messageBus,
private readonly StoredObjectRepositoryInterface $storedObjectRepository
) {}
public function canRun(?CronJobExecution $cronJobExecution): bool
{
if (null === $cronJobExecution) {
return true;
}
return $this->clock->now() >= $cronJobExecution->getLastEnd()->add(new \DateInterval('P7D'));
}
public function getKey(): string
{
return self::KEY;
}
public function run(array $lastExecutionData): ?array
{
$lastDeleted = $lastExecutionData[self::LAST_DELETED_KEY] ?? 0;
foreach ($this->storedObjectRepository->findByExpired($this->clock->now()) as $storedObject) {
foreach ($storedObject->getVersions() as $version) {
$this->messageBus->dispatch(new RemoveOldVersionMessage($version->getId()));
}
$lastDeleted = max($lastDeleted, $storedObject->getId());
}
return [self::LAST_DELETED_KEY => $lastDeleted];
}
}