Completed
Push — master ( 122dc2...fa7a2a )
by Matthew
09:15
created

JobManager::updateNearestBatch()   B

Complexity

Conditions 4
Paths 12

Size

Total Lines 37
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 4.0312

Importance

Changes 0
Metric Value
dl 0
loc 37
ccs 21
cts 24
cp 0.875
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 26
nc 12
nop 1
crap 4.0312
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 $formerIdGenerators;
18
    protected static $saveInsertCalled = null;
19
    protected static $resetInsertCalled = null;
20
21 3
    public function countJobsByStatus($objectName, $status, $workerName = null, $method = null)
22
    {
23
        /** @var EntityManager $objectManager */
24 3
        $objectManager = $this->getObjectManager();
25
26
        $qb = $objectManager
27 3
            ->createQueryBuilder()
28 3
            ->select('count(a.id)')
29 3
            ->from($objectName, 'a')
30 3
            ->where('a.status = :status');
31
32 3
        if (null !== $workerName) {
33 1
            $qb->andWhere('a.workerName = :workerName')
34 1
                ->setParameter(':workerName', $workerName);
35
        }
36
37 3
        if (null !== $method) {
38 1
            $qb->andWhere('a.method = :method')
39 1
                ->setParameter(':method', $workerName);
40
        }
41
42 3
        $count = $qb->setParameter(':status', $status)
43 3
            ->getQuery()->getSingleScalarResult();
44
45 3
        if (!$count) {
46 1
            return 0;
47
        }
48
49 3
        return $count;
50
    }
51
52
    /**
53
     * @param string|null $workerName
54
     * @param string|null $method
55
     *
56
     * @return int Count of jobs pruned
57
     */
58 1
    public function pruneErroneousJobs($workerName = null, $method = null)
59
    {
60
        /** @var EntityManager $objectManager */
61 1
        $objectManager = $this->getObjectManager();
62 1
        $qb = $objectManager->createQueryBuilder()->delete($this->getArchiveObjectName(), 'j');
63 1
        $qb->where('j.status = :status')
64 1
            ->setParameter(':status', BaseJob::STATUS_ERROR);
65
66 1
        $this->addWorkerNameCriterion($qb, $workerName, $method);
67 1
        $query = $qb->getQuery();
68
69 1
        return intval($query->execute());
70
    }
71
72 14
    protected function resetSaveOk($function)
73
    {
74 14
        $objectManager = $this->getObjectManager();
75 14
        $splObjectHash = spl_object_hash($objectManager);
76
77 14
        if ('save' === $function) {
78
            $compare = static::$resetInsertCalled;
79
        } else {
80 14
            $compare = static::$saveInsertCalled;
81
        }
82
83 14
        if ($splObjectHash === $compare) {
84
            // Insert SQL is cached...
85
            $msg = "Can't call save and reset within the same process cycle (or using the same EntityManager)";
86
            throw new \Exception($msg);
87
        }
88
89 14
        if ('save' === $function) {
90
            static::$saveInsertCalled = spl_object_hash($objectManager);
91
        } else {
92 14
            static::$resetInsertCalled = spl_object_hash($objectManager);
93
        }
94 14
    }
95
96
    /**
97
     * @param string $workerName
98
     * @param string $method
99
     */
100 8
    protected function addWorkerNameCriterion(QueryBuilder $queryBuilder, $workerName = null, $method = null)
101
    {
102 8
        if (null !== $workerName) {
103 3
            $queryBuilder->andWhere('j.workerName = :workerName')->setParameter(':workerName', $workerName);
104
        }
105
106 8
        if (null !== $method) {
107 2
            $queryBuilder->andWhere('j.method = :method')->setParameter(':method', $method);
108
        }
109 8
    }
110
111 1
    protected function updateExpired($workerName = null, $method = null)
112
    {
113
        /** @var EntityManager $objectManager */
114 1
        $objectManager = $this->getObjectManager();
115 1
        $qb = $objectManager->createQueryBuilder()->update($this->getObjectName(), 'j');
116 1
        $qb->set('j.status', ':newStatus');
117 1
        $qb->where('j.expiresAt <= :expiresAt')
118 1
            ->setParameter(':expiresAt', new \DateTime());
119 1
        $qb->andWhere('j.status = :status')
120 1
            ->setParameter(':status', BaseJob::STATUS_NEW)
121 1
            ->setParameter(':newStatus', Job::STATUS_EXPIRED);
122
123 1
        $this->addWorkerNameCriterion($qb, $workerName, $method);
124 1
        $query = $qb->getQuery();
125
126 1
        return intval($query->execute());
127
    }
