GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#290)
by
unknown
01:34
created

Report::run()   F

Complexity

Conditions 33
Paths > 20000

Size

Total Lines 238

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 238
rs 0
c 0
b 0
f 0
cc 33
nc 47775744
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace App\Queue\Management;
4
5
use SilverStripe\Control\HTTPRequest;
6
use SilverStripe\Dev\BuildTask;
7
use SilverStripe\ORM\FieldType\DBDatetime;
8
use SilverStripe\ORM\Queries\SQLSelect;
9
use Symbiote\QueuedJobs\DataObjects\QueuedJobDescriptor;
10
use Symbiote\QueuedJobs\Services\QueuedJob;
11
use Symbiote\QueuedJobs\Services\QueuedJobService;
12
13
/**
14
 * Class Report
15
 *
16
 * Queue state overview report
17
 *
18
 * @package App\Queue\Management
19
 */
20
class Report extends BuildTask
21
{
22
23
    /**
24
     * {@inheritDoc}
25
     *
26
     * @var string
27
     */
28
    private static $segment = 'queue-management-report';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
29
30
    /**
31
     * @return string
32
     */
33
    public function getDescription(): string
34
    {
35
        return 'Overall queued jobs completion progress';
36
    }
37
38
    /**
39
     * @param HTTPRequest $request
40
     */
41
    public function run($request): void // phpcs:ignore SlevomatCodingStandard.TypeHints
42
    {
43
        $now = DBDatetime::now()->Rfc2822();
44
        $service = QueuedJobService::singleton();
45
        $queueState = [];
46
47
        if ($service->isMaintenanceLockActive()) {
48
            $queueState[] = 'Paused';
49
        }
50
51
        if ($service->isAtMaxJobs()) {
52
            $queueState[] = 'Maximum init jobs';
53
        }
54
55
        $queueState = $queueState
56
            ? implode(' ', $queueState)
57
            : 'Running';
58
59
        // job states
60
        $query = SQLSelect::create(
61
            '`JobStatus`, COUNT(`JobStatus`) as `count`',
62
            'QueuedJobDescriptor',
63
            ['StartAfter IS NULL OR StartAfter <= ?' => $now],
64
            ['count' => 'DESC'],
65
            ['JobStatus']
66
        );
67
68
        $results = $query->execute();
69
        $totalJobs = 0;
70
71
        $jobsData = [];
72
73
        while ($result = $results->next()) {
74
            $status = $result['JobStatus'];
75
            $count = $result['count'];
76
            $jobsData[$status] = $count;
77
            $totalJobs+= $count;
78
        }
79
80
        $brokenJobs = array_key_exists(QueuedJob::STATUS_BROKEN, $jobsData)
81
            ? $jobsData[QueuedJob::STATUS_BROKEN]
82
            : 0;
83
        $newsJobs = array_key_exists(QueuedJob::STATUS_NEW, $jobsData)
84
            ? $jobsData[QueuedJob::STATUS_NEW]
85
            : 0;
86
        $initJobs = array_key_exists(QueuedJob::STATUS_INIT, $jobsData)
87
            ? $jobsData[QueuedJob::STATUS_INIT]
88
            : 0;
89
        $runningJobs = array_key_exists(QueuedJob::STATUS_RUN, $jobsData)
90
            ? $jobsData[QueuedJob::STATUS_RUN]
91
            : 0;
92
        $completedJobs = array_key_exists(QueuedJob::STATUS_COMPLETE, $jobsData)
93
            ? $jobsData[QueuedJob::STATUS_COMPLETE]
94
            : 0;
95
        $jobsInProgress = $newsJobs + $initJobs + $runningJobs;
96
97
        $queueState = $queueState === 'Running' && $jobsInProgress === 0
98
            ? 'Idle'
99
            : $queueState;
100
101
        // progress bar
102
        echo sprintf(
103
            '<h2>[%s] Job progress %0.2f%%</h2>',
104
            $queueState,
105
            $totalJobs > 0 ? (($totalJobs - $jobsInProgress) / $totalJobs) * 100 : 0
106
        );
107
108
        $barWidth = 1000;
109
        echo sprintf(
110
            '<div style="background-color: white; height: 40px; width: %dpx; border: thin solid black">',
111
            $barWidth
112
        );
113
114
        foreach (['lime' => $completedJobs, 'red' => $brokenJobs] as $color => $count) {
115
            echo sprintf(
116
                '<div title="%d" style="background-color: %s; height: 100%%; width: %0.2fpx; display: inline-block">'
117
                . '</div>',
118
                $count,
119
                $color,
120
                $totalJobs > 0 ? ($count / $totalJobs) * $barWidth : 0
121
            );
122
        }
123
124
        echo '</div>';
125
126
        echo '<h3>Job status breakdown</h3>';
127
128
        foreach ($jobsData as $status => $count) {
129
            if (!$count) {
130
                continue;
131
            }
132
133
            echo sprintf('<p><b>%d</b> - %s</p>', $count, $status);
134
        }
135
136
        echo sprintf('<p><b>%d</b> - Total</p>', $totalJobs);
137
138
        // first and last completed job
139
        $query = SQLSelect::create(
140
            'MAX(`JobFinished`) as `last_job`, MIN(`JobStarted`) as `first_job`',
141
            'QueuedJobDescriptor',
142
            [['JobStatus' => QueuedJob::STATUS_COMPLETE]]
143
        );
144
145
        $results = $query->execute();
146
        $result = $results->first();
147
        $firstJob = $result['first_job'] ?? '';
148
        $lastJob = $result['last_job'] ?? '';
149
150
        // total job duration
151
        $query = SQLSelect::create(
152
            sprintf(
153
                '`JobTitle`, SUM(UNIX_TIMESTAMP(`JobFinished`) - UNIX_TIMESTAMP(%s) as `duration`, COUNT(*) as `count`',
154
                'COALESCE(`JobRestarted`, `JobStarted`))'
155
            ),
156
            'QueuedJobDescriptor',
157
            [['JobStatus' => QueuedJob::STATUS_COMPLETE]],
158
            ['duration' => 'DESC'],
159
            ['JobTitle']
160
        );
161
162
        $results = $query->execute();
163
164
        $totalDuration = 0;
165
        $jobDurations = [];
166
        $jobTypesCompleted = [];
167
        $jobQueueTypeCompleted = [];
168
169
        while ($result = $results->next()) {
170
            $jobType = $result['JobTitle'];
171
            $duration = $result['duration'];
172
            $totalDuration += $duration;
173
174
            $jobDurations[$jobType] = $duration;
175
176
            $count = $result['count'];
177
            $jobTypesCompleted[$jobType] = $count;
178
        }
179
180
        // total job duration
181
        $query = SQLSelect::create(
182
            'JobType, COUNT(*) as `count`',
183
            'QueuedJobDescriptor',
184
            [['JobStatus' => QueuedJob::STATUS_COMPLETE]],
185
            [],
186
            ['JobType']
187
        );
188
189
        $results = $query->execute();
190
191
        while ($result = $results->next()) {
192
            $jobType = $result['JobType'];
193
            $count = $result['count'];
194
195
            $jobQueueTypeCompleted[$jobType] = $count;
196
        }
197
198
        $elapsed = 0;
199
200
        if ($totalDuration > 0) {
201
            echo sprintf('<p><b>%d</b> s - total job duration</p>', $totalDuration);
202
            echo sprintf('<p><b>%0.4f</b> s - average job duration</p>', $totalDuration / $completedJobs);
203
            echo sprintf('<p><b>%s</b> - first job</p>', $firstJob);
204
            echo sprintf('<p><b>%s</b> - last job</p>', $lastJob);
205
206
            $elapsed = strtotime($lastJob) - strtotime($firstJob);
207
            echo sprintf('<p><b>%s</b> - elapsed time (s)</p>', $elapsed);
208
        } else {
209
            echo '<p>No completed jobs found</p>';
210
        }
211
212
        echo '<h3>Durations by job type</h3>';
213
214
        foreach ($jobDurations as $jobType => $duration) {
215
            $jobType = $jobType ?: 'Unknown';
216
217
            echo sprintf('<p><b>%d</b> s - %s</p>', $duration, $jobType);
218
        }
219
220
        echo '<h3>Completed jobs by job type</h3>';
221
222
        foreach ($jobTypesCompleted as $jobType => $completed) {
223
            $jobType = $jobType ?: 'Unknown';
224
225
            echo sprintf('<p><b>%d</b> jobs - %s</p>', $completed, $jobType);
226
        }
227
228
        echo '<h3>Completed jobs by queue type</h3>';
229
230
        $queueTypes = QueuedJobDescriptor::singleton()->getJobTypeValues();
231
232
        foreach ($jobQueueTypeCompleted as $jobType => $completed) {
233
            $jobType = $jobType ?: QueuedJob::QUEUED;
234
235
            echo sprintf('<p><b>%d</b> - %s</p>', $completed, $queueTypes[(string) $jobType]);
236
        }
237
238
        echo '<h3>Seconds per completed job by job type</h3>';
239
240
        foreach ($jobDurations as $jobType => $duration) {
241
            $completed = (int) $jobTypesCompleted[$jobType];
242
            $jobType = $jobType ?: 'Unknown';
243
244
            echo sprintf('<p><b>%f</b> s/job - %s</p>', ($duration / $completed), $jobType);
245
        }
246
247
        echo '<h3>Completed jobs per elapsed second by job type</h3>';
248
249
        if ($elapsed) {
250
            foreach ($jobTypesCompleted as $jobType => $completed) {
251
                $jobType = $jobType ?: 'Unknown';
252
253
                echo sprintf('<p><b>%f</b> jobs/elapsed second - %s</p>', ($completed / $elapsed), $jobType);
254
            }
255
        }
256
257
        // job type breakdown
258
        $query = SQLSelect::create(
259
            '`JobTitle`, COUNT(`JobTitle`) as `count`',
260
            'QueuedJobDescriptor',
261
            ['StartAfter IS NULL OR StartAfter <= ?' => $now],
262
            ['count' => 'DESC'],
263
            ['JobTitle']
264
        );
265
266
        $results = $query->execute();
267
        echo '<h3>Job type breakdown</h3>';
268
269
        while ($result = $results->next()) {
270
            $count = $result['count'];
271
272
            if (!$count) {
273
                continue;
274
            }
275
276
            echo sprintf('<p><b>%d</b> - %s</p>', $count, $result['JobTitle']);
277
        }
278
    }
279
}
280