Passed
Push — master ( 5e090d...dbfe7b )
by Blizzz
16:19 queued 13s
created

JobList   A

Complexity

Total Complexity 41

Size/Duplication

Total Lines 342
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 184
dl 0
loc 342
rs 9.1199
c 0
b 0
f 0
wmc 41

16 Methods

Rating   Name   Duplication   Size   Complexity  
A setExecutionTime() 0 6 1
A remove() 0 29 5
A add() 0 30 4
A resetBackgroundJob() 0 7 1
A unlockJob() 0 6 1
A has() 0 20 2
A setLastJob() 0 3 1
A buildJob() 0 27 5
A __construct() 0 4 1
A setLastRun() 0 12 3
A removeById() 0 5 1
A getJobsIterator() 0 25 5
A getJobs() 0 6 2
A getDetailsById() 0 14 2
A getNext() 0 53 5
A getById() 0 8 2

How to fix   Complexity   

Complex Class

Complex classes like JobList often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use JobList, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Christoph Wurst <[email protected]>
6
 * @author Georg Ehrke <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Jörn Friedrich Dreyer <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Noveen Sachdeva <[email protected]>
11
 * @author Robin Appelman <[email protected]>
12
 * @author Robin McCorkell <[email protected]>
13
 * @author Roeland Jago Douma <[email protected]>
14
 *
15
 * @license AGPL-3.0
16
 *
17
 * This code is free software: you can redistribute it and/or modify
18
 * it under the terms of the GNU Affero General Public License, version 3,
19
 * as published by the Free Software Foundation.
20
 *
21
 * This program is distributed in the hope that it will be useful,
22
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
23
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24
 * GNU Affero General Public License for more details.
25
 *
26
 * You should have received a copy of the GNU Affero General Public License, version 3,
27
 * along with this program. If not, see <http://www.gnu.org/licenses/>
28
 *
29
 */
30
namespace OC\BackgroundJob;
31
32
use Doctrine\DBAL\Platforms\MySQLPlatform;
33
use OCP\AppFramework\QueryException;
34
use OCP\AppFramework\Utility\ITimeFactory;
35
use OCP\AutoloadNotAllowedException;
36
use OCP\BackgroundJob\IJob;
37
use OCP\BackgroundJob\IJobList;
38
use OCP\DB\QueryBuilder\IQueryBuilder;
39
use OCP\IConfig;
40
use OCP\IDBConnection;
41
42
class JobList implements IJobList {
43
	protected IDBConnection $connection;
44
	protected IConfig $config;
45
	protected ITimeFactory $timeFactory;
46
47
	public function __construct(IDBConnection $connection, IConfig $config, ITimeFactory $timeFactory) {
48
		$this->connection = $connection;
49
		$this->config = $config;
50
		$this->timeFactory = $timeFactory;
51
	}
52
53
	/**
54
	 * @param IJob|class-string<IJob> $job
0 ignored issues
show
Documentation Bug introduced by
The doc comment IJob|class-string<IJob> at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in IJob|class-string<IJob>.
Loading history...
55
	 * @param mixed $argument
56
	 */
57
	public function add($job, $argument = null): void {
58
		if ($job instanceof IJob) {
59
			$class = get_class($job);
60
		} else {
61
			$class = $job;
62
		}
63
64
		$argumentJson = json_encode($argument);
65
		if (strlen($argumentJson) > 4000) {
66
			throw new \InvalidArgumentException('Background job arguments can\'t exceed 4000 characters (json encoded)');
67
		}
68
69
		$query = $this->connection->getQueryBuilder();
70
		if (!$this->has($job, $argument)) {
71
			$query->insert('jobs')
72
				->values([
73
					'class' => $query->createNamedParameter($class),
74
					'argument' => $query->createNamedParameter($argumentJson),
75
					'argument_hash' => $query->createNamedParameter(md5($argumentJson)),
76
					'last_run' => $query->createNamedParameter(0, IQueryBuilder::PARAM_INT),
77
					'last_checked' => $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT),
78
				]);
79
		} else {
80
			$query->update('jobs')
81
				->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
82
				->set('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT))
83
				->where($query->expr()->eq('class', $query->createNamedParameter($class)))
84
				->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
85
		}
86
		$query->executeStatement();
87
	}
88
89
	/**
90
	 * @param IJob|string $job
91
	 * @param mixed $argument
92
	 */
93
	public function remove($job, $argument = null): void {
94
		if ($job instanceof IJob) {
95
			$class = get_class($job);
96
		} else {
97
			$class = $job;
98
		}
99
100
		$query = $this->connection->getQueryBuilder();
101
		$query->delete('jobs')
102
			->where($query->expr()->eq('class', $query->createNamedParameter($class)));
103
		if (!is_null($argument)) {
104
			$argumentJson = json_encode($argument);
105
			$query->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argumentJson))));