128
129
    /**
130
     * Removes archived jobs older than $olderThan.
131
     *
132
     * @param \DateTime $olderThan
133
     */
134 1
    public function pruneArchivedJobs(\DateTime $olderThan)
135
    {
136
        /** @var EntityManager $entityManager */
137 1
        $entityManager = $this->getObjectManager();
138
139 1
        return $this->removeOlderThan($entityManager,
140 1
                $this->getArchiveObjectName(),
141 1
                'updatedAt',
142 1
                $olderThan);
143
    }
144
145 2
    public function getJobCount($workerName = null, $method = null)
146
    {
147
        /** @var EntityManager $objectManager */
148 2
        $objectManager = $this->getObjectManager();
149 2
        $qb = $objectManager->createQueryBuilder();
150
151 2
        $qb = $qb->select('count(j)')->from($this->getObjectName(), 'j');
152
153 2
        $where = 'where';
154 2
        if (null !== $workerName) {
155
            if (null !== $method) {
156
                $qb->where($qb->expr()->andX(
157
                    $qb->expr()->eq('j.workerName', ':workerName'),
158
                                                $qb->expr()->eq('j.method', ':method')
159
                ))
160
                    ->setParameter(':method', $method);
161
            } else {
162
                $qb->where('j.workerName = :workerName');
163
            }
164
            $qb->setParameter(':workerName', $workerName);
165
            $where = 'andWhere';
166 2
        } elseif (null !== $method) {
167
            $qb->where('j.method = :method')->setParameter(':method', $method);
168
            $where = 'andWhere';
169
        }
170
171 2
        $dateTime = new \DateTime();
172
        // Filter
173
        $qb
174 2
            ->$where($qb->expr()->orX(
175 2
                $qb->expr()->isNull('j.whenAt'),
176 2
                                        $qb->expr()->lte('j.whenAt', ':whenAt')
177
            ))
178 2
            ->andWhere($qb->expr()->orX(
179 2
                $qb->expr()->isNull('j.expiresAt'),
180 2
                $qb->expr()->gt('j.expiresAt', ':expiresAt')
181
            ))
182 2
            ->andWhere('j.locked is NULL')
183 2
            ->setParameter(':whenAt', $dateTime)
184 2
            ->setParameter(':expiresAt', $dateTime);
185
186 2
        $query = $qb->getQuery();
187
188 2
        return $query->getSingleScalarResult();
189
    }
190
191
    /**
192
     * Get Jobs statuses.
193
     */
194 2
    public function getStatus()
195
    {
196 2
        $result = [];
197 2
        $this->getStatusByEntityName($this->getObjectName(), $result);
198 2
        $this->getStatusByEntityName($this->getArchiveObjectName(), $result);
199
200 2
        $finalResult = [];
201 2
        foreach ($result as $key => $item) {
202 1
            ksort($item);
203 1
            foreach ($item as $status => $count) {
204 1
                if (isset($finalResult[$key][$status])) {
205
                    $finalResult[$key][$status] += $count;
206
                } else {
207 1
                    $finalResult[$key][$status] = $count;
208
                }
209
            }
210
        }
211
212 2
        return $finalResult;
213
    }
214
215
    /**
216
     * @param string $entityName
217
     */
218 2
    protected function getStatusByEntityName($entityName, array &$result)
219
    {
220
        /** @var EntityManager $objectManager */
221 2
        $objectManager = $this->getObjectManager();
222 2
        $result1 = $objectManager->getRepository($entityName)->createQueryBuilder('j')->select('j.workerName, j.method, j.status, count(j) as c')
223 2
            ->groupBy('j.workerName, j.method, j.status')->getQuery()->getArrayResult();
224
225 2
        foreach ($result1 as $item) {
226 1
            $method = $item['workerName'].'->'.$item['method'].'()';
227 1
            if (!isset($result[$method])) {
228 1
                $result[$method] = [BaseJob::STATUS_NEW => 0,
229 1
                    BaseJob::STATUS_RUNNING => 0,
230 1
                    RetryableJob::STATUS_EXPIRED => 0,
231 1
                    RetryableJob::STATUS_MAX_ERROR => 0,
232 1
                    RetryableJob::STATUS_MAX_STALLED => 0,
233 1
                    RetryableJob::STATUS_MAX_RETRIES => 0,
234 1
                    BaseJob::STATUS_SUCCESS => 0,
235 1
                    BaseJob::STATUS_ERROR => 0, ];
236
            }
237 1
            $result[$method][$item['status']] += intval($item['c']);
238
        }
239 2
    }
240
241
    /**
242
     * Get the next job to run (can be filtered by workername and method name).
243
     *
244
     * @param string $workerName
245
     * @param string $methodName
246
     * @param bool   $prioritize
247
     *
248
     * @return Job|null
249
     */
250 6
    public function getJob($workerName = null, $methodName = null, $prioritize = true, $runId = null)
251
    {
252 6
        $uniqid = uniqid(gethostname().'-'.getmypid(), true);
253 6
        $hash = hash('sha256', $uniqid);
254
255
        /** @var EntityManager $objectManager */
256 6
        $objectManager = $this->getObjectManager();
257
258 6
        $objectManager->beginTransaction();
259
260
        /** @var EntityRepository $repository */
261 6
        $repository = $this->getRepository();
262 6
        $qb = $repository->createQueryBuilder('j');
263 6
        $dateTime = new \DateTime();
264
        $qb
265 6
            ->select('j')
266 6
            ->where('j.status = :status')->setParameter(':status', BaseJob::STATUS_NEW)
267 6
            ->andWhere('j.locked is NULL')
268 6
            ->andWhere($qb->expr()->orX(
269 6
                $qb->expr()->isNull('j.whenAt'),
270 6
                        $qb->expr()->lte('j.whenAt', ':whenAt')
271
            ))
272 6
            ->andWhere($qb->expr()->orX(
273 6
                $qb->expr()->isNull('j.expiresAt'),
274 6
                        $qb->expr()->gt('j.expiresAt', ':expiresAt')
275
            ))
276 6
            ->setParameter(':whenAt', $dateTime)
277 6
            ->setParameter(':expiresAt', $dateTime);
278
279 6
        $this->addWorkerNameCriterion($qb, $workerName, $methodName);
280
281 6
        if ($prioritize) {
282 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...
283
        } else {
284
            $qb->orderBy('j.whenAt', 'ASC');
285
        }
286 6
        $qb->setMaxResults(1);
287
288
        /** @var QueryBuilder $qb */
289 6
        $query = $qb->getQuery();
290 6
        $query->setLockMode(LockMode::PESSIMISTIC_WRITE);
291 6
        $jobs = $query->getResult();
292
293 6
        if ($jobs) {
294
            /** @var Job $job */
295 5
            $job = $jobs[0];
296 5
            if (!$job) {
297
                throw new \Exception("No job found for $hash, even though last result was count ".count($jobs));
298
            }
299 5
            $job->setLocked(true);
300 5
            $job->setLockedAt(new \DateTime());
301 5
            $job->setStatus(BaseJob::STATUS_RUNNING);
302 5
            $job->setRunId($runId);
303 5
            $objectManager->commit();
304 5
            $objectManager->flush();
305
306 5
            return $job;
307
        }
308
309 3
        $objectManager->rollback();
310
311 3
        return null;
312
    }
313
314
    /**
315
     * Tries to update the nearest job as a batch.
316
     *
317
     * @param \Dtc\QueueBundle\Model\Job $job
318
     *
319
     * @return mixed|null
320
     */
321 1
    public function updateNearestBatch(\Dtc\QueueBundle\Model\Job $job)
322
    {
323 1
        $oldJob = null;
324
        do {
325
            try {
326
                /** @var EntityManager $entityManager */
327 1
                $entityManager = $this->getObjectManager();
328 1
                $entityManager->beginTransaction();
329
330
                /** @var QueryBuilder $queryBuilder */
331 1
                $queryBuilder = $this->getRepository()->createQueryBuilder('j');
332 1
                $queryBuilder->select()
333 1
                    ->where('j.crcHash = :crcHash')
334 1
                    ->andWhere('j.status = :status')
335 1
                    ->setParameter(':status', BaseJob::STATUS_NEW)
336 1
                    ->setParameter(':crcHash', $job->getCrcHash())
337 1
                    ->orderBy('j.whenAt', 'ASC')
338 1
                    ->setMaxResults(1);
339 1
                $oldJob = $queryBuilder->getQuery()->getSingleResult();
340
341 1
                if (!$oldJob) {
342
                    return null;
343
                }
344
345 1
                $oldJob->setPriority(max($job->getPriority(), $oldJob->getPriority()));
346 1
                $oldJob->setWhenAt(min($job->getWhenAt(), $oldJob->getWhenAt()));
347
348 1
                $entityManager->persist($oldJob);
349 1
                $entityManager->commit();
350 1
                $entityManager->flush();
351
            } catch (\Exception $exception) {
352
                $entityManager->rollback();
353
            }
354 1
        } while (null === $oldJob);
355
356 1
        return $oldJob;
357
    }
358
}
359