| 1 |
<?php |
| 2 |
|
| 3 |
namespace React\Http\Middleware; |
| 4 |
|
| 5 |
use Psr\Http\Message\ServerRequestInterface; |
| 6 |
|
| 7 |
/** |
| 8 |
* Process incoming requests with a streaming request body (without buffering). |
| 9 |
* |
| 10 |
* This allows you to process requests of any size without buffering the request |
| 11 |
* body in memory. Instead, it will represent the request body as a |
| 12 |
* [`ReadableStreamInterface`](https://github.com/reactphp/stream#readablestreaminterface) |
| 13 |
* that emit chunks of incoming data as it is received: |
| 14 |
* |
| 15 |
* ```php |
| 16 |
* $http = new React\Http\HttpServer( |
| 17 |
* new React\Http\Middleware\StreamingRequestMiddleware(), |
| 18 |
* function (Psr\Http\Message\ServerRequestInterface $request) { |
| 19 |
* $body = $request->getBody(); |
| 20 |
* assert($body instanceof Psr\Http\Message\StreamInterface); |
| 21 |
* assert($body instanceof React\Stream\ReadableStreamInterface); |
| 22 |
* |
| 23 |
* return new React\Promise\Promise(function ($resolve) use ($body) { |
| 24 |
* $bytes = 0; |
| 25 |
* $body->on('data', function ($chunk) use (&$bytes) { |
| 26 |
* $bytes += \count($chunk); |
| 27 |
* }); |
| 28 |
* $body->on('close', function () use (&$bytes, $resolve) { |
| 29 |
* $resolve(new React\Http\Response( |
| 30 |
* 200, |
| 31 |
* [], |
| 32 |
* "Received $bytes bytes\n" |
| 33 |
* )); |
| 34 |
* }); |
| 35 |
* }); |
| 36 |
* } |
| 37 |
* ); |
| 38 |
* ``` |
| 39 |
* |
| 40 |
* See also [streaming incoming request](../../README.md#streaming-incoming-request) |
| 41 |
* for more details. |
| 42 |
* |
| 43 |
* Additionally, this middleware can be used in combination with the |
| 44 |
* [`LimitConcurrentRequestsMiddleware`](#limitconcurrentrequestsmiddleware) and |
| 45 |
* [`RequestBodyBufferMiddleware`](#requestbodybuffermiddleware) (see below) |
| 46 |
* to explicitly configure the total number of requests that can be handled at |
| 47 |
* once: |
| 48 |
* |
| 49 |
* ```php |
| 50 |
* $http = new React\Http\HttpServer( |
| 51 |
* new React\Http\Middleware\StreamingRequestMiddleware(), |
| 52 |
* new React\Http\Middleware\LimitConcurrentRequestsMiddleware(100), // 100 concurrent buffering handlers |
| 53 |
* new React\Http\Middleware\RequestBodyBufferMiddleware(2 * 1024 * 1024), // 2 MiB per request |
| 54 |
* new React\Http\Middleware\RequestBodyParserMiddleware(), |
| 55 |
* $handler |
| 56 |
* ); |
| 57 |
* ``` |
| 58 |
* |
| 59 |
* > Internally, this class is used as a "marker" to not trigger the default |
| 60 |
* request buffering behavior in the `HttpServer`. It does not implement any logic |
| 61 |
* on its own. |
| 62 |
*/ |
| 63 |
final class StreamingRequestMiddleware |
| 64 |
{ |
| 65 |
public function __invoke(ServerRequestInterface $request, $next) |
| 66 |
{ |
| 67 |
return $next($request); |
| 68 |
} |
| 69 |
} |