From 29fec50515e3daa1864913b8b4249198ef92f246 Mon Sep 17 00:00:00 2001 From: Julie Lenaerts Date: Mon, 12 Aug 2024 11:45:27 +0200 Subject: [PATCH] Add cronjob and repository method to find and cancel stale workflows every other day --- .../Workflow/EntityWorkflowRepository.php | 13 +++++ .../Workflow/CancelStaleWorkflowCronJob.php | 55 +++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 src/Bundle/ChillMainBundle/Service/Workflow/CancelStaleWorkflowCronJob.php diff --git a/src/Bundle/ChillMainBundle/Repository/Workflow/EntityWorkflowRepository.php b/src/Bundle/ChillMainBundle/Repository/Workflow/EntityWorkflowRepository.php index f5696d2b9..b6e2e0814 100644 --- a/src/Bundle/ChillMainBundle/Repository/Workflow/EntityWorkflowRepository.php +++ b/src/Bundle/ChillMainBundle/Repository/Workflow/EntityWorkflowRepository.php @@ -198,6 +198,19 @@ class EntityWorkflowRepository implements ObjectRepository return $this->repository->findOneBy($criteria); } + public function findWorkflowsWithoutFinalStepAndOlderThan(\DateTimeImmutable $olderThanDate) + { + $qb = $this->repository->createQueryBuilder('sw'); + + $qb->select('sw.id') + ->where('NOT EXISTS (SELECT 1 FROM chill_main_entity_workflow_step ews WHERE ews.isFinal = TRUE AND ews.entityWorkflow = sw.id)') + ->andWhere(':olderThanDate > ALL (SELECT ews.transitionAt FROM chill_main_entity_workflow_step ews WHERE ews.transitionAt IS NOT NULL AND ews.entityWorkflow = sw.id)') + ->andWhere('sw.createdAt < :olderThanDate') + ->setParameter('olderThanDate', $olderThanDate); + + return $qb->getQuery()->getResult(); + } + public function getClassName(): string { return EntityWorkflow::class; diff --git a/src/Bundle/ChillMainBundle/Service/Workflow/CancelStaleWorkflowCronJob.php b/src/Bundle/ChillMainBundle/Service/Workflow/CancelStaleWorkflowCronJob.php new file mode 100644 index 000000000..2114396f0 --- /dev/null +++ b/src/Bundle/ChillMainBundle/Service/Workflow/CancelStaleWorkflowCronJob.php @@ -0,0 +1,55 @@ +clock->now() >= $cronJobExecution->getLastEnd()->add(new DateInterval('P1D')); + } + + public function getKey(): string + { + return self::KEY; + } + + public function run(array $lastExecutionData): ?array + { + $olderThanDate = $this->clock->now()->sub(new DateInterval(self::KEEP_INTERVAL)); + + $staleWorkflowIds = $this->workflowRepository->findWorkflowsWithoutFinalStepAndOlderThan($olderThanDate); + + $lastCanceled = self::LAST_CANCELED_WORKFLOW; + + foreach ($staleWorkflowIds as $wId) { + $this->messageBus->dispatch(new CancelStaleWorkflow($wId)); + $lastCanceled = $wId; + } + + return [self::LAST_CANCELED_WORKFLOW => $lastCanceled]; + } + +}