106
		}
107
108
		// Add galera safe delete chunking if using mysql
109
		// Stops us hitting wsrep_max_ws_rows when large row counts are deleted
110
		if ($this->connection->getDatabasePlatform() instanceof MySQLPlatform) {
111
			// Then use chunked delete
112
			$max = IQueryBuilder::MAX_ROW_DELETION;
113
114
			$query->setMaxResults($max);
115
116
			do {
117
				$deleted = $query->execute();
118
			} while ($deleted === $max);
119
		} else {
120
			// Dont use chunked delete - let the DB handle the large row count natively
121
			$query->execute();
122
		}
123
	}
124
125
	protected function removeById(int $id): void {
126
		$query = $this->connection->getQueryBuilder();
127
		$query->delete('jobs')
128
			->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
129
		$query->executeStatement();
130
	}
131
132
	/**
133
	 * check if a job is in the list
134
	 *
135
	 * @param IJob|class-string<IJob> $job
0 ignored issues
show
Documentation Bug introduced by
The doc comment IJob|class-string<IJob> at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in IJob|class-string<IJob>.
Loading history...
136
	 * @param mixed $argument
137
	 */
138
	public function has($job, $argument): bool {
139
		if ($job instanceof IJob) {
140
			$class = get_class($job);
141
		} else {
142
			$class = $job;
143
		}
144
		$argument = json_encode($argument);
145
146
		$query = $this->connection->getQueryBuilder();
147
		$query->select('id')
148
			->from('jobs')
149
			->where($query->expr()->eq('class', $query->createNamedParameter($class)))
150
			->andWhere($query->expr()->eq('argument_hash', $query->createNamedParameter(md5($argument))))
151
			->setMaxResults(1);
152
153
		$result = $query->executeQuery();
154
		$row = $result->fetch();
155
		$result->closeCursor();
156
157
		return (bool) $row;
158
	}
159
160
	public function getJobs($job, ?int $limit, int $offset): array {
161
		$iterable = $this->getJobsIterator($job, $limit, $offset);
162
		if (is_array($iterable)) {
0 ignored issues
show
introduced by
The condition is_array($iterable) is always false.
Loading history...
163
			return $iterable;
164
		} else {
165
			return iterator_to_array($iterable);
166
		}
167
	}
168
169
	/**
170
	 * @param IJob|class-string<IJob>|null $job
0 ignored issues
show
Documentation Bug introduced by
The doc comment IJob|class-string<IJob>|null at position 2 could not be parsed: Unknown type name 'class-string' at position 2 in IJob|class-string<IJob>|null.
Loading history...
171
	 * @return iterable<IJob> Avoid to store these objects as they may share a Singleton instance. You should instead use these IJobs instances while looping on the iterable.
172
	 */
173
	public function getJobsIterator($job, ?int $limit, int $offset): iterable {
174
		$query = $this->connection->getQueryBuilder();
175
		$query->select('*')
176
			->from('jobs')
177
			->setMaxResults($limit)
178
			->setFirstResult($offset);
179
180
		if ($job !== null) {
181
			if ($job instanceof IJob) {
182
				$class = get_class($job);
183
			} else {
184
				$class = $job;
185
			}
186
			$query->where($query->expr()->eq('class', $query->createNamedParameter($class)));
187
		}
188
189
		$result = $query->executeQuery();
190
191
		while ($row = $result->fetch()) {
192
			$job = $this->buildJob($row);
193
			if ($job) {
194
				yield $job;
195
			}
196
		}
197
		$result->closeCursor();
198
	}
