Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 137
0.00% covered (danger)
0.00%
0 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
JobQueueGroup
0.00% covered (danger)
0.00%
0 / 136
0.00% covered (danger)
0.00%
0 / 13
2970
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 get
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 push
0.00% covered (danger)
0.00%
0 / 31
0.00% covered (danger)
0.00%
0 / 1
132
 lazyPush
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
20
 pop
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
132
 ack
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getQueueTypes
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getDefaultQueueTypes
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 queuesHaveJobs
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
20
 getQueuesWithJobs
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
30
 getQueueSizes
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 getCoalescedQueues
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
30
 assertValidJobs
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2/**
3 * @license GPL-2.0-or-later
4 * @file
5 */
6
7namespace MediaWiki\JobQueue;
8
9use InvalidArgumentException;
10use LogicException;
11use MediaWiki\Deferred\DeferredUpdates;
12use MediaWiki\Deferred\JobQueueEnqueueUpdate;
13use MediaWiki\JobQueue\Exceptions\JobQueueError;
14use MediaWiki\MediaWikiServices;
15use Wikimedia\MapCacheLRU\MapCacheLRU;
16use Wikimedia\ObjectCache\WANObjectCache;
17use Wikimedia\Rdbms\ReadOnlyMode;
18use Wikimedia\Stats\StatsFactory;
19use Wikimedia\UUID\GlobalIdGenerator;
20
21/**
22 * Handle enqueueing of background jobs.
23 *
24 * @warning This service class supports queuing jobs to foreign wikis via JobQueueGroupFactory,
25 * but other operations may be called for the local wiki only. Exceptions may be thrown if you
26 * attempt to inspect, pop, or execute a foreign wiki's job queue.
27 *
28 * @since 1.21
29 * @ingroup JobQueue
30 */
31class JobQueueGroup {
32    /** @var MapCacheLRU */
33    protected $cache;
34
35    /** @var string Wiki domain ID */
36    protected $domain;
37    /** @var ReadOnlyMode Read only mode */
38    protected $readOnlyMode;
39    /** @var array|null */
40    private $localJobClasses;
41    /** @var array */
42    private $jobTypeConfiguration;
43    /** @var array */
44    private $jobTypesExcludedFromDefaultQueue;
45    /** @var StatsFactory */
46    private $statsFactory;
47    /** @var WANObjectCache */
48    private $wanCache;
49    /** @var GlobalIdGenerator */
50    private $globalIdGenerator;
51
52    /** @var array Map of (bucket => (queue => JobQueue, types => list of types) */
53    protected $coalescedQueues;
54
55    public const TYPE_DEFAULT = 1; // integer; jobs popped by default
56    private const TYPE_ANY = 2; // integer; any job
57
58    public const USE_CACHE = 1; // integer; use process or persistent cache
59
60    private const PROC_CACHE_TTL = 15; // integer; seconds
61
62    /**
63     * @internal Use MediaWikiServices::getJobQueueGroupFactory
64     *
65     * @param string $domain Wiki domain ID
66     * @param ReadOnlyMode $readOnlyMode Read-only mode
67     * @param array|null $localJobClasses
68     * @param array $jobTypeConfiguration
69     * @param array $jobTypesExcludedFromDefaultQueue
70     * @param StatsFactory $statsFactory
71     * @param WANObjectCache $wanCache
72     * @param GlobalIdGenerator $globalIdGenerator
73     */
74    public function __construct(
75        $domain,
76        ReadOnlyMode $readOnlyMode,
77        ?array $localJobClasses,
78        array $jobTypeConfiguration,
79        array $jobTypesExcludedFromDefaultQueue,
80        StatsFactory $statsFactory,
81        WANObjectCache $wanCache,
82        GlobalIdGenerator $globalIdGenerator
83    ) {
84        $this->domain = $domain;
85        $this->readOnlyMode = $readOnlyMode;
86        $this->cache = new MapCacheLRU( 10 );
87        $this->localJobClasses = $localJobClasses;
88        $this->jobTypeConfiguration = $jobTypeConfiguration;
89        $this->jobTypesExcludedFromDefaultQueue = $jobTypesExcludedFromDefaultQueue;
90        $this->statsFactory = $statsFactory;
91        $this->wanCache = $wanCache;
92        $this->globalIdGenerator = $globalIdGenerator;
93    }
94
95    /**
96     * Get the job queue object for a given queue type
97     *
98     * @param string $type
99     * @return JobQueue
100     */
101    public function get( $type ) {
102        $conf = [ 'domain' => $this->domain, 'type' => $type ];
103        $conf += $this->jobTypeConfiguration[$type] ?? $this->jobTypeConfiguration['default'];
104        if ( !isset( $conf['readOnlyReason'] ) ) {
105            $conf['readOnlyReason'] = $this->readOnlyMode->getConfiguredReason();
106        }
107
108        $conf['stats'] = $this->statsFactory;
109        $conf['wanCache'] = $this->wanCache;
110        $conf['idGenerator'] = $this->globalIdGenerator;
111
112        return JobQueue::factory( $conf );
113    }
114
115    /**
116     * Insert jobs into the respective queues of which they belong
117     *
118     * This inserts the jobs into the queue specified by $wgJobTypeConf
119     * and updates the aggregate job queue information cache as needed.
120     *
121     * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
122     * @return void
123     */
124    public function push( $jobs ) {
125        $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
126        if ( $jobs === [] ) {
127            return;
128        }
129
130        $this->assertValidJobs( $jobs );
131
132        $jobsByType = []; // (job type => list of jobs)
133        foreach ( $jobs as $job ) {
134            $type = $job->getType();
135            if ( isset( $this->jobTypeConfiguration[$type] ) ) {
136                $jobsByType[$type][] = $job;
137            } else {
138                if (
139                    isset( $this->jobTypeConfiguration['default']['typeAgnostic'] ) &&
140                    $this->jobTypeConfiguration['default']['typeAgnostic']
141                ) {
142                    $jobsByType['default'][] = $job;
143                } else {
144                    $jobsByType[$type][] = $job;
145                }
146            }
147        }
148
149        foreach ( $jobsByType as $type => $jobs ) {
150            $this->get( $type )->push( $jobs );
151        }
152
153        if ( $this->cache->hasField( 'queues-ready', 'list' ) ) {
154            $list = $this->cache->getField( 'queues-ready', 'list' );
155            if ( count( array_diff( array_keys( $jobsByType ), $list ) ) ) {
156                $this->cache->clear( 'queues-ready' );
157            }
158        }
159
160        $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
161        $cache->set(
162            $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_ANY ),
163            'true',
164            15
165        );
166        if ( array_diff( array_keys( $jobsByType ), $this->jobTypesExcludedFromDefaultQueue ) ) {
167            $cache->set(
168                $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', self::TYPE_DEFAULT ),
169                'true',
170                15
171            );
172        }
173    }
174
175    /**
176     * Buffer jobs for insertion via push() or call it now if in CLI mode
177     *
178     * @param IJobSpecification|IJobSpecification[] $jobs A single Job or a list of Jobs
179     * @return void
180     * @since 1.26
181     */
182    public function lazyPush( $jobs ) {
183        if ( PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg' ) {
184            $this->push( $jobs );
185            return;
186        }
187
188        $jobs = is_array( $jobs ) ? $jobs : [ $jobs ];
189
190        // Throw errors now instead of on push(), when other jobs may be buffered
191        $this->assertValidJobs( $jobs );
192
193        DeferredUpdates::addUpdate( new JobQueueEnqueueUpdate( $this->domain, $jobs ) );
194    }
195
196    /**
197     * Pop one job off a job queue
198     *
199     * @warning May not be called on foreign wikis!
200     *
201     * This pops a job off a queue as specified by $wgJobTypeConf and
202     * updates the aggregate job queue information cache as needed.
203     *
204     * @param int|string $qtype JobQueueGroup::TYPE_* constant or job type string
205     * @param int $flags Bitfield of JobQueueGroup::USE_* constants
206     * @param array $ignored List of job types to ignore
207     * @return RunnableJob|false Returns false on failure
208     * @throws JobQueueError
209     */
210    public function pop( $qtype = self::TYPE_DEFAULT, $flags = 0, array $ignored = [] ) {
211        $job = false;
212
213        if ( !$this->localJobClasses ) {
214            throw new JobQueueError(
215                "Cannot pop '{$qtype}' job off foreign '{$this->domain}' wiki queue." );
216        }
217        if ( is_string( $qtype ) && !isset( $this->localJobClasses[$qtype] ) ) {
218            // Do not pop jobs if there is no class for the queue type
219            throw new JobQueueError( "Unrecognized job type '$qtype'." );
220        }
221
222        if ( is_string( $qtype ) ) { // specific job type
223            if ( !in_array( $qtype, $ignored ) ) {
224                $job = $this->get( $qtype )->pop();
225            }
226        } else { // any job in the "default" jobs types
227            if ( $flags & self::USE_CACHE ) {
228                if ( !$this->cache->hasField( 'queues-ready', 'list', self::PROC_CACHE_TTL ) ) {
229                    $this->cache->setField( 'queues-ready', 'list', $this->getQueuesWithJobs() );
230                }
231                $types = $this->cache->getField( 'queues-ready', 'list' );
232            } else {
233                $types = $this->getQueuesWithJobs();
234            }
235
236            if ( $qtype == self::TYPE_DEFAULT ) {
237                $types = array_intersect( $types, $this->getDefaultQueueTypes() );
238            }
239
240            $types = array_diff( $types, $ignored ); // avoid selected types
241            shuffle( $types ); // avoid starvation
242
243            foreach ( $types as $type ) { // for each queue...
244                $job = $this->get( $type )->pop();
245                if ( $job ) { // found
246                    break;
247                } else { // not found
248                    $this->cache->clear( 'queues-ready' );
249                }
250            }
251        }
252
253        return $job;
254    }
255
256    /**
257     * Acknowledge that a job was completed
258     *
259     * @param RunnableJob $job
260     * @return void
261     */
262    public function ack( RunnableJob $job ) {
263        $this->get( $job->getType() )->ack( $job );
264    }
265
266    /**
267     * Get the list of queue types
268     *
269     * @warning May not be called on foreign wikis!
270     *
271     * @return string[]
272     */
273    public function getQueueTypes() {
274        if ( !$this->localJobClasses ) {
275            throw new LogicException( 'Cannot inspect job queue from foreign wiki' );
276        }
277        return array_keys( $this->localJobClasses );
278    }
279
280    /**
281     * Get the list of default queue types
282     *
283     * @warning May not be called on foreign wikis!
284     *
285     * @return string[]
286     */
287    public function getDefaultQueueTypes() {
288        return array_diff( $this->getQueueTypes(), $this->jobTypesExcludedFromDefaultQueue );
289    }
290
291    /**
292     * Check if there are any queues with jobs (this is cached)
293     *
294     * @warning May not be called on foreign wikis!
295     *
296     * @since 1.23
297     * @param int $type JobQueueGroup::TYPE_* constant
298     * @return bool
299     */
300    public function queuesHaveJobs( $type = self::TYPE_ANY ) {
301        $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
302        $key = $cache->makeGlobalKey( 'jobqueue', $this->domain, 'hasjobs', $type );
303
304        $value = $cache->get( $key );
305        if ( $value === false ) {
306            $queues = $this->getQueuesWithJobs();
307            if ( $type == self::TYPE_DEFAULT ) {
308                $queues = array_intersect( $queues, $this->getDefaultQueueTypes() );
309            }
310            $value = count( $queues ) ? 'true' : 'false';
311            $cache->add( $key, $value, 15 );
312        }
313
314        return ( $value === 'true' );
315    }
316
317    /**
318     * Get the list of job types that have non-empty queues
319     *
320     * @warning May not be called on foreign wikis!
321     *
322     * @return string[] List of job types that have non-empty queues
323     */
324    public function getQueuesWithJobs() {
325        $types = [];
326        foreach ( $this->getCoalescedQueues() as $info ) {
327            /** @var JobQueue $queue */
328            $queue = $info['queue'];
329            $nonEmpty = $queue->getSiblingQueuesWithJobs( $this->getQueueTypes() );
330            if ( is_array( $nonEmpty ) ) { // batching features supported
331                $types = array_merge( $types, $nonEmpty );
332            } else { // we have to go through the queues in the bucket one-by-one
333                foreach ( $info['types'] as $type ) {
334                    if ( !$this->get( $type )->isEmpty() ) {
335                        $types[] = $type;
336                    }
337                }
338            }
339        }
340
341        return $types;
342    }
343
344    /**
345     * Get the size of the queues for a list of job types
346     *
347     * @warning May not be called on foreign wikis!
348     *
349     * @return int[] Map of (job type => size)
350     */
351    public function getQueueSizes() {
352        $sizeMap = [];
353        foreach ( $this->getCoalescedQueues() as $info ) {
354            /** @var JobQueue $queue */
355            $queue = $info['queue'];
356            $sizes = $queue->getSiblingQueueSizes( $this->getQueueTypes() );
357            if ( is_array( $sizes ) ) { // batching features supported
358                $sizeMap += $sizes;
359            } else { // we have to go through the queues in the bucket one-by-one
360                foreach ( $info['types'] as $type ) {
361                    $sizeMap[$type] = $this->get( $type )->getSize();
362                }
363            }
364        }
365
366        return $sizeMap;
367    }
368
369    /**
370     * @return array[]
371     * @phan-return array<string,array{queue:JobQueue,types:array<string,class-string>}>
372     */
373    protected function getCoalescedQueues() {
374        if ( $this->coalescedQueues === null ) {
375            $this->coalescedQueues = [];
376            foreach ( $this->jobTypeConfiguration as $type => $conf ) {
377                $conf['domain'] = $this->domain;
378                $conf['type'] = 'null';
379                $conf['stats'] = $this->statsFactory;
380                $conf['wanCache'] = $this->wanCache;
381                $conf['idGenerator'] = $this->globalIdGenerator;
382
383                $queue = JobQueue::factory( $conf );
384                $loc = $queue->getCoalesceLocationInternal();
385                if ( !isset( $this->coalescedQueues[$loc] ) ) {
386                    $this->coalescedQueues[$loc]['queue'] = $queue;
387                    $this->coalescedQueues[$loc]['types'] = [];
388                }
389                if ( $type === 'default' ) {
390                    $this->coalescedQueues[$loc]['types'] = array_merge(
391                        $this->coalescedQueues[$loc]['types'],
392                        array_diff( $this->getQueueTypes(), array_keys( $this->jobTypeConfiguration ) )
393                    );
394                } else {
395                    $this->coalescedQueues[$loc]['types'][] = $type;
396                }
397            }
398        }
399
400        return $this->coalescedQueues;
401    }
402
403    private function assertValidJobs( array $jobs ) {
404        foreach ( $jobs as $job ) {
405            if ( !( $job instanceof IJobSpecification ) ) {
406                $type = get_debug_type( $job );
407                throw new InvalidArgumentException( "Expected IJobSpecification objects, got " . $type );
408            }
409        }
410    }
411}
412
413/** @deprecated class alias since 1.44 */
414class_alias( JobQueueGroup::class, 'JobQueueGroup' );