forked from traderinteractive/mongo-queue-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Queue.php
469 lines (398 loc) · 17.5 KB
/
Queue.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
<?php
/**
* Defines the DominionEnterprises\Mongo\Queue class.
*/
namespace DominionEnterprises\Mongo;
/**
* Abstraction of mongo db collection as priority queue.
*
* Tied priorities are ordered by time. So you may use a single priority for normal queuing (default args exist for this purpose).
* Using a random priority achieves random get()
*/
final class Queue
{
const MONGO_INT32_MAX = 2147483647;//2147483648 can overflow in php mongo without using the MongoInt64
/**
* mongo collection to use for queue.
*
* @var \MongoCollection
*/
private $_collection;
/**
* Construct queue.
*
* @param string $url the mongo url
* @param string $db the mongo db name
* @param string $collection the collection name to use for the queue
*
* @throws \InvalidArgumentException $url, $db or $collection was not a string
*/
public function __construct($url, $db, $collection)
{
if (!is_string($url)) {
throw new \InvalidArgumentException('$url was not a string');
}
if (!is_string($db)) {
throw new \InvalidArgumentException('$db was not a string');
}
if (!is_string($collection)) {
throw new \InvalidArgumentException('$collection was not a string');
}
$mongo = new \MongoClient($url);
$mongoDb = $mongo->selectDB($db);
$this->_collection = $mongoDb->selectCollection($collection);
}
/**
* Ensure an index for the get() method.
*
* @param array $beforeSort fields in get() call to index before the sort field in same format as \MongoCollection::ensureIndex()
* @param array $afterSort fields in get() call to index after the sort field in same format as \MongoCollection::ensureIndex()
*
* @return void
*
* @throws \InvalidArgumentException value of $beforeSort or $afterSort is not 1 or -1 for ascending and descending
* @throws \InvalidArgumentException key in $beforeSort or $afterSort was not a string
*/
public function ensureGetIndex(array $beforeSort = array(), array $afterSort = array())
{
//using general rule: equality, sort, range or more equality tests in that order for index
$completeFields = array('running' => 1);
foreach ($beforeSort as $key => $value) {
if (!is_string($key)) {
throw new \InvalidArgumentException('key in $beforeSort was not a string');
}
if ($value !== 1 && $value !== -1) {
throw new \InvalidArgumentException('value of $beforeSort is not 1 or -1 for ascending and descending');
}
$completeFields["payload.{$key}"] = $value;
}
$completeFields['priority'] = 1;
$completeFields['created'] = 1;
foreach ($afterSort as $key => $value) {
if (!is_string($key)) {
throw new \InvalidArgumentException('key in $afterSort was not a string');
}
if ($value !== 1 && $value !== -1) {
throw new \InvalidArgumentException('value of $afterSort is not 1 or -1 for ascending and descending');
}
$completeFields["payload.{$key}"] = $value;
}
$completeFields['earliestGet'] = 1;
//for the main query in get()
$this->_ensureIndex($completeFields);
//for the stuck messages query in get()
$this->_ensureIndex(array('running' => 1, 'resetTimestamp' => 1));
}
/**
* Ensure an index for the count() method.
* Is a no-op if the generated index is a prefix of an existing one. If you have a similar ensureGetIndex call, call it first.
*
* @param array $fields fields in count() call to index in same format as \MongoCollection::ensureIndex()
* @param bool $includeRunning whether to include the running field in the index
*
* @return void
*
* @throws \InvalidArgumentException $includeRunning was not a boolean
* @throws \InvalidArgumentException key in $fields was not a string
* @throws \InvalidArgumentException value of $fields is not 1 or -1 for ascending and descending
*/
public function ensureCountIndex(array $fields, $includeRunning)
{
if (!is_bool($includeRunning)) {
throw new \InvalidArgumentException('$includeRunning was not a boolean');
}
$completeFields = array();
if ($includeRunning) {
$completeFields['running'] = 1;
}
foreach ($fields as $key => $value) {
if (!is_string($key)) {
throw new \InvalidArgumentException('key in $fields was not a string');
}
if ($value !== 1 && $value !== -1) {
throw new \InvalidArgumentException('value of $fields is not 1 or -1 for ascending and descending');
}
$completeFields["payload.{$key}"] = $value;
}
$this->_ensureIndex($completeFields);
}
/**
* Get a non running message from the queue.
*
* @param array $query in same format as \MongoCollection::find() where top level fields do not contain operators.
* Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}
* @param int $runningResetDuration second duration the message can stay unacked before it resets and can be retreived again.
* @param int $waitDurationInMillis millisecond duration to wait for a message.
* @param int $pollDurationInMillis millisecond duration to wait between polls.
*
* @return array|null the message or null if one is not found
*
* @throws \InvalidArgumentException $runningResetDuration, $waitDurationInMillis or $pollDurationInMillis was not an int
* @throws \InvalidArgumentException key in $query was not a string
*/
public function get(array $query, $runningResetDuration, $waitDurationInMillis = 3000, $pollDurationInMillis = 200)
{
if (!is_int($runningResetDuration)) {
throw new \InvalidArgumentException('$runningResetDuration was not an int');
}
if (!is_int($waitDurationInMillis)) {
throw new \InvalidArgumentException('$waitDurationInMillis was not an int');
}
if (!is_int($pollDurationInMillis)) {
throw new \InvalidArgumentException('$pollDurationInMillis was not an int');
}
if ($pollDurationInMillis < 0) {
$pollDurationInMillis = 0;
}
//reset stuck messages
$this->_collection->update(
array('running' => true, 'resetTimestamp' => array('$lte' => new \MongoDate())),
array('$set' => array('running' => false)),
array('multiple' => true)
);
$completeQuery = array('running' => false);
foreach ($query as $key => $value) {
if (!is_string($key)) {
throw new \InvalidArgumentException('key in $query was not a string');
}
$completeQuery["payload.{$key}"] = $value;
}
$completeQuery['earliestGet'] = array('$lte' => new \MongoDate());
$resetTimestamp = time() + $runningResetDuration;
//ints overflow to floats
if (!is_int($resetTimestamp)) {
$resetTimestamp = $runningResetDuration > 0 ? self::MONGO_INT32_MAX : 0;
}
$update = array('$set' => array('resetTimestamp' => new \MongoDate($resetTimestamp), 'running' => true));
$fields = array('payload' => 1);
$options = array('sort' => array('priority' => 1, 'created' => 1));
//ints overflow to floats, should be fine
$end = microtime(true) + ($waitDurationInMillis / 1000.0);
$sleepTime = $pollDurationInMillis * 1000;
//ints overflow to floats and already checked $pollDurationInMillis was positive
if (!is_int($sleepTime)) {
//ignore since testing a giant sleep takes too long
//@codeCoverageIgnoreStart
$sleepTime = PHP_INT_MAX;
} //@codeCoverageIgnoreEnd
while (true) {
$message = $this->_collection->findAndModify($completeQuery, $update, $fields, $options);
//checking if _id exist because findAndModify doesnt seem to return null when it can't match the query
if (array_key_exists('_id', $message)) {
//id on left of union operator so a possible id in payload doesnt wipe it out the generated one
return array('id' => $message['_id']) + $message['payload'];
}
if (microtime(true) >= $end) {
return null;
}
usleep($sleepTime);
}
//ignore since always return from the function from the while loop
//@codeCoverageIgnoreStart
}
//@codeCoverageIgnoreEnd
/**
* Count queue messages.
*
* @param array $query in same format as \MongoCollection::find() where top level fields do not contain operators.
* Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}
* @param bool|null $running query a running message or not or all
*
* @return int the count
*
* @throws \InvalidArgumentException $running was not null and not a bool
* @throws \InvalidArgumentException key in $query was not a string
*/
public function count(array $query, $running = null)
{
if ($running !== null && !is_bool($running)) {
throw new \InvalidArgumentException('$running was not null and not a bool');
}
$totalQuery = array();
if ($running !== null) {
$totalQuery['running'] = $running;
}
foreach ($query as $key => $value) {
if (!is_string($key)) {
throw new \InvalidArgumentException('key in $query was not a string');
}
$totalQuery["payload.{$key}"] = $value;
}
return $this->_collection->count($totalQuery);
}
/**
* Acknowledge a message was processed and remove from queue.
*
* @param array $message message received from get()
*
* @return void
*
* @throws \InvalidArgumentException $message does not have a field "id" that is a MongoId
*/
public function ack(array $message)
{
$id = null;
if (array_key_exists('id', $message)) {
$id = $message['id'];
}
if (!($id instanceof \MongoId)) {
throw new \InvalidArgumentException('$message does not have a field "id" that is a MongoId');
}
$this->_collection->remove(array('_id' => $id));
}
/**
* Atomically acknowledge and send a message to the queue.
*
* @param array $message the message to ack received from get()
* @param array $payload the data to store in the message to send. Data is handled same way as \MongoCollection::insert()
* @param int $earliestGet earliest unix timestamp the message can be retreived.
* @param float $priority priority for order out of get(). 0 is higher priority than 1
* @param bool $newTimestamp true to give the payload a new timestamp or false to use given message timestamp
*
* @return void
*
* @throws \InvalidArgumentException $message does not have a field "id" that is a MongoId
* @throws \InvalidArgumentException $earliestGet was not an int
* @throws \InvalidArgumentException $priority was not a float
* @throws \InvalidArgumentException $priority is NaN
* @throws \InvalidArgumentException $newTimestamp was not a bool
*/
public function ackSend(array $message, array $payload, $earliestGet = 0, $priority = 0.0, $newTimestamp = true)
{
$id = null;
if (array_key_exists('id', $message)) {
$id = $message['id'];
}
if (!($id instanceof \MongoId)) {
throw new \InvalidArgumentException('$message does not have a field "id" that is a MongoId');
}
if (!is_int($earliestGet)) {
throw new \InvalidArgumentException('$earliestGet was not an int');
}
if (!is_float($priority)) {
throw new \InvalidArgumentException('$priority was not a float');
}
if (is_nan($priority)) {
throw new \InvalidArgumentException('$priority was NaN');
}
if ($newTimestamp !== true && $newTimestamp !== false) {
throw new \InvalidArgumentException('$newTimestamp was not a bool');
}
if ($earliestGet > self::MONGO_INT32_MAX) {
$earliestGet = self::MONGO_INT32_MAX;
} elseif ($earliestGet < 0) {
$earliestGet = 0;
}
$toSet = array(
'payload' => $payload,
'running' => false,
'resetTimestamp' => new \MongoDate(self::MONGO_INT32_MAX),
'earliestGet' => new \MongoDate($earliestGet),
'priority' => $priority,
);
if ($newTimestamp) {
$toSet['created'] = new \MongoDate();
}
//using upsert because if no documents found then the doc was removed (SHOULD ONLY HAPPEN BY SOMEONE MANUALLY) so we can just send
$this->_collection->update(array('_id' => $id), array('$set' => $toSet), array('upsert' => true));
}
/**
* Requeue message to the queue. Same as ackSend() with the same message.
*
* @param array $message message received from get().
* @param int $earliestGet earliest unix timestamp the message can be retreived.
* @param float $priority priority for order out of get(). 0 is higher priority than 1
* @param bool $newTimestamp true to give the payload a new timestamp or false to use given message timestamp
*
* @return void
*
* @throws \InvalidArgumentException $message does not have a field "id" that is a MongoId
* @throws \InvalidArgumentException $earliestGet was not an int
* @throws \InvalidArgumentException $priority was not a float
* @throws \InvalidArgumentException priority is NaN
* @throws \InvalidArgumentException $newTimestamp was not a bool
*/
public function requeue(array $message, $earliestGet = 0, $priority = 0.0, $newTimestamp = true)
{
$forRequeue = $message;
unset($forRequeue['id']);
$this->ackSend($message, $forRequeue, $earliestGet, $priority, $newTimestamp);
}
/**
* Send a message to the queue.
*
* @param array $payload the data to store in the message. Data is handled same way as \MongoCollection::insert()
* @param int $earliestGet earliest unix timestamp the message can be retreived.
* @param float $priority priority for order out of get(). 0 is higher priority than 1
*
* @return void
*
* @throws \InvalidArgumentException $earliestGet was not an int
* @throws \InvalidArgumentException $priority was not a float
* @throws \InvalidArgumentException $priority is NaN
*/
public function send(array $payload, $earliestGet = 0, $priority = 0.0)
{
if (!is_int($earliestGet)) {
throw new \InvalidArgumentException('$earliestGet was not an int');
}
if (!is_float($priority)) {
throw new \InvalidArgumentException('$priority was not a float');
}
if (is_nan($priority)) {
throw new \InvalidArgumentException('$priority was NaN');
}
if ($earliestGet > self::MONGO_INT32_MAX) {
$earliestGet = self::MONGO_INT32_MAX;
} elseif ($earliestGet < 0) {
$earliestGet = 0;
}
$message = array(
'payload' => $payload,
'running' => false,
'resetTimestamp' => new \MongoDate(self::MONGO_INT32_MAX),
'earliestGet' => new \MongoDate($earliestGet),
'priority' => $priority,
'created' => new \MongoDate(),
);
$this->_collection->insert($message);
}
/**
* Ensure index of correct specification and a unique name whether the specification or name already exist or not.
* Will not create index if $index is a prefix of an existing index
*
* @param array $index index to create in same format as \MongoCollection::ensureIndex()
*
* @return void
*
* @throws \Exception couldnt create index after 5 attempts
*/
private function _ensureIndex(array $index)
{
//if $index is a prefix of any existing index we are good
foreach ($this->_collection->getIndexInfo() as $existingIndex) {
$slice = array_slice($existingIndex['key'], 0, count($index), true);
if ($slice === $index) {
return;
}
}
for ($i = 0; $i < 5; ++$i) {
for ($name = uniqid(); strlen($name) > 0; $name = substr($name, 0, -1)) {
//creating an index with same name and different spec does nothing.
//creating an index with same spec and different name does nothing.
//so we use any generated name, and then find the right spec after we have called, and just go with that name.
try {
$this->_collection->ensureIndex($index, array('name' => $name, 'background' => true));
} catch (\MongoCursorException $e) {
//this happens when the name was too long, let continue
}
foreach ($this->_collection->getIndexInfo() as $existingIndex) {
if ($existingIndex['key'] === $index) {
return;
}
}
}
}
throw new \Exception('couldnt create index after 5 attempts');
}
}