199
200
	/**
201
	 * Get the next job in the list
202
	 * @return ?IJob the next job to run. Beware that this object may be a singleton and may be modified by the next call to buildJob.
203
	 */
204
	public function getNext(bool $onlyTimeSensitive = false): ?IJob {
205
		$query = $this->connection->getQueryBuilder();
206
		$query->select('*')
207
			->from('jobs')
208
			->where($query->expr()->lte('reserved_at', $query->createNamedParameter($this->timeFactory->getTime() - 12 * 3600, IQueryBuilder::PARAM_INT)))
209
			->andWhere($query->expr()->lte('last_checked', $query->createNamedParameter($this->timeFactory->getTime(), IQueryBuilder::PARAM_INT)))
210
			->orderBy('last_checked', 'ASC')
211
			->setMaxResults(1);
212
213
		if ($onlyTimeSensitive) {
214
			$query->andWhere($query->expr()->eq('time_sensitive', $query->createNamedParameter(IJob::TIME_SENSITIVE, IQueryBuilder::PARAM_INT)));
215
		}
216
217
		$update = $this->connection->getQueryBuilder();
218
		$update->update('jobs')
219
			->set('reserved_at', $update->createNamedParameter($this->timeFactory->getTime()))
220
			->set('last_checked', $update->createNamedParameter($this->timeFactory->getTime()))
221
			->where($update->expr()->eq('id', $update->createParameter('jobid')))
222
			->andWhere($update->expr()->eq('reserved_at', $update->createParameter('reserved_at')))
223
			->andWhere($update->expr()->eq('last_checked', $update->createParameter('last_checked')));
224
225
		$result = $query->executeQuery();
226
		$row = $result->fetch();
227
		$result->closeCursor();
228
229
		if ($row) {
230
			$update->setParameter('jobid', $row['id']);
231
			$update->setParameter('reserved_at', $row['reserved_at']);
232
			$update->setParameter('last_checked', $row['last_checked']);
233
			$count = $update->executeStatement();
234
235
			if ($count === 0) {
236
				// Background job already executed elsewhere, try again.
237
				return $this->getNext($onlyTimeSensitive);
238
			}
239
			$job = $this->buildJob($row);
240
241
			if ($job === null) {
242
				// set the last_checked to 12h in the future to not check failing jobs all over again
243
				$reset = $this->connection->getQueryBuilder();
244
				$reset->update('jobs')
245
					->set('reserved_at', $reset->expr()->literal(0, IQueryBuilder::PARAM_INT))
246
					->set('last_checked', $reset->createNamedParameter($this->timeFactory->getTime() + 12 * 3600, IQueryBuilder::PARAM_INT))
247
					->where($reset->expr()->eq('id', $reset->createNamedParameter($row['id'], IQueryBuilder::PARAM_INT)));
248
				$reset->executeStatement();
249
250
				// Background job from disabled app, try again.
251
				return $this->getNext($onlyTimeSensitive);
252
			}
253
254
			return $job;
255
		} else {
256
			return null;
257
		}
258
	}
259
260
	/**
261
	 * @return ?IJob The job matching the id. Beware that this object may be a singleton and may be modified by the next call to buildJob.
262
	 */
263
	public function getById(int $id): ?IJob {
264
		$row = $this->getDetailsById($id);
265
266
		if ($row) {
267
			return $this->buildJob($row);
268
		}
269
270
		return null;
271
	}
272
273
	public function getDetailsById(int $id): ?array {
274
		$query = $this->connection->getQueryBuilder();
275
		$query->select('*')
276
			->from('jobs')
277
			->where($query->expr()->eq('id', $query->createNamedParameter($id, IQueryBuilder::PARAM_INT)));
278
		$result = $query->executeQuery();
279
		$row = $result->fetch();
280
		$result->closeCursor();
281
282
		if ($row) {
283
			return $row;
284
		}
285
286
		return null;
287
	}
