Completed
Pull Request — master (#24)
by Matthew
12:26
created

JobManager::getStatusByEntityName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 17
cts 17
cp 1
rs 9.2
c 0
b 0
f 0
cc 3
eloc 16
nc 3
nop 2
crap 3
1
<?php
2
3
namespace Dtc\QueueBundle\ORM;
4
5
use Doctrine\DBAL\LockMode;
6
use Doctrine\ORM\EntityManager;
7
use Doctrine\ORM\EntityRepository;
8
use Doctrine\ORM\QueryBuilder;
9
use Dtc\QueueBundle\Doctrine\BaseJobManager;
10
use Dtc\QueueBundle\Entity\Job;
11
use Dtc\QueueBundle\Model\BaseJob;
12
use Dtc\QueueBundle\Model\RetryableJob;
13
14
class JobManager extends BaseJobManager
15
{
16
    use CommonTrait;
17
    protected static $saveInsertCalled = null;
18
    protected static $resetInsertCalled = null;
19
20 3
    public function countJobsByStatus($objectName, $status, $workerName = null, $method = null)
21
    {
22
        /** @var EntityManager $objectManager */
23 3
        $objectManager = $this->getObjectManager();
24
25
        $qb = $objectManager
26 3
            ->createQueryBuilder()
27 3
            ->select('count(a.id)')
28 3
            ->from($objectName, 'a')
29 3
            ->where('a.status = :status');
30
31 3
        if (null !== $workerName) {
32 1
            $qb->andWhere('a.workerName = :workerName')
33 1
                ->setParameter(':workerName', $workerName);
34
        }
35
36 3
        if (null !== $method) {
37 1
            $qb->andWhere('a.method = :method')
38 1
                ->setParameter(':method', $workerName);
39
        }
40
41 3
        $count = $qb->setParameter(':status', $status)
42 3
            ->getQuery()->getSingleScalarResult();
43
44 3
        if (!$count) {
45 1
            return 0;
46
        }
47
48 3
        return $count;
49
    }
50
51
    /**
52
     * @param string|null $workerName
53
     * @param string|null $method
54
     *
55
     * @return int Count of jobs pruned
56
     */
57 1
    public function pruneErroneousJobs($workerName = null, $method = null)
58
    {
59
        /** @var EntityManager $objectManager */
60 1
        $objectManager = $this->getObjectManager();
61 1
        $qb = $objectManager->createQueryBuilder()->delete($this->getArchiveObjectName(), 'j');
62 1
        $qb->where('j.status = :status')
63 1
            ->setParameter(':status', BaseJob::STATUS_ERROR);
64
65 1
        $this->addWorkerNameCriterion($qb, $workerName, $method);
66 1
        $query = $qb->getQuery();
67
68 1
        return intval($query->execute());
69
    }
70
71 14
    protected function resetSaveOk($function)
72
    {
73 14
        $objectManager = $this->getObjectManager();
74 14
        $splObjectHash = spl_object_hash($objectManager);
75
76 14
        if ('save' === $function) {
77
            $compare = static::$resetInsertCalled;
78
        } else {
79 14
            $compare = static::$saveInsertCalled;
80
        }
81
82 14
        if ($splObjectHash === $compare) {
83
            // Insert SQL is cached...
84
            $msg = "Can't call save and reset within the same process cycle (or using the same EntityManager)";
85
            throw new \Exception($msg);
86
        }
87
88 14
        if ('save' === $function) {
89
            static::$saveInsertCalled = spl_object_hash($objectManager);
90
        } else {
91 14
            static::$resetInsertCalled = spl_object_hash($objectManager);
92
        }
93 14
    }
94
95
    /**
96
     * @param string $workerName
97
     * @param string $method
98
     */
99 8
    protected function addWorkerNameCriterion(QueryBuilder $queryBuilder, $workerName = null, $method = null)
100
    {
101 8
        if (null !== $workerName) {
102 3
            $queryBuilder->andWhere('j.workerName = :workerName')->setParameter(':workerName', $workerName);
103
        }
104
105 8
        if (null !== $method) {
106 2
            $queryBuilder->andWhere('j.method = :method')->setParameter(':method', $method);
107
        }
108 8
    }
109
110 1
    protected function updateExpired($workerName = null, $method = null)
111
    {
112
        /** @var EntityManager $objectManager */
113 1
        $objectManager = $this->getObjectManager();
114 1
        $qb = $objectManager->createQueryBuilder()->update($this->getObjectName(), 'j');
115 1
        $qb->set('j.status', ':newStatus');
116 1
        $qb->where('j.expiresAt <= :expiresAt')
117 1
            ->setParameter(':expiresAt', new \DateTime());
118 1
        $qb->andWhere('j.status = :status')
119 1
            ->setParameter(':status', BaseJob::STATUS_NEW)
120 1
            ->setParameter(':newStatus', Job::STATUS_EXPIRED);
121
122 1
        $this->addWorkerNameCriterion($qb, $workerName, $method);
123 1
        $query = $qb->getQuery();
124
125 1
        return intval($query->execute());
126
    }
127
128 1
    protected function getJobCurrentStatus(\Dtc\QueueBundle\Model\Job $job)
129
    {
130
        /** @var EntityManager $objectManager */
131 1
        $objectManager = $this->getObjectManager();
132 1
        $qb = $objectManager->createQueryBuilder()->select('j.status')->from($this->getObjectName(), 'j');
133 1
        $qb->where('j.id = :id')->setParameter(':id', $job->getId());
134
135 1
        return $qb->getQuery()->getSingleScalarResult();
136
    }
137
138
    /**
139
     * Removes archived jobs older than $olderThan.
140
     *
141
     * @param \DateTime $olderThan
142
     */
143 1
    public function pruneArchivedJobs(\DateTime $olderThan)
144
    {
145 1
        return $this->removeOlderThan($this->getArchiveObjectName(),
146 1
                'updatedAt',
147 1
                $olderThan);
148
    }
149
150 2
    public function getJobCount($workerName = null, $method = null)
151
    {
152
        /** @var EntityManager $objectManager */
153 2
        $objectManager = $this->getObjectManager();
154 2
        $qb = $objectManager->createQueryBuilder();
155
156 2
        $qb = $qb->select('count(j)')->from($this->getObjectName(), 'j');
157
158 2
        $where = 'where';
159 2
        if (null !== $workerName) {
160
            if (null !== $method) {
161
                $qb->where($qb->expr()->andX(
162
                    $qb->expr()->eq('j.workerName', ':workerName'),
163
                                                $qb->expr()->eq('j.method', ':method')
164
                ))
165
                    ->setParameter(':method', $method);
166
            } else {
167
                $qb->where('j.workerName = :workerName');
168
            }
169
            $qb->setParameter(':workerName', $workerName);
170
            $where = 'andWhere';
171 2
        } elseif (null !== $method) {
172
            $qb->where('j.method = :method')->setParameter(':method', $method);
173
            $where = 'andWhere';
174
        }
175
176 2
        $dateTime = new \DateTime();
177
        // Filter
178
        $qb
179 2
            ->$where($qb->expr()->orX(
180 2
                $qb->expr()->isNull('j.whenAt'),
181 2
                                        $qb->expr()->lte('j.whenAt', ':whenAt')
182
            ))
183 2
            ->andWhere($qb->expr()->orX(
184 2
                $qb->expr()->isNull('j.expiresAt'),
185 2
                $qb->expr()->gt('j.expiresAt', ':expiresAt')
186
            ))
187 2
            ->andWhere('j.locked is NULL')
188 2
            ->setParameter(':whenAt', $dateTime)
189 2
            ->setParameter(':expiresAt', $dateTime);
190
191 2
        $query = $qb->getQuery();
192
193 2
        return $query->getSingleScalarResult();
194
    }
195
196
    /**
197
     * For ORM it's prudent to wrap things in a transaction.
198
     *
199
     * @param $i
200
     * @param $count
201
     * @param array $stalledJobs
202
     * @param $countProcessed
203
     */
204 1
    protected function runStalledLoop($i, $count, array $stalledJobs, &$countProcessed)
205
    {
206
        /** @var EntityManager $objectManager */
207 1
        $objectManager = $this->getObjectManager();
208
        try {
209 1
            $objectManager->beginTransaction();
210 1
            parent::runStalledLoop($i, $count, $stalledJobs, $countProcessed);
211 1
            $objectManager->commit();
212
        } catch (\Exception $exception) {
213
            $objectManager->rollback();
214
215
            // Try again
216
            parent::runStalledLoop($i, $count, $stalledJobs, $countProcessed);
217
        }
218 1
    }
219
220
    /**
221
     * Get Jobs statuses.
222
     */
223 2
    public function getStatus()
224
    {
225 2
        $result = [];
226 2
        $this->getStatusByEntityName($this->getObjectName(), $result);
227 2
        $this->getStatusByEntityName($this->getArchiveObjectName(), $result);
228
229 2
        $finalResult = [];
230 2
        foreach ($result as $key => $item) {
231 1
            ksort($item);
232 1
            foreach ($item as $status => $count) {
233 1
                if (isset($finalResult[$key][$status])) {
234
                    $finalResult[$key][$status] += $count;
235
                } else {
236 1
                    $finalResult[$key][$status] = $count;
237
                }
238
            }
239
        }
240
241 2
        return $finalResult;
242
    }
243
244
    /**
245
     * @param string $entityName
246
     */
247 2
    protected function getStatusByEntityName($entityName, array &$result)
248
    {
249
        /** @var EntityManager $objectManager */
250 2
        $objectManager = $this->getObjectManager();
251 2
        $result1 = $objectManager->getRepository($entityName)->createQueryBuilder('j')->select('j.workerName, j.method, j.status, count(j) as c')
252 2
            ->groupBy('j.workerName, j.method, j.status')->getQuery()->getArrayResult();
253
254 2
        foreach ($result1 as $item) {
255 1
            $method = $item['workerName'].'->'.$item['method'].'()';
256 1
            if (!isset($result[$method])) {
257 1
                $result[$method] = [BaseJob::STATUS_NEW => 0,
258 1
                    BaseJob::STATUS_RUNNING => 0,
259 1
                    RetryableJob::STATUS_EXPIRED => 0,
260 1
                    RetryableJob::STATUS_MAX_ERROR => 0,
261 1
                    RetryableJob::STATUS_MAX_STALLED => 0,
262 1
                    RetryableJob::STATUS_MAX_RETRIES => 0,
263 1
                    BaseJob::STATUS_SUCCESS => 0,
264 1
                    BaseJob::STATUS_ERROR => 0, ];
265
            }
266 1
            $result[$method][$item['status']] += intval($item['c']);
267
        }
268 2
    }
269
270
    /**
271
     * Get the next job to run (can be filtered by workername and method name).
272
     *
273
     * @param string $workerName
274
     * @param string $methodName
275
     * @param bool   $prioritize
276
     *
277
     * @return Job|null
278
     */
279 6
    public function getJob($workerName = null, $methodName = null, $prioritize = true, $runId = null)
280
    {
281 6
        $uniqid = uniqid(gethostname().'-'.getmypid(), true);
282 6
        $hash = hash('sha256', $uniqid);
283
284
        /** @var EntityManager $objectManager */
285 6
        $objectManager = $this->getObjectManager();
286
287 6
        $objectManager->beginTransaction();
288
289
        /** @var EntityRepository $repository */
290 6
        $repository = $this->getRepository();
291 6
        $qb = $repository->createQueryBuilder('j');
292 6
        $dateTime = new \DateTime();
293
        $qb
294 6
            ->select('j')
295 6
            ->where('j.status = :status')->setParameter(':status', BaseJob::STATUS_NEW)
296 6
            ->andWhere('j.locked is NULL')
297 6
            ->andWhere($qb->expr()->orX(
298 6
                $qb->expr()->isNull('j.whenAt'),
299 6
                        $qb->expr()->lte('j.whenAt', ':whenAt')
300
            ))
301 6
            ->andWhere($qb->expr()->orX(
302 6
                $qb->expr()->isNull('j.expiresAt'),
303 6
                        $qb->expr()->gt('j.expiresAt', ':expiresAt')
304
            ))
305 6
            ->setParameter(':whenAt', $dateTime)
306 6
            ->setParameter(':expiresAt', $dateTime);
307
308 6
        $this->addWorkerNameCriterion($qb, $workerName, $methodName);
309
310 6
        if ($prioritize) {
311 6
            $qb->add('orderBy', 'j.priority DESC, j.whenAt ASC');
0 ignored issues
show
Documentation introduced by
'j.priority DESC, j.whenAt ASC' is of type string, but the function expects a object<Doctrine\ORM\Query\Expr\Base>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
312
        } else {
313
            $qb->orderBy('j.whenAt', 'ASC');
314
        }
315 6
        $qb->setMaxResults(1);
316
317
        /** @var QueryBuilder $qb */
318 6
        $query = $qb->getQuery();
319 6
        $query->setLockMode(LockMode::PESSIMISTIC_WRITE);
320 6
        $jobs = $query->getResult();
321
322 6
        if ($jobs) {
323
            /** @var Job $job */
324 5
            $job = $jobs[0];
325 5
            if (!$job) {
326
                throw new \Exception("No job found for $hash, even though last result was count ".count($jobs));
327
            }
328 5
            $job->setLocked(true);
329 5
            $job->setLockedAt(new \DateTime());
330 5
            $job->setStatus(BaseJob::STATUS_RUNNING);
331 5
            $job->setRunId($runId);
332 5
            $objectManager->commit();
333 5
            $objectManager->flush();
334
335 5
            return $job;
336
        }
337
338 3
        $objectManager->rollback();
339
340 3
        return null;
341
    }
342
343
    /**
344
     * Tries to update the nearest job as a batch.
345
     *
346
     * @param \Dtc\QueueBundle\Model\Job $job
347
     *
348
     * @return mixed|null
349
     */
350 1
    public function updateNearestBatch(\Dtc\QueueBundle\Model\Job $job)
351
    {
352 1
        $oldJob = null;
353
        do {
354
            try {
355
                /** @var EntityManager $entityManager */
356 1
                $entityManager = $this->getObjectManager();
357 1
                $entityManager->beginTransaction();
358
359
                /** @var QueryBuilder $queryBuilder */
360 1
                $queryBuilder = $this->getRepository()->createQueryBuilder('j');
361 1
                $queryBuilder->select()
362 1
                    ->where('j.crcHash = :crcHash')
363 1
                    ->andWhere('j.status = :status')
364 1
                    ->setParameter(':status', BaseJob::STATUS_NEW)
365 1
                    ->setParameter(':crcHash', $job->getCrcHash())
366 1
                    ->orderBy('j.whenAt', 'ASC')
367 1
                    ->setMaxResults(1);
368 1
                $oldJob = $queryBuilder->getQuery()->getSingleResult();
369
370 1
                if (!$oldJob) {
371
                    return null;
372
                }
373
374 1
                $oldJob->setPriority(max($job->getPriority(), $oldJob->getPriority()));
375 1
                $oldJob->setWhenAt(min($job->getWhenAt(), $oldJob->getWhenAt()));
376
377 1
                $entityManager->persist($oldJob);
378 1
                $entityManager->commit();
379 1
                $this->flush();
380
            } catch (\Exception $exception) {
381
                $entityManager->rollback();
382
            }
383 1
        } while (null === $oldJob);
384
385 1
        return $oldJob;
386
    }
387
}
388