This repository has been archived by the owner on Jul 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 31
/
DoctrineQueue.php
452 lines (390 loc) · 16.1 KB
/
DoctrineQueue.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<?php
namespace SlmQueueDoctrine\Queue;
use SlmQueueDoctrine\Exception\LogicException;
use SlmQueueDoctrine\Exception\RuntimeException;
use SlmQueueDoctrine\Exception\JobNotFoundException;
use DateInterval;
use DateTime;
use DateTimeInterface;
use DateTimeZone;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Exception as DBALException;
use Doctrine\DBAL\LockMode;
use Doctrine\DBAL\Types\Types;
use SlmQueue\Job\JobInterface;
use SlmQueue\Job\JobPluginManager;
use SlmQueue\Queue\AbstractQueue;
use SlmQueueDoctrine\Options\DoctrineOptions;
use SlmQueueDoctrine\Worker\DoctrineWorker;
class DoctrineQueue extends AbstractQueue implements DoctrineQueueInterface
{
protected static $defaultWorkerName = DoctrineWorker::class;
public const STATUS_PENDING = 1;
public const STATUS_RUNNING = 2;
public const STATUS_DELETED = 3;
public const STATUS_BURIED = 4;
public const LIFETIME_DISABLED = 0;
public const LIFETIME_UNLIMITED = -1;
private const DATABASE_PLATFORM_POSTGRES = 'postgresql';
public const DEFAULT_PRIORITY = 1024;
/**
* Options for this queue
*/
protected DoctrineOptions $options;
/**
* Used to synchronize time calculations
*/
private DateTimeInterface $now;
private Connection $connection;
public function __construct(
Connection $connection,
DoctrineOptions $options,
string $name,
JobPluginManager $jobPluginManager
) {
$this->connection = $connection;
$this->options = clone $options;
parent::__construct($name, $jobPluginManager);
}
public function getOptions(): DoctrineOptions
{
return $this->options;
}
/**
* Valid options are:
* - priority: the lower the priority is, the sooner the job get popped from the queue (default to 1024)
*
* Note : see DoctrineQueue::parseOptionsToDateTime for schedule and delay options
*/
public function push(JobInterface $job, array $options = []): void
{
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$this->now = new DateTime(
date('Y-m-d H:i:s.' . $micro, (int)$time),
new DateTimeZone(date_default_timezone_get())
);
$scheduled = $this->parseOptionsToDateTime($options);
$this->connection->insert($this->options->getTableName(), [
'queue' => $this->getName(),
'status' => self::STATUS_PENDING,
'created' => $this->now->format('Y-m-d H:i:s.u'),
'data' => $this->serializeJob($job),
'scheduled' => $scheduled->format('Y-m-d H:i:s.u'),
'priority' => isset($options['priority']) ? $options['priority'] : self::DEFAULT_PRIORITY,
], [
Types::STRING,
Types::SMALLINT,
Types::STRING,
Types::TEXT,
Types::STRING,
Types::INTEGER,
]);
if (self::DATABASE_PLATFORM_POSTGRES == $this->connection->getDatabasePlatform()->getName()) {
$id = $this->connection->lastInsertId($this->options->getTableName() . '_id_seq');
} else {
$id = $this->connection->lastInsertId();
}
$job->setId($id);
}
/**
* {@inheritDoc}
*/
public function pop(array $options = []): ?JobInterface
{
// First run garbage collection
$this->purge();
$conn = $this->connection;
$conn->beginTransaction();
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$this->now = new DateTime(
date('Y-m-d H:i:s.' . $micro, (int)$time),
new DateTimeZone(date_default_timezone_get())
);
try {
$platform = $conn->getDatabasePlatform();
$queryBuilder = $conn->createQueryBuilder();
$queryBuilder
->select('*')
->from($platform->appendLockHint($this->options->getTableName(), LockMode::PESSIMISTIC_WRITE))
->where('status = ?')
->andWhere('queue = ?')
->andWhere('scheduled <= ?')
->addOrderBy('priority', 'ASC')
->addOrderBy('scheduled', 'ASC')
->setParameter(0, static::STATUS_PENDING)
->setParameter(1, $this->getName())
->setParameter(2, $this->now->format('Y-m-d H:i:s.u'))
->setMaxResults(1);
// Modify the query so it supports row locking (if applicable for database provider)
// @see https://github.com/doctrine/doctrine2/blob/5f3afa4c4ffb8cb49870d794cc7daf6a49406966/lib/Doctrine/ORM/Query/SqlWalker.php#L556-L558
$sql = $queryBuilder->getSQL() . ' ' . $platform->getWriteLockSQL();
$query = $this->connection->executeQuery(
$sql,
$queryBuilder->getParameters(),
$queryBuilder->getParameterTypes()
);
if ($row = $query->fetch()) {
$update = 'UPDATE ' . $this->options->getTableName() . ' ' .
'SET status = ?, executed = ? ' .
'WHERE id = ? AND status = ?';
$rows = $conn->executeUpdate(
$update,
[
static::STATUS_RUNNING,
$this->now->format('Y-m-d H:i:s.u'),
$row['id'],
static::STATUS_PENDING
],
[Types::SMALLINT, Types::STRING, Types::INTEGER, Types::SMALLINT]
);
if ($rows !== 1) {
throw new LogicException("Race-condition detected while updating item in queue.");
}
}
$conn->commit();
} catch (DBALException $e) {
$conn->rollback();
$conn->close();
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}
if ($row === false) {
return null;
}
// Add job ID to meta data
return $this->unserializeJob($row['data'], ['__id__' => $row['id']]);
}
/**
* {@inheritDoc}
*
* Note: When $deletedLifetime === 0 the job will be deleted immediately
*/
public function delete(JobInterface $job, array $options = []): void
{
if ($this->options->getDeletedLifetime() === static::LIFETIME_DISABLED) {
$this->connection->delete($this->options->getTableName(), ['id' => $job->getId()]);
} else {
$update = 'UPDATE ' . $this->options->getTableName() . ' ' .
'SET status = ?, finished = ? ' .
'WHERE id = ? AND status = ?';
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$this->now = new DateTime(
date('Y-m-d H:i:s.' . $micro, (int)$time),
new DateTimeZone(date_default_timezone_get())
);
$rows = $this->connection->executeUpdate(
$update,
[
static::STATUS_DELETED,
$this->now->format('Y-m-d H:i:s.u'),
$job->getId(),
static::STATUS_RUNNING
],
[Types::SMALLINT, Types::STRING, Types::INTEGER, Types::SMALLINT]
);
if ($rows !== 1) {
throw new LogicException("Race-condition detected while updating item in queue.");
}
}
}
/**
* {@inheritDoc}
*
* Note: When $buriedLifetime === 0 the job will be deleted immediately
*/
public function bury(JobInterface $job, array $options = []): void
{
if ($this->options->getBuriedLifetime() === static::LIFETIME_DISABLED) {
$this->connection->delete($this->options->getTableName(), ['id' => $job->getId()]);
} else {
$message = isset($options['message']) ? $options['message'] : null;
$trace = isset($options['trace']) ? $options['trace'] : null;
$update = 'UPDATE ' . $this->options->getTableName() . ' ' .
'SET status = ?, finished = ?, message = ?, trace = ? ' .
'WHERE id = ? AND status = ?';
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$this->now = new DateTime(
date('Y-m-d H:i:s.' . $micro, (int)$time),
new DateTimeZone(date_default_timezone_get())
);
$rows = $this->connection->executeUpdate(
$update,
[
static::STATUS_BURIED,
$this->now->format('Y-m-d H:i:s.u'),
$message,
$trace,
$job->getId(),
static::STATUS_RUNNING
],
[Types::SMALLINT, Types::STRING, Types::STRING, Types::TEXT, Types::INTEGER, Types::SMALLINT]
);
if ($rows !== 1) {
throw new LogicException("Race-condition detected while updating item in queue.");
}
}
}
/**
* {@inheritDoc}
*/
public function recover(int $executionTime): int
{
$executedLifetime = $this->parseOptionsToDateTime(['delay' => - ($executionTime * 60)]);
$update = 'UPDATE ' . $this->options->getTableName() . ' ' .
'SET status = ? ' .
'WHERE executed < ? AND status = ? AND queue = ? AND finished IS NULL';
return $this->connection->executeUpdate(
$update,
[
static::STATUS_PENDING,
$executedLifetime->format('Y-m-d H:i:s.u'),
static::STATUS_RUNNING,
$this->getName()
],
[Types::SMALLINT, Types::STRING, Types::SMALLINT, Types::STRING]
);
}
/**
* Create a concrete instance of a job from the queue
*/
public function peek(int $id): JobInterface
{
$sql = 'SELECT * FROM ' . $this->options->getTableName() . ' WHERE id = ?';
$row = $this->connection->fetchAssociative($sql, [$id], [Types::SMALLINT]);
if (!$row) {
throw new JobNotFoundException(sprintf("Job with id '%s' does not exists.", $id));
}
// Add job ID to meta data
return $this->unserializeJob($row['data'], ['__id__' => $row['id']]);
}
/**
* Reschedules a specific running job
*
* Note : see DoctrineQueue::parseOptionsToDateTime for schedule and delay options
*/
public function release(JobInterface $job, array $options = []): void
{
$scheduled = $this->parseOptionsToDateTime($options);
$update = 'UPDATE ' . $this->options->getTableName() . ' ' .
'SET status = ?, finished = ? , scheduled = ?, data = ? ' .
'WHERE id = ? AND status = ?';
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$rows = $this->connection->executeUpdate(
$update,
[
static::STATUS_PENDING,
$this->now->format('Y-m-d H:i:s.u'),
$scheduled->format('Y-m-d H:i:s.u'),
$this->serializeJob($job),
$job->getId(),
static::STATUS_RUNNING,
],
[Types::SMALLINT, Types::STRING, Types::STRING, Types::STRING, Types::INTEGER, Types::SMALLINT]
);
if ($rows !== 1) {
throw new LogicException("Race-condition detected while updating item in queue.");
}
}
/**
* Parses options to a datetime object
*
* valid options keys:
*
* scheduled: the time when the job will be scheduled to run next
* - numeric string or integer - interpreted as a timestamp
* - string parserable by the DateTime object
* - DateTime instance
* delay: the delay before a job become available to be popped (defaults to 0 - no delay -)
* - numeric string or integer - interpreted as seconds
* - string parserable (ISO 8601 duration) by DateTimeInterval::__construct
* - string parserable (relative parts) by DateTimeInterval::createFromDateString
* - DateTimeInterval instance
*
* @see http://en.wikipedia.org/wiki/Iso8601#Durations
* @see http://www.php.net/manual/en/datetime.formats.relative.php
*/
protected function parseOptionsToDateTime(array $options): DateTime
{
$time = microtime(true);
$micro = sprintf("%06d", ($time - floor($time)) * 1000000);
$this->now = new DateTime(
date('Y-m-d H:i:s.' . $micro, (int)$time),
new DateTimeZone(date_default_timezone_get())
);
$scheduled = clone ($this->now);
if (isset($options['scheduled'])) {
switch (true) {
case is_numeric($options['scheduled']):
$scheduled = new DateTime(
sprintf("@%d", (int) $options['scheduled']),
new DateTimeZone(date_default_timezone_get())
);
break;
case is_string($options['scheduled']):
$scheduled = new DateTime($options['scheduled'], new DateTimeZone(date_default_timezone_get()));
break;
case $options['scheduled'] instanceof DateTime:
$scheduled = $options['scheduled'];
break;
}
}
if (isset($options['delay'])) {
switch (true) {
case is_numeric($options['delay']):
$delay = new DateInterval(sprintf("PT%dS", abs((int) $options['delay'])));
$delay->invert = ($options['delay'] < 0) ? 1 : 0;
break;
case is_string($options['delay']):
try {
// first try ISO 8601 duration specification
$delay = new DateInterval($options['delay']);
} catch (\Exception $e) {
// then try normal date parser
$delay = DateInterval::createFromDateString($options['delay']);
}
break;
case $options['delay'] instanceof DateInterval:
$delay = $options['delay'];
break;
default:
$delay = null;
}
if ($delay instanceof DateInterval) {
$scheduled->add($delay);
}
}
return $scheduled;
}
/**
* Cleans old jobs in the table according to the configured lifetime of successful and failed jobs.
*/
protected function purge(): void
{
if ($this->options->getBuriedLifetime() > static::LIFETIME_UNLIMITED) {
$options = ['delay' => - ($this->options->getBuriedLifetime() * 60)];
$buriedLifetime = $this->parseOptionsToDateTime($options);
$delete = 'DELETE FROM ' . $this->options->getTableName() . ' ' .
'WHERE finished < ? AND status = ? AND queue = ? AND finished IS NOT NULL';
$this->connection->executeUpdate(
$delete,
[$buriedLifetime->format('Y-m-d H:i:s.u'), static::STATUS_BURIED, $this->getName()],
[Types::STRING, Types::INTEGER, Types::STRING]
);
}
if ($this->options->getDeletedLifetime() > static::LIFETIME_UNLIMITED) {
$options = ['delay' => - ($this->options->getDeletedLifetime() * 60)];
$deletedLifetime = $this->parseOptionsToDateTime($options);
$delete = 'DELETE FROM ' . $this->options->getTableName() . ' ' .
'WHERE finished < ? AND status = ? AND queue = ? AND finished IS NOT NULL';
$this->connection->executeUpdate(
$delete,
[$deletedLifetime->format('Y-m-d H:i:s.u'), static::STATUS_DELETED, $this->getName()],
[Types::STRING, Types::INTEGER, Types::STRING]
);
}
}
}