-
-
Notifications
You must be signed in to change notification settings - Fork 440
Expand file tree
/
Copy pathParallelFileProcessor.php
More file actions
286 lines (238 loc) · 10.1 KB
/
ParallelFileProcessor.php
File metadata and controls
286 lines (238 loc) · 10.1 KB
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
<?php
declare(strict_types=1);
namespace Rector\Parallel\Application;
use Clue\React\NDJson\Decoder;
use Clue\React\NDJson\Encoder;
use Nette\Utils\Random;
use React\EventLoop\StreamSelectLoop;
use React\Socket\ConnectionInterface;
use React\Socket\TcpServer;
use Rector\Configuration\Option;
use Rector\Configuration\Parameter\SimpleParameterProvider;
use Rector\Console\Command\ProcessCommand;
use Rector\Parallel\Command\WorkerCommandLineFactory;
use Rector\Parallel\ValueObject\Bridge;
use Rector\ValueObject\Error\SystemError;
use Rector\ValueObject\ProcessResult;
use Rector\ValueObject\Reporting\FileDiff;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symplify\EasyParallel\Enum\Action;
use Symplify\EasyParallel\Enum\Content;
use Symplify\EasyParallel\Enum\ReactCommand;
use Symplify\EasyParallel\Enum\ReactEvent;
use Symplify\EasyParallel\ValueObject\ParallelProcess;
use Symplify\EasyParallel\ValueObject\ProcessPool;
use Symplify\EasyParallel\ValueObject\Schedule;
use Throwable;
/**
* Inspired from @see
* https://github.com/phpstan/phpstan-src/commit/9124c66dcc55a222e21b1717ba5f60771f7dda92#diff-39c7a3b0cbb217bbfff96fbb454e6e5e60c74cf92fbb0f9d246b8bebbaad2bb0
*
* https://github.com/phpstan/phpstan-src/commit/b84acd2e3eadf66189a64fdbc6dd18ff76323f67#diff-7f625777f1ce5384046df08abffd6c911cfbb1cfc8fcb2bdeaf78f337689e3e2R150
*/
final class ParallelFileProcessor
{
/**
* @var int
*/
private const SYSTEM_ERROR_LIMIT = 50;
/**
* The number of chunks a worker can process before getting killed.
* In contrast the jobSize defines the maximum size of a chunk, a worker process at a time.
*
* @var int
*/
private const MAX_CHUNKS_PER_WORKER = 8;
private ProcessPool|null $processPool = null;
public function __construct(
private readonly WorkerCommandLineFactory $workerCommandLineFactory,
) {
}
/**
* @param callable(int $stepCount): void $postFileCallback Used for progress bar jump
*/
public function process(
Schedule $schedule,
string $mainScript,
callable $postFileCallback,
InputInterface $input
): ProcessResult {
$jobs = array_reverse($schedule->getJobs());
$streamSelectLoop = new StreamSelectLoop();
// basic properties setup
$numberOfProcesses = $schedule->getNumberOfProcesses();
// initial counters
/** @var FileDiff[] $fileDiffs */
$fileDiffs = [];
/** @var SystemError[] $systemErrors */
$systemErrors = [];
$tcpServer = new TcpServer('127.0.0.1:0', $streamSelectLoop);
$this->processPool = new ProcessPool($tcpServer);
$tcpServer->on(ReactEvent::CONNECTION, function (ConnectionInterface $connection) use (&$jobs): void {
$inDecoder = new Decoder($connection, true, 512, 0, 4 * 1024 * 1024);
$outEncoder = new Encoder($connection);
$inDecoder->on(ReactEvent::DATA, function (array $data) use (&$jobs, $inDecoder, $outEncoder): void {
$action = $data[ReactCommand::ACTION];
if ($action !== Action::HELLO) {
return;
}
$processIdentifier = $data[Option::PARALLEL_IDENTIFIER];
$parallelProcess = $this->processPool->getProcess($processIdentifier);
$parallelProcess->bindConnection($inDecoder, $outEncoder);
if ($jobs === []) {
$this->processPool->quitProcess($processIdentifier);
return;
}
$jobsChunk = array_pop($jobs);
$parallelProcess->request([
ReactCommand::ACTION => Action::MAIN,
Content::FILES => $jobsChunk,
]);
});
});
/** @var string $serverAddress */
$serverAddress = $tcpServer->getAddress();
/** @var int $serverPort */
$serverPort = parse_url($serverAddress, PHP_URL_PORT);
$systemErrorsCount = 0;
$reachedSystemErrorsCountLimit = false;
$totalChanged = 0;
$handleErrorCallable = function (Throwable $throwable) use (
&$systemErrors,
&$systemErrorsCount,
&$reachedSystemErrorsCountLimit
): void {
$systemErrors[] = new SystemError(
$throwable->getMessage(),
$throwable->getFile(),
$throwable->getLine(),
);
++$systemErrorsCount;
$reachedSystemErrorsCountLimit = true;
$this->processPool->quitAll();
// This sleep has to be here, because event though we have called $this->processPool->quitAll(),
// it takes some time for the child processes to actually die, during which they can still write to cache
// @see https://github.com/rectorphp/rector-src/pull/3834/files#r1231696531
sleep(1);
};
$timeoutInSeconds = SimpleParameterProvider::provideIntParameter(Option::PARALLEL_JOB_TIMEOUT_IN_SECONDS);
$fileChunksBudgetPerProcess = [];
$processSpawner = function () use (
&$systemErrors,
&$fileDiffs,
&$jobs,
$postFileCallback,
&$systemErrorsCount,
&$reachedInternalErrorsCountLimit,
$mainScript,
$input,
$serverPort,
$streamSelectLoop,
$timeoutInSeconds,
$handleErrorCallable,
&$fileChunksBudgetPerProcess,
&$processSpawner,
&$totalChanged
): void {
$processIdentifier = Random::generate();
$workerCommandLine = $this->workerCommandLineFactory->create(
$mainScript,
ProcessCommand::class,
'worker',
$input,
$processIdentifier,
$serverPort,
);
$fileChunksBudgetPerProcess[$processIdentifier] = self::MAX_CHUNKS_PER_WORKER;
$parallelProcess = new ParallelProcess($workerCommandLine, $streamSelectLoop, $timeoutInSeconds);
$parallelProcess->start(
// 1. callable on data
function (array $json) use (
$parallelProcess,
&$systemErrors,
&$fileDiffs,
&$jobs,
$postFileCallback,
&$systemErrorsCount,
&$reachedInternalErrorsCountLimit,
$processIdentifier,
&$fileChunksBudgetPerProcess,
&$processSpawner,
&$totalChanged
): void {
/** @var array{
* total_changed: int,
* system_errors: mixed[],
* file_diffs: array<string, mixed>,
* files_count: int,
* system_errors_count: int
* } $json */
$totalChanged += $json[Bridge::TOTAL_CHANGED];
// decode arrays to objects
foreach ($json[Bridge::SYSTEM_ERRORS] as $jsonError) {
if (is_string($jsonError)) {
$systemErrors[] = new SystemError('System error: ' . $jsonError);
continue;
}
$systemErrors[] = SystemError::decode($jsonError);
}
foreach ($json[Bridge::FILE_DIFFS] as $jsonFileDiff) {
$fileDiffs[] = FileDiff::decode($jsonFileDiff);
}
$postFileCallback($json[Bridge::FILES_COUNT]);
$systemErrorsCount += $json[Bridge::SYSTEM_ERRORS_COUNT];
if ($systemErrorsCount >= self::SYSTEM_ERROR_LIMIT) {
$reachedInternalErrorsCountLimit = true;
$this->processPool->quitAll();
}
if ($fileChunksBudgetPerProcess[$processIdentifier] <= 0) {
// kill the current worker, and spawn a fresh one to free memory
$this->processPool->quitProcess($processIdentifier);
($processSpawner)();
return;
}
if ($jobs === []) {
$this->processPool->quitProcess($processIdentifier);
return;
}
$jobsChunk = array_pop($jobs);
$parallelProcess->request([
ReactCommand::ACTION => Action::MAIN,
Content::FILES => $jobsChunk,
]);
--$fileChunksBudgetPerProcess[$processIdentifier];
},
// 2. callable on error
$handleErrorCallable,
// 3. callable on exit
function ($exitCode, string $stdErr) use (&$systemErrors, $processIdentifier): void {
$this->processPool->tryQuitProcess($processIdentifier);
if ($exitCode === Command::SUCCESS) {
return;
}
if ($exitCode === null) {
return;
}
$systemErrors[] = new SystemError('Child process error: ' . $stdErr);
}
);
$this->processPool->attachProcess($processIdentifier, $parallelProcess);
};
for ($i = 0; $i < $numberOfProcesses; ++$i) {
// nothing else to process, stop now
if ($jobs === []) {
break;
}
($processSpawner)();
}
$streamSelectLoop->run();
if ($reachedSystemErrorsCountLimit) {
$systemErrors[] = new SystemError(sprintf(
'Reached system errors count limit of %d, exiting...',
self::SYSTEM_ERROR_LIMIT
));
}
return new ProcessResult($systemErrors, $fileDiffs, $totalChanged);
}
}