-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResque.php
402 lines (358 loc) · 11.6 KB
/
Resque.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
<?php
namespace he\queue;
use he\queue\tool\Event;
use he\queue\tool\Job;
use he\queue\tool\job\DontCreate;
use he\queue\tool\Redis;
use RuntimeException;
/**
* Base Resque class.
*
* @package Resque
* @author Chris Boulton <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php
*/
class Resque
{
const VERSION = '1.0';
const DEFAULT_INTERVAL = 5;
/**
* @var Redis|\Redis Instance of Resque_Redis that talks to redis.
*/
public static $redis = null;
/**
* @var mixed Host/port conbination separated by a colon, or a nested
* array of server swith host/port pairs
*/
protected static $redisServer = null;
/**
* @var int ID of Redis database to select.
*/
protected static $redisDatabase = 0;
/**
* Given a host/port combination separated by a colon, set it as
* the redis server that Resque will talk to.
*
* @param mixed $server Host/port combination separated by a colon, DSN-formatted URI, or
* a callable that receives the configured database ID
* and returns a Resque_Redis instance, or
* a nested array of servers with host/port pairs.
* @param int $database
*/
public static function setBackend($server, $database = 0)
{
self::$redisServer = $server;
self::$redisDatabase = $database;
self::$redis = null;
}
protected static $redisRetry = 0;
/**
* Return an instance of the Resque_Redis class instantiated for Resque.
*
* @return Redis|\Redis Instance of Resque_Redis.
* @throws tool\RedisException|\RedisException
*/
public static function redis()
{
if (self::$redis === null) {
if (is_callable(self::$redisServer)) {
self::$redis = call_user_func(self::$redisServer, self::$redisDatabase);
} else {
self::$redis = new Redis(self::$redisServer, self::$redisDatabase);
}
}
try {
if (!self::$redis->ping()) {
throw new \Exception('need retry');
}
} catch (\Throwable $e) {
if (self::$redisRetry < 3) {
self::$redis = null;
sleep(self::$redisRetry);
return self::redis();
}
}
return self::$redis;
}
/**
* fork() helper method for php-resque that handles issues PHP socket
* and phpredis have with passing around sockets between child/parent
* processes.
*
* Will close connection to Redis before forking.
*
* @return int Return vars as per pcntl_fork(). False if pcntl_fork is unavailable
*/
public static function fork()
{
if (!function_exists('pcntl_fork')) {
return false;
}
// Close the connection to Redis before forking.
// This is a workaround for issues phpredis has.
self::$redis = null;
$pid = pcntl_fork();
if ($pid === -1) {
throw new RuntimeException('Unable to fork child worker.');
}
return $pid;
}
/**
* Push a job to the end of a specific queue. If the queue does not
* exist, then create it as well.
*
* @param string $queue The name of the queue to add the job to.
* @param array $item Job description as an array to be JSON encoded.
*/
public static function push($queue, $item)
{
$encodedItem = json_encode($item);
if ($encodedItem === false) {
return false;
}
self::redis()->sadd('queues', $queue);
$length = self::redis()->rpush('queue:' . $queue, $encodedItem);
if ($length < 1) {
return false;
}
return true;
}
/**
* Pop an item off the end of the specified queue, decode it and
* return it.
*
* @param string $queue The name of the queue to fetch an item from.
* @return array Decoded item from the queue.
*/
public static function pop($queue)
{
$item = self::redis()->lpop('queue:' . $queue);
if (!$item) {
return null;
}
return json_decode($item, true);
}
/**
* Remove items of the specified queue
*
* @param string $queue The name of the queue to fetch an item from.
* @param array $items
* @return integer number of deleted items
*/
public static function dequeue($queue, $items = array())
{
if (count($items) > 0) {
return self::removeItems($queue, $items);
} else {
return self::removeList($queue);
}
}
/**
* Remove specified queue
*
* @param string $queue The name of the queue to remove.
* @return integer Number of deleted items
*/
public static function removeQueue($queue)
{
$num = self::removeList($queue);
self::redis()->srem('queues', $queue);
return $num;
}
/**
* Pop an item off the end of the specified queues, using blocking list pop,
* decode it and return it.
*
* @param array $queues
* @param int $timeout
* @return null|array Decoded item from the queue.
*/
public static function blpop(array $queues, $timeout)
{
$list = array();
foreach ($queues as $queue) {
$list[] = 'queue:' . $queue;
}
$item = self::redis()->blpop($list, (int)$timeout);
if (!$item) {
return null;
}
/**
* Normally the Resque_Redis class returns queue names without the prefix
* But the blpop is a bit different. It returns the name as prefix:queue:name
* So we need to strip off the prefix:queue: part
*/
$queue = substr($item[0], strlen(self::redis()->getPrefix() . 'queue:'));
return array(
'queue' => $queue,
'payload' => json_decode($item[1], true)
);
}
/**
* Return the size (number of pending jobs) of the specified queue.
*
* @param string $queue name of the queue to be checked for pending jobs
*
* @return int The size of the queue.
*/
public static function size($queue)
{
return self::redis()->llen('queue:' . $queue);
}
/**
* Create a new job and save it to the specified queue.
*
* @param string $queue The name of the queue to place the job in.
* @param string $class The name of the class that contains the code to execute the job.
* @param array $args Any optional arguments that should be passed when the job is executed.
* @param boolean $trackStatus Set to true to be able to monitor the status of a job.
*
* @return string|boolean Job ID when the job was created, false if creation was cancelled due to beforeEnqueue
*/
public static function enqueue($queue, $class, $args = null, $trackStatus = false)
{
$id = Resque::generateJobId();
$hookParams = array(
'class' => $class,
'args' => $args,
'queue' => $queue,
'id' => $id,
);
try {
Event::trigger('beforeEnqueue', $hookParams);
} catch (DontCreate $e) {
return false;
}
Job::create($queue, $class, $args, $trackStatus, $id);
Event::trigger('afterEnqueue', $hookParams);
return $id;
}
/**
* Reserve and return the next available job in the specified queue.
*
* @param string $queue Queue to fetch next available job from.
* @return Job Instance of Resque_Job to be processed, false if none or error.
*/
public static function reserve(string $queue): Job
{
return Job::reserve($queue);
}
/**
* Get an array of all known queues.
*
* @return array Array of queues.
*/
public static function queues()
{
$queues = self::redis()->smembers('queues');
if (!is_array($queues)) {
$queues = array();
}
return $queues;
}
/**
* Remove Items from the queue
* Safely moving each item to a temporary queue before processing it
* If the Job matches, counts otherwise puts it in a requeue_queue
* which at the end eventually be copied back into the original queue
*
* @private
*
* @param string $queue The name of the queue
* @param array $items
* @return integer number of deleted items
*/
private static function removeItems($queue, $items = array())
{
$counter = 0;
$originalQueue = 'queue:' . $queue;
$tempQueue = $originalQueue . ':temp:' . time();
$requeueQueue = $tempQueue . ':requeue';
// move each item from original queue to temp queue and process it
$finished = false;
while (!$finished) {
$string = self::redis()->rpoplpush($originalQueue, self::redis()->getPrefix() . $tempQueue);
if (!empty($string)) {
if (self::matchItem($string, $items)) {
self::redis()->rpop($tempQueue);
$counter++;
} else {
self::redis()->rpoplpush($tempQueue, self::redis()->getPrefix() . $requeueQueue);
}
} else {
$finished = true;
}
}
// move back from temp queue to original queue
$finished = false;
while (!$finished) {
$string = self::redis()->rpoplpush($requeueQueue, self::redis()->getPrefix() . $originalQueue);
if (empty($string)) {
$finished = true;
}
}
// remove temp queue and requeue queue
self::redis()->del($requeueQueue);
self::redis()->del($tempQueue);
return $counter;
}
/**
* matching item
* item can be ['class'] or ['class' => 'id'] or ['class' => {:foo => 1, :bar => 2}]
* @private
*
* @params string $string redis result in json
* @params $items
* @param $string
* @param $items
* @return bool (bool)
*/
private static function matchItem($string, $items)
{
$decoded = json_decode($string, true);
foreach ($items as $key => $val) {
# class name only ex: item[0] = ['class']
if (is_numeric($key)) {
if ($decoded['class'] == $val) {
return true;
}
# class name with args , example: item[0] = ['class' => {'foo' => 1, 'bar' => 2}]
} elseif (is_array($val)) {
$decodedArgs = (array)$decoded['args'][0];
if ($decoded['class'] == $key &&
count($decodedArgs) > 0 && count(array_diff($decodedArgs, $val)) == 0) {
return true;
}
# class name with ID, example: item[0] = ['class' => 'id']
} else {
if ($decoded['class'] == $key && $decoded['id'] == $val) {
return true;
}
}
}
return false;
}
/**
* Remove List
*
* @private
*
* @params string $queue the name of the queue
* @return integer number of deleted items belongs to this list
*/
private static function removeList($queue): int
{
$counter = self::size($queue);
$result = self::redis()->del('queue:' . $queue);
return ($result == 1) ? $counter : 0;
}
/*
* Generate an identifier to attach to a job for status tracking.
*
* @return string
*/
public static function generateJobId(): string
{
return md5(uniqid('', true));
}
}