-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathSubprocessJobRunnerCommand.php
More file actions
222 lines (192 loc) · 6.43 KB
/
SubprocessJobRunnerCommand.php
File metadata and controls
222 lines (192 loc) · 6.43 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
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org/)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org/)
* @link https://cakephp.org CakePHP(tm) Project
* @since 2.2.0
* @license https://opensource.org/licenses/MIT MIT License
*/
namespace Cake\Queue\Command;
use Cake\Command\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Core\ContainerInterface;
use Cake\Log\Engine\ConsoleLog;
use Cake\Log\Log;
use Cake\Queue\Job\Message;
use Cake\Queue\Queue\Processor;
use Enqueue\Null\NullConnectionFactory;
use Enqueue\Null\NullMessage;
use Interop\Queue\Message as QueueMessage;
use Interop\Queue\Processor as InteropProcessor;
use JsonException;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use RuntimeException;
use Throwable;
/**
* Subprocess job runner command.
* Executes a single job in an isolated subprocess.
*/
class SubprocessJobRunnerCommand extends Command
{
/**
* @param \Cake\Core\ContainerInterface|null $container DI container instance
*/
public function __construct(
protected readonly ?ContainerInterface $container = null,
) {
}
/**
* Get the command name.
*
* @return string
*/
public static function defaultName(): string
{
return 'queue subprocess_runner';
}
/**
* Execute a single job from STDIN and output result to STDOUT.
*
* @param \Cake\Console\Arguments $args Arguments
* @param \Cake\Console\ConsoleIo $io ConsoleIo
* @return int
*/
public function execute(Arguments $args, ConsoleIo $io): int
{
$input = $this->readInput($io);
if ($input === '') {
$this->outputResult($io, [
'success' => false,
'error' => 'No input received',
]);
return self::CODE_ERROR;
}
try {
$data = json_decode($input, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $jsonException) {
$this->outputResult($io, [
'success' => false,
'error' => 'Invalid JSON input: ' . $jsonException->getMessage(),
]);
return self::CODE_ERROR;
}
try {
$result = $this->executeJob($data);
$this->outputResult($io, [
'success' => true,
'result' => $result,
]);
return self::CODE_SUCCESS;
} catch (Throwable $throwable) {
$this->outputResult($io, [
'success' => false,
'result' => InteropProcessor::REQUEUE,
'exception' => [
'class' => get_class($throwable),
'message' => $throwable->getMessage(),
'code' => $throwable->getCode(),
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
'trace' => $throwable->getTraceAsString(),
],
]);
return self::CODE_SUCCESS;
}
}
/**
* Read input from STDIN or ConsoleIo
*
* @param \Cake\Console\ConsoleIo $io ConsoleIo
* @return string
*/
protected function readInput(ConsoleIo $io): string
{
$input = '';
while (!feof(STDIN)) {
$chunk = fread(STDIN, 8192);
if ($chunk === false) {
break;
}
$input .= $chunk;
}
return $input;
}
/**
* Execute the job with the provided data.
*
* @param array<string, mixed> $data Job data
* @return string
*/
protected function executeJob(array $data): string
{
$connectionFactory = new NullConnectionFactory();
$context = $connectionFactory->createContext();
$messageClass = $data['messageClass'] ?? NullMessage::class;
// Validate message class for security
if (!class_exists($messageClass) || !is_subclass_of($messageClass, QueueMessage::class)) {
throw new RuntimeException(sprintf('Invalid message class: %s', $messageClass));
}
$messageBody = json_encode($data['body']);
/** @var \Interop\Queue\Message $queueMessage */
$queueMessage = new $messageClass($messageBody);
if (isset($data['properties']) && is_array($data['properties'])) {
foreach ($data['properties'] as $key => $value) {
$queueMessage->setProperty($key, $value);
}
}
$logger = $this->configureLogging($data);
$message = new Message($queueMessage, $context, $this->container);
$processor = new Processor($logger, $this->container);
$result = $processor->processMessage($message);
// Result is string|object (with __toString)
/** @phpstan-ignore cast.string */
return is_string($result) ? $result : (string)$result;
}
/**
* Configure logging to use STDERR to prevent job logs from contaminating STDOUT.
* Reconfigures all CakePHP loggers to write to STDERR with no additional formatting.
*
* @param array<string, mixed> $data Job data
* @return \Psr\Log\LoggerInterface
*/
protected function configureLogging(array $data): LoggerInterface
{
// Drop all existing loggers to prevent duplicate logging
foreach (Log::configured() as $loggerName) {
Log::drop($loggerName);
}
// Configure a single stderr logger
Log::setConfig('default', [
'className' => ConsoleLog::class,
'stream' => 'php://stderr',
]);
$logger = Log::engine('default');
if (!$logger instanceof LoggerInterface) {
$logger = new NullLogger();
}
return $logger;
}
/**
* Output result as JSON to STDOUT.
*
* @param \Cake\Console\ConsoleIo $io ConsoleIo
* @param array<string, mixed> $result Result data
* @return void
*/
protected function outputResult(ConsoleIo $io, array $result): void
{
$json = json_encode($result);
if ($json !== false) {
$io->out($json);
}
}
}