-
-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathHttpWorker.php
More file actions
278 lines (245 loc) · 9.18 KB
/
HttpWorker.php
File metadata and controls
278 lines (245 loc) · 9.18 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
<?php
declare(strict_types=1);
namespace Spiral\RoadRunner\Http;
use Generator;
use RoadRunner\HTTP\DTO\V1\HeaderValue;
use RoadRunner\HTTP\DTO\V1\Request as RequestProto;
use RoadRunner\HTTP\DTO\V1\Response;
use Spiral\Goridge\Frame;
use Spiral\RoadRunner\Http\Exception\StreamStoppedException;
use Spiral\RoadRunner\Message\Command\StreamStop;
use Spiral\RoadRunner\Payload;
use Spiral\RoadRunner\StreamWorkerInterface;
use Spiral\RoadRunner\WorkerInterface;
/**
* @psalm-import-type HeadersList from Request
* @psalm-import-type AttributesList from Request
* @psalm-import-type UploadedFilesList from Request
* @psalm-import-type CookiesList from Request
*
* @psalm-type RequestContext = array{
* remoteAddr: non-empty-string,
* protocol: non-empty-string,
* method: non-empty-string,
* uri: string,
* attributes: AttributesList,
* headers: HeadersList,
* cookies: CookiesList,
* uploads: UploadedFilesList|null,
* rawQuery: string,
* parsed: bool
* }
*
* @see Request
*
* @api
*/
class HttpWorker implements HttpWorkerInterface
{
private static ?int $codec = null;
public function __construct(
private readonly WorkerInterface $worker,
) {}
public function getWorker(): WorkerInterface
{
return $this->worker;
}
/**
* @throws \JsonException
*/
public function waitRequest(): ?Request
{
$payload = $this->worker->waitPayload();
// Termination request
if ($payload === null || (!$payload->body && !$payload->header)) {
return null;
}
if (static::$codec === null) {
static::$codec = \json_validate($payload->header) ? Frame::CODEC_JSON : Frame::CODEC_PROTO;
}
if (static::$codec === Frame::CODEC_PROTO) {
$message = new RequestProto();
$message->mergeFromString($payload->header);
return $this->requestFromProto($payload->body, $message);
}
/** @var RequestContext $context */
$context = \json_decode($payload->header, true, 512, \JSON_THROW_ON_ERROR);
return $this->arrayToRequest($payload->body, $context);
}
/**
* @param array<array-key, array<array-key, string>> $headers
* @throws \JsonException
*/
public function respond(int $status, string|\Generator $body = '', array $headers = [], bool $endOfStream = true): void
{
if ($status < 200 && $status >= 100 && $body !== '') {
throw new \InvalidArgumentException('Unable to send a body with informational status code.');
}
if ($body instanceof \Generator) {
$this->respondStream($status, $body, $headers, $endOfStream);
return;
}
/** @psalm-suppress TooManyArguments */
$this->worker->respond($this->createRespondPayload($status, $body, $headers, $endOfStream), static::$codec);
}
/**
* @param array<array-key, array<array-key, string>> $headers
*/
private function respondStream(int $status, \Generator $body, array $headers = [], bool $endOfStream = true): void
{
$worker = $this->worker instanceof StreamWorkerInterface
? $this->worker->withStreamMode()
: $this->worker;
do {
if (!$body->valid()) {
// End of generator
$content = (string) $body->getReturn();
if ($endOfStream === false && $content === '') {
// We don't need to send an empty frame if the stream is not ended
return;
}
/** @psalm-suppress TooManyArguments */
$worker->respond(
$this->createRespondPayload($status, $content, $headers, $endOfStream),
static::$codec,
);
break;
}
$content = (string) $body->current();
if ($worker->getPayload(StreamStop::class) !== null) {
$body->throw(new StreamStoppedException());
// RoadRunner is waiting for a Stream Stop Frame to confirm that the stream is closed
// and the worker doesn't hang
$worker->respond(new Payload(''));
return;
}
/**
* Send a chunk of data
* @psalm-suppress TooManyArguments
*/
$worker->respond($this->createRespondPayload($status, $content, $headers, false), static::$codec);
try {
$body->next();
} catch (\Throwable) {
// Stop the stream if an exception is thrown from the generator
$worker->respond(new Payload(''));
return;
}
} while (true);
}
/**
* @param RequestContext $context
*/
private function arrayToRequest(string $body, array $context): Request
{
\parse_str($context['rawQuery'], $query);
return new Request(
remoteAddr: $context['remoteAddr'],
protocol: $context['protocol'],
method: $context['method'],
uri: $context['uri'],
headers: $this->filterHeaders((array) ($context['headers'] ?? [])),
cookies: (array) ($context['cookies'] ?? []),
uploads: (array) ($context['uploads'] ?? []),
attributes: [
Request::PARSED_BODY_ATTRIBUTE_NAME => $context['parsed'],
] + (array) ($context['attributes'] ?? []),
query: $query,
body: $body,
parsed: $context['parsed'],
);
}
private function requestFromProto(string $body, RequestProto $message): Request
{
/** @var UploadedFilesList $uploads */
$uploads = \json_decode($message->getUploads(), true) ?? [];
$headers = $this->headerValueToArray($message->getHeader());
\parse_str($message->getRawQuery(), $query);
/** @psalm-suppress ArgumentTypeCoercion, MixedArgumentTypeCoercion */
return new Request(
remoteAddr: $message->getRemoteAddr(),
protocol: $message->getProtocol(),
method: $message->getMethod(),
uri: $message->getUri(),
headers: $this->filterHeaders($headers),
cookies: \array_map(
static fn(array $values) => \implode(',', $values),
$this->headerValueToArray($message->getCookies()),
),
uploads: $uploads,
attributes: [
Request::PARSED_BODY_ATTRIBUTE_NAME => $message->getParsed(),
] + \array_map(
static fn(array $values) => \array_shift($values),
$this->headerValueToArray($message->getAttributes()),
),
query: $query,
body: $message->getParsed() && $body === '' ? '{}' : $body,
parsed: $message->getParsed(),
);
}
/**
* Remove all non-string and empty-string keys
*
* @param array<array-key, array<array-key, string>> $headers
* @return HeadersList
*/
private function filterHeaders(array $headers): array
{
foreach ($headers as $key => $_) {
if (!\is_string($key) || $key === '') {
// ignore invalid header names or values (otherwise, the worker might be crashed)
// @see: <https://git.io/JzjgJ>
unset($headers[$key]);
}
}
/** @var HeadersList $headers */
return $headers;
}
/**
* @param \Traversable<non-empty-string, HeaderValue> $message
*/
private function headerValueToArray(\Traversable $message): array
{
$result = [];
/**
* @var non-empty-string $key
* @var HeaderValue $value
*/
foreach ($message as $key => $value) {
$result[$key] = \iterator_to_array($value->getValue());
}
return $result;
}
/**
* @param array<array-key, array<array-key, string>> $headers
* @return array<non-empty-string, HeaderValue>
*/
private function arrayToHeaderValue(array $headers = []): array
{
$result = [];
/**
* @var non-empty-string $key
* @var array<array-key, string> $value
*/
foreach ($headers as $key => $value) {
/** @psalm-suppress DocblockTypeContradiction */
$value = \array_filter(\is_array($value) ? $value : [$value], static fn(mixed $v): bool => \is_string($v));
if ($value !== []) {
$result[$key] = new HeaderValue(['value' => $value]);
}
}
return $result;
}
/**
* @param array<array-key, array<array-key, string>> $headers
*/
private function createRespondPayload(int $status, string $body, array $headers = [], bool $eos = true): Payload
{
$head = static::$codec === Frame::CODEC_PROTO
? (new Response(['status' => $status, 'headers' => $this->arrayToHeaderValue($headers)]))
->serializeToString()
: \json_encode(['status' => $status, 'headers' => $headers ?: (object) []], \JSON_THROW_ON_ERROR);
return new Payload(body: $body, header: $head, eos: $eos);
}
}