wse-1.0.x-dev/modules/wse_task_monitor/src/WorkspaceTaskRepository.php
modules/wse_task_monitor/src/WorkspaceTaskRepository.php
<?php
declare(strict_types=1);
namespace Drupal\wse_task_monitor;
use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
/**
* Repository for workspace task storage operations using key-value store.
*/
class WorkspaceTaskRepository implements WorkspaceTaskRepositoryInterface {
/**
* Default expiration time for running tasks (1 hour).
*/
protected const DEFAULT_EXPIRE = 3600;
/**
* Expiration time for completed tasks (5 minutes).
*/
protected const COMPLETED_EXPIRE = 300;
/**
* The key-value store for task persistence.
*/
protected KeyValueStoreExpirableInterface $keyValueStore;
public function __construct(
protected readonly UuidInterface $uuidGenerator,
#[Autowire(service: 'keyvalue.expirable')]
protected readonly KeyValueExpirableFactoryInterface $keyValueExpirable,
) {
$this->keyValueStore = $keyValueExpirable->get('wse.workspace_task');
}
/**
* Generates a new unique task ID.
*
* @return string
* The generated task ID.
*/
public function generateTaskId(): string {
return $this->uuidGenerator->generate();
}
/**
* {@inheritdoc}
*/
public function save(WorkspaceTask $task): void {
$expireTime = $task->isFinished() ? self::COMPLETED_EXPIRE : self::DEFAULT_EXPIRE;
$this->keyValueStore->setWithExpire($task->getId(), $task, $expireTime);
}
/**
* {@inheritdoc}
*/
public function find(string $taskId): ?WorkspaceTask {
return $this->keyValueStore->get($taskId);
}
/**
* {@inheritdoc}
*/
public function delete(string $taskId): void {
$this->keyValueStore->delete($taskId);
}
/**
* {@inheritdoc}
*/
public function findAll(?string $workspaceId = NULL, ?TaskStatus $status = NULL): array {
$tasks = [];
foreach ($this->keyValueStore->getAll() as $taskId => $task) {
if ($workspaceId !== NULL && $task->getWorkspaceId() !== $workspaceId) {
continue;
}
if ($status !== NULL && $task->getStatus() !== $status) {
continue;
}
$tasks[$taskId] = $task;
}
return $tasks;
}
/**
* {@inheritdoc}
*/
public function findByHandlerClass(string $workspaceId, string $handlerClass, TaskStatus $status): array {
$tasks = [];
foreach ($this->keyValueStore->getAll() as $taskId => $task) {
if ($task->getWorkspaceId() !== $workspaceId ||
$task->getHandlerClass() !== $handlerClass ||
$task->getStatus() !== $status) {
continue;
}
$tasks[$taskId] = $task;
}
return $tasks;
}
}