288
289
	/**
290
	 * get the job object from a row in the db
291
	 *
292
	 * @param array{class:class-string<IJob>, id:mixed, last_run:mixed, argument:string} $row
0 ignored issues
show
Documentation Bug introduced by
The doc comment array{class:class-string...mixed, argument:string} at position 4 could not be parsed: Unknown type name 'class-string' at position 4 in array{class:class-string<IJob>, id:mixed, last_run:mixed, argument:string}.
Loading history...
293
	 * @return ?IJob the next job to run. Beware that this object may be a singleton and may be modified by the next call to buildJob.
294
	 */
295
	private function buildJob(array $row): ?IJob {
296
		try {
297
			try {
298
				// Try to load the job as a service
299
				/** @var IJob $job */
300
				$job = \OCP\Server::get($row['class']);
301
			} catch (QueryException $e) {
302
				if (class_exists($row['class'])) {
303
					$class = $row['class'];
304
					$job = new $class();
305
				} else {
306
					// job from disabled app or old version of an app, no need to do anything
307
					return null;
308
				}
309
			}
310
311
			if (!($job instanceof IJob)) {
312
				// This most likely means an invalid job was enqueued. We can ignore it.
313
				return null;
314
			}
315
			$job->setId((int) $row['id']);
316
			$job->setLastRun((int) $row['last_run']);
317
			$job->setArgument(json_decode($row['argument'], true));
318
			return $job;
319
		} catch (AutoloadNotAllowedException $e) {
320
			// job is from a disabled app, ignore
321
			return null;
322
		}
323
	}
324
325
	/**
326
	 * set the job that was last ran
327
	 */
328
	public function setLastJob(IJob $job): void {
329
		$this->unlockJob($job);
330
		$this->config->setAppValue('backgroundjob', 'lastjob', (string)$job->getId());
331
	}
332
333
	/**
334
	 * Remove the reservation for a job
335
	 */
336
	public function unlockJob(IJob $job): void {
337
		$query = $this->connection->getQueryBuilder();
338
		$query->update('jobs')
339
			->set('reserved_at', $query->expr()->literal(0, IQueryBuilder::PARAM_INT))
340
			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
341
		$query->executeStatement();
342
	}
343
344
	/**
345
	 * set the lastRun of $job to now
346
	 */
347
	public function setLastRun(IJob $job): void {
348
		$query = $this->connection->getQueryBuilder();
349
		$query->update('jobs')
350
			->set('last_run', $query->createNamedParameter(time(), IQueryBuilder::PARAM_INT))
351
			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
352
353
		if ($job instanceof \OCP\BackgroundJob\TimedJob
354
			&& !$job->isTimeSensitive()) {
355
			$query->set('time_sensitive', $query->createNamedParameter(IJob::TIME_INSENSITIVE));
356
		}
357
358
		$query->executeStatement();
359
	}
360
361
	/**
362
	 * @param int $timeTaken
363
	 */
364
	public function setExecutionTime(IJob $job, $timeTaken): void {
365
		$query = $this->connection->getQueryBuilder();
366
		$query->update('jobs')
367
			->set('execution_duration', $query->createNamedParameter($timeTaken, IQueryBuilder::PARAM_INT))
368
			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId(), IQueryBuilder::PARAM_INT)));
369
		$query->executeStatement();
370
	}
371
372
	/**
373
	 * Reset the $job so it executes on the next trigger
374
	 *
375
	 * @since 23.0.0
376
	 */
377
	public function resetBackgroundJob(IJob $job): void {
378
		$query = $this->connection->getQueryBuilder();
379
		$query->update('jobs')
380
			->set('last_run', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
381
			->set('reserved_at', $query->createNamedParameter(0, IQueryBuilder::PARAM_INT))
382
			->where($query->expr()->eq('id', $query->createNamedParameter($job->getId()), IQueryBuilder::PARAM_INT));
383
		$query->executeStatement();
384
	}
385
}
386