feat: run Front Controllers returning a PSR-15 request handlerUnverified
The handler is built once and reused like a Kernel, and served by HttpKernelRunner through a RequestHandlerKernel adapter converting with symfony/psr-http-message-bridge, so the Event conversions, proxy trust and upload cleanup stay in one place. The bridge and nyholm/psr7 are suggested dependencies; without the bridge the Invocation fails with an explanation. PSR-15 apps cannot see Symfony's trusted proxies, so the PSR-7 request gets the client, scheme and host resolved from X-Forwarded-* in its server params as well as in its URI. A handler implementing ResetInterface is reset before every Invocation but the first, like the Kernel's services_resetter.
2fab7ff parent: d996d11 modified
composer.json +7 -2 | @@ -17,14 +17,19 @@ | ||
| 17 | 17 | "symfony/runtime": "^7.4 || ^8.0" |
| 18 | 18 | }, |
| 19 | 19 | "suggest": { |
| 20 | - "ext-zip": "To build the deployment zip with vendor/bin/scaleway-package" | |
| 20 | + "ext-zip": "To build the deployment zip with vendor/bin/scaleway-package", | |
| 21 | + "nyholm/psr7": "To run Front Controllers returning a PSR-15 request handler", | |
| 22 | + "symfony/psr-http-message-bridge": "To run Front Controllers returning a PSR-15 request handler" | |
| 21 | 23 | }, |
| 22 | 24 | "require-dev": { |
| 23 | 25 | "friendsofphp/php-cs-fixer": "^3.95", |
| 26 | + "nyholm/psr7": "^1.8", | |
| 24 | 27 | "phpstan/phpstan": "^2.3", |
| 25 | 28 | "phpstan/phpstan-phpunit": "^2.1", |
| 26 | 29 | "phpunit/phpunit": "^13.4", |
| 27 | - "symfony/framework-bundle": "^7.4 || ^8.0" | |
| 30 | + "psr/http-server-handler": "^1.0", | |
| 31 | + "symfony/framework-bundle": "^7.4 || ^8.0", | |
| 32 | + "symfony/psr-http-message-bridge": "^7.4 || ^8.0" | |
| 28 | 33 | }, |
| 29 | 34 | "autoload": { |
| 30 | 35 | "psr-4": { |
| @@ -17,14 +17,19 @@ | |||
| 17 | "symfony/runtime": "^7.4 || ^8.0" | 17 | "symfony/runtime": "^7.4 || ^8.0" |
| 18 | }, | 18 | }, |
| 19 | "suggest": { | 19 | "suggest": { |
| 20 | - "ext-zip": "To build the deployment zip with vendor/bin/scaleway-package" | 20 | + "ext-zip": "To build the deployment zip with vendor/bin/scaleway-package", |
| 21 | + "nyholm/psr7": "To run Front Controllers returning a PSR-15 request handler", | ||
| 22 | + "symfony/psr-http-message-bridge": "To run Front Controllers returning a PSR-15 request handler" | ||
| 21 | }, | 23 | }, |
| 22 | "require-dev": { | 24 | "require-dev": { |
| 23 | "friendsofphp/php-cs-fixer": "^3.95", | 25 | "friendsofphp/php-cs-fixer": "^3.95", |
| 26 | + "nyholm/psr7": "^1.8", | ||
| 24 | "phpstan/phpstan": "^2.3", | 27 | "phpstan/phpstan": "^2.3", |
| 25 | "phpstan/phpstan-phpunit": "^2.1", | 28 | "phpstan/phpstan-phpunit": "^2.1", |
| 26 | "phpunit/phpunit": "^13.4", | 29 | "phpunit/phpunit": "^13.4", |
| 27 | - "symfony/framework-bundle": "^7.4 || ^8.0" | 30 | + "psr/http-server-handler": "^1.0", |
| 31 | + "symfony/framework-bundle": "^7.4 || ^8.0", | ||
| 32 | + "symfony/psr-http-message-bridge": "^7.4 || ^8.0" | ||
| 28 | }, | 33 | }, |
| 29 | "autoload": { | 34 | "autoload": { |
| 30 | "psr-4": { | 35 | "psr-4": { |
modified
docs/plan.md +1 -0 | @@ -11,6 +11,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc | ||
| 11 | 11 | - The Front Controller is the unchanged `public/index.php`; its path is the `front_controller` runtime option (`extra.runtime` or `APP_RUNTIME_OPTIONS`). |
| 12 | 12 | - The Application is booted once per Warm Process; between Invocations the runtime calls `terminate()` and the `services_resetter`; a failed boot is retried on the next Invocation (ADR 0002). |
| 13 | 13 | - A Front Controller returning a Response is called for every Invocation, a `Request` argument receiving the Invocation's Request (ADR 0004). |
| 14 | +- A Front Controller returning a PSR-15 `RequestHandlerInterface` is built once like a Kernel and served through `symfony/psr-http-message-bridge` (suggested, with `nyholm/psr7`); the PSR-7 request carries the client resolved from the trusted `X-Forwarded-*` headers in its server params (`REMOTE_ADDR`, `HTTPS`, `HTTP_HOST`, `SERVER_PORT`) and URI; a handler implementing `ResetInterface` is reset before every Invocation but the first. | |
| 14 | 15 | - HTTP mapping: base64 bodies decoded on input; output marked `isBase64Encoded` when the body is not valid UTF-8; multi-value headers sent as arrays; streamed and binary file responses buffered; query string rebuilt from `queryStringParameters`; `X-Forwarded-*` trusted; platform limits documented. |
| 15 | 16 | - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`). |
| 16 | 17 | - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; logs go to stderr. |
| @@ -11,6 +11,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc | |||
| 11 | - The Front Controller is the unchanged `public/index.php`; its path is the `front_controller` runtime option (`extra.runtime` or `APP_RUNTIME_OPTIONS`). | 11 | - The Front Controller is the unchanged `public/index.php`; its path is the `front_controller` runtime option (`extra.runtime` or `APP_RUNTIME_OPTIONS`). |
| 12 | - The Application is booted once per Warm Process; between Invocations the runtime calls `terminate()` and the `services_resetter`; a failed boot is retried on the next Invocation (ADR 0002). | 12 | - The Application is booted once per Warm Process; between Invocations the runtime calls `terminate()` and the `services_resetter`; a failed boot is retried on the next Invocation (ADR 0002). |
| 13 | - A Front Controller returning a Response is called for every Invocation, a `Request` argument receiving the Invocation's Request (ADR 0004). | 13 | - A Front Controller returning a Response is called for every Invocation, a `Request` argument receiving the Invocation's Request (ADR 0004). |
| 14 | +- A Front Controller returning a PSR-15 `RequestHandlerInterface` is built once like a Kernel and served through `symfony/psr-http-message-bridge` (suggested, with `nyholm/psr7`); the PSR-7 request carries the client resolved from the trusted `X-Forwarded-*` headers in its server params (`REMOTE_ADDR`, `HTTPS`, `HTTP_HOST`, `SERVER_PORT`) and URI; a handler implementing `ResetInterface` is reset before every Invocation but the first. | ||
| 14 | - HTTP mapping: base64 bodies decoded on input; output marked `isBase64Encoded` when the body is not valid UTF-8; multi-value headers sent as arrays; streamed and binary file responses buffered; query string rebuilt from `queryStringParameters`; `X-Forwarded-*` trusted; platform limits documented. | 15 | - HTTP mapping: base64 bodies decoded on input; output marked `isBase64Encoded` when the body is not valid UTF-8; multi-value headers sent as arrays; streamed and binary file responses buffered; query string rebuilt from `queryStringParameters`; `X-Forwarded-*` trusted; platform limits documented. |
| 15 | - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`). | 16 | - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`). |
| 16 | - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; logs go to stderr. | 17 | - Cache is warmed at build time; cache and log dirs fall back to `/tmp` when the project dir is not writable; logs go to stderr. |
added
src/Runner/RequestHandlerKernel.php +60 -0 | new file mode 100644 | ||
| @@ -0,0 +1,60 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace JDecool\ScalewayRuntime\Runner; | |
| 6 | + | |
| 7 | +use Psr\Http\Server\RequestHandlerInterface; | |
| 8 | +use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; | |
| 9 | +use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory; | |
| 10 | +use Symfony\Component\HttpFoundation\Request; | |
| 11 | +use Symfony\Component\HttpFoundation\Response; | |
| 12 | +use Symfony\Component\HttpKernel\HttpKernelInterface; | |
| 13 | +use Symfony\Contracts\Service\ResetInterface; | |
| 14 | + | |
| 15 | +/** | |
| 16 | + * Serves a PSR-15 Application, so that HttpKernelRunner handles it like any Kernel. | |
| 17 | + * | |
| 18 | + * @internal | |
| 19 | + */ | |
| 20 | +final class RequestHandlerKernel implements HttpKernelInterface | |
| 21 | +{ | |
| 22 | + private readonly PsrHttpFactory $psrFactory; | |
| 23 | + private readonly HttpFoundationFactory $httpFoundationFactory; | |
| 24 | + private bool $handled = false; | |
| 25 | + | |
| 26 | + public function __construct( | |
| 27 | + private readonly RequestHandlerInterface $handler, | |
| 28 | + ) { | |
| 29 | + if (!class_exists(PsrHttpFactory::class)) { | |
| 30 | + throw new \LogicException(\sprintf('Running a PSR-15 Application ("%s") requires the PSR-7 bridge, try running "composer require symfony/psr-http-message-bridge nyholm/psr7".', get_debug_type($handler))); | |
| 31 | + } | |
| 32 | + | |
| 33 | + // Without a PSR-17 factory given, the bridge picks nyholm/psr7 or php-http/discovery, and explains how to get one. | |
| 34 | + $this->psrFactory = new PsrHttpFactory(); | |
| 35 | + $this->httpFoundationFactory = new HttpFoundationFactory(); | |
| 36 | + } | |
| 37 | + | |
| 38 | + public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response | |
| 39 | + { | |
| 40 | + // Before every Invocation but the first, like the Kernel's services_resetter, so a failed one is cleaned up too. | |
| 41 | + if ($this->handled && $this->handler instanceof ResetInterface) { | |
| 42 | + $this->handler->reset(); | |
| 43 | + } | |
| 44 | + $this->handled = true; | |
| 45 | + | |
| 46 | + // PSR-15 apps read the client from the server params and do not know the trusted proxies, so they get | |
| 47 | + // the request as the platform proxy received it, the way mod_remoteip presents it to PHP. | |
| 48 | + $server = [ | |
| 49 | + 'REMOTE_ADDR' => $request->getClientIp(), | |
| 50 | + // PSR-7 needs a parsable URI; an Event without Host gets the default of Request::create(). | |
| 51 | + 'HTTP_HOST' => '' === $request->getHost() ? 'localhost' : $request->getHttpHost(), | |
| 52 | + 'SERVER_PORT' => $request->getPort() ?? ($request->isSecure() ? 443 : 80), | |
| 53 | + 'HTTPS' => $request->isSecure() ? 'on' : 'off', | |
| 54 | + ] + $request->server->all(); | |
| 55 | + | |
| 56 | + $response = $this->handler->handle($this->psrFactory->createRequest($request->duplicate(server: $server))); | |
| 57 | + | |
| 58 | + return $this->httpFoundationFactory->createResponse($response); | |
| 59 | + } | |
| 60 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,60 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +namespace JDecool\ScalewayRuntime\Runner; | ||
| 6 | + | ||
| 7 | +use Psr\Http\Server\RequestHandlerInterface; | ||
| 8 | +use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory; | ||
| 9 | +use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory; | ||
| 10 | +use Symfony\Component\HttpFoundation\Request; | ||
| 11 | +use Symfony\Component\HttpFoundation\Response; | ||
| 12 | +use Symfony\Component\HttpKernel\HttpKernelInterface; | ||
| 13 | +use Symfony\Contracts\Service\ResetInterface; | ||
| 14 | + | ||
| 15 | +/** | ||
| 16 | + * Serves a PSR-15 Application, so that HttpKernelRunner handles it like any Kernel. | ||
| 17 | + * | ||
| 18 | + * @internal | ||
| 19 | + */ | ||
| 20 | +final class RequestHandlerKernel implements HttpKernelInterface | ||
| 21 | +{ | ||
| 22 | + private readonly PsrHttpFactory $psrFactory; | ||
| 23 | + private readonly HttpFoundationFactory $httpFoundationFactory; | ||
| 24 | + private bool $handled = false; | ||
| 25 | + | ||
| 26 | + public function __construct( | ||
| 27 | + private readonly RequestHandlerInterface $handler, | ||
| 28 | + ) { | ||
| 29 | + if (!class_exists(PsrHttpFactory::class)) { | ||
| 30 | + throw new \LogicException(\sprintf('Running a PSR-15 Application ("%s") requires the PSR-7 bridge, try running "composer require symfony/psr-http-message-bridge nyholm/psr7".', get_debug_type($handler))); | ||
| 31 | + } | ||
| 32 | + | ||
| 33 | + // Without a PSR-17 factory given, the bridge picks nyholm/psr7 or php-http/discovery, and explains how to get one. | ||
| 34 | + $this->psrFactory = new PsrHttpFactory(); | ||
| 35 | + $this->httpFoundationFactory = new HttpFoundationFactory(); | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response | ||
| 39 | + { | ||
| 40 | + // Before every Invocation but the first, like the Kernel's services_resetter, so a failed one is cleaned up too. | ||
| 41 | + if ($this->handled && $this->handler instanceof ResetInterface) { | ||
| 42 | + $this->handler->reset(); | ||
| 43 | + } | ||
| 44 | + $this->handled = true; | ||
| 45 | + | ||
| 46 | + // PSR-15 apps read the client from the server params and do not know the trusted proxies, so they get | ||
| 47 | + // the request as the platform proxy received it, the way mod_remoteip presents it to PHP. | ||
| 48 | + $server = [ | ||
| 49 | + 'REMOTE_ADDR' => $request->getClientIp(), | ||
| 50 | + // PSR-7 needs a parsable URI; an Event without Host gets the default of Request::create(). | ||
| 51 | + 'HTTP_HOST' => '' === $request->getHost() ? 'localhost' : $request->getHttpHost(), | ||
| 52 | + 'SERVER_PORT' => $request->getPort() ?? ($request->isSecure() ? 443 : 80), | ||
| 53 | + 'HTTPS' => $request->isSecure() ? 'on' : 'off', | ||
| 54 | + ] + $request->server->all(); | ||
| 55 | + | ||
| 56 | + $response = $this->handler->handle($this->psrFactory->createRequest($request->duplicate(server: $server))); | ||
| 57 | + | ||
| 58 | + return $this->httpFoundationFactory->createResponse($response); | ||
| 59 | + } | ||
| 60 | +} | ||
modified
src/ScalewayRuntime.php +4 -0 | @@ -6,7 +6,9 @@ namespace JDecool\ScalewayRuntime; | ||
| 6 | 6 | |
| 7 | 7 | use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; |
| 8 | 8 | use JDecool\ScalewayRuntime\Runner\InvocationRunner; |
| 9 | +use JDecool\ScalewayRuntime\Runner\RequestHandlerKernel; | |
| 9 | 10 | use JDecool\ScalewayRuntime\Runner\ResponseKernel; |
| 11 | +use Psr\Http\Server\RequestHandlerInterface; | |
| 10 | 12 | use Symfony\Component\HttpFoundation\Request; |
| 11 | 13 | use Symfony\Component\HttpFoundation\Response; |
| 12 | 14 | use Symfony\Component\HttpKernel\HttpKernelInterface; |
| @@ -24,6 +26,7 @@ use Symfony\Component\Runtime\SymfonyRuntime; | ||
| 24 | 26 | * |
| 25 | 27 | * A Front Controller closure returning a Response is called again for every Invocation, and one |
| 26 | 28 | * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md). |
| 29 | + * A PSR-15 request handler is built once and reused like a Kernel; it needs symfony/psr-http-message-bridge and nyholm/psr7. | |
| 27 | 30 | */ |
| 28 | 31 | class ScalewayRuntime extends SymfonyRuntime |
| 29 | 32 | { |
| @@ -92,6 +95,7 @@ class ScalewayRuntime extends SymfonyRuntime | ||
| 92 | 95 | return match (true) { |
| 93 | 96 | $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog), |
| 94 | 97 | $application instanceof Response => new HttpKernelRunner(new ResponseKernel($respond, $application), $errorLog), |
| 98 | + $application instanceof RequestHandlerInterface => new HttpKernelRunner(new RequestHandlerKernel($application), $errorLog), | |
| 95 | 99 | default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))), |
| 96 | 100 | }; |
| 97 | 101 | } |
| @@ -6,7 +6,9 @@ namespace JDecool\ScalewayRuntime; | |||
| 6 | 6 | ||
| 7 | use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; | 7 | use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; |
| 8 | use JDecool\ScalewayRuntime\Runner\InvocationRunner; | 8 | use JDecool\ScalewayRuntime\Runner\InvocationRunner; |
| 9 | +use JDecool\ScalewayRuntime\Runner\RequestHandlerKernel; | ||
| 9 | use JDecool\ScalewayRuntime\Runner\ResponseKernel; | 10 | use JDecool\ScalewayRuntime\Runner\ResponseKernel; |
| 11 | +use Psr\Http\Server\RequestHandlerInterface; | ||
| 10 | use Symfony\Component\HttpFoundation\Request; | 12 | use Symfony\Component\HttpFoundation\Request; |
| 11 | use Symfony\Component\HttpFoundation\Response; | 13 | use Symfony\Component\HttpFoundation\Response; |
| 12 | use Symfony\Component\HttpKernel\HttpKernelInterface; | 14 | use Symfony\Component\HttpKernel\HttpKernelInterface; |
| @@ -24,6 +26,7 @@ use Symfony\Component\Runtime\SymfonyRuntime; | |||
| 24 | * | 26 | * |
| 25 | * A Front Controller closure returning a Response is called again for every Invocation, and one | 27 | * A Front Controller closure returning a Response is called again for every Invocation, and one |
| 26 | * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md). | 28 | * taking a Request gets the Invocation's Request (see docs/adr/0004-call-response-front-controllers-per-invocation.md). |
| 29 | + * A PSR-15 request handler is built once and reused like a Kernel; it needs symfony/psr-http-message-bridge and nyholm/psr7. | ||
| 27 | */ | 30 | */ |
| 28 | class ScalewayRuntime extends SymfonyRuntime | 31 | class ScalewayRuntime extends SymfonyRuntime |
| 29 | { | 32 | { |
| @@ -92,6 +95,7 @@ class ScalewayRuntime extends SymfonyRuntime | |||
| 92 | return match (true) { | 95 | return match (true) { |
| 93 | $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog), | 96 | $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog), |
| 94 | $application instanceof Response => new HttpKernelRunner(new ResponseKernel($respond, $application), $errorLog), | 97 | $application instanceof Response => new HttpKernelRunner(new ResponseKernel($respond, $application), $errorLog), |
| 98 | + $application instanceof RequestHandlerInterface => new HttpKernelRunner(new RequestHandlerKernel($application), $errorLog), | ||
| 95 | default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))), | 99 | default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))), |
| 96 | }; | 100 | }; |
| 97 | } | 101 | } |
added
tests/Fixtures/App/public/request-handler.php +9 -0 | new file mode 100644 | ||
| @@ -0,0 +1,9 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +use JDecool\ScalewayRuntime\Tests\Fixtures\EchoRequestHandler; | |
| 6 | + | |
| 7 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 8 | + | |
| 9 | +return static fn (): EchoRequestHandler => new EchoRequestHandler(); | |
| new file mode 100644 | |||
| @@ -0,0 +1,9 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +use JDecool\ScalewayRuntime\Tests\Fixtures\EchoRequestHandler; | ||
| 6 | + | ||
| 7 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 8 | + | ||
| 9 | +return static fn (): EchoRequestHandler => new EchoRequestHandler(); | ||
added
tests/Fixtures/EchoRequestHandler.php +59 -0 | new file mode 100644 | ||
| @@ -0,0 +1,59 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace JDecool\ScalewayRuntime\Tests\Fixtures; | |
| 6 | + | |
| 7 | +use Nyholm\Psr7\Response; | |
| 8 | +use Psr\Http\Message\ResponseInterface; | |
| 9 | +use Psr\Http\Message\ServerRequestInterface; | |
| 10 | +use Psr\Http\Message\UploadedFileInterface; | |
| 11 | +use Psr\Http\Server\RequestHandlerInterface; | |
| 12 | +use Symfony\Contracts\Service\ResetInterface; | |
| 13 | + | |
| 14 | +/** | |
| 15 | + * A PSR-15 Application describing the PSR-7 request it gets, with the response features a Function Response must keep. | |
| 16 | + */ | |
| 17 | +final class EchoRequestHandler implements RequestHandlerInterface, ResetInterface | |
| 18 | +{ | |
| 19 | + public int $handled = 0; | |
| 20 | + public int $resets = 0; | |
| 21 | + public ?ServerRequestInterface $lastRequest = null; | |
| 22 | + | |
| 23 | + public function handle(ServerRequestInterface $request): ResponseInterface | |
| 24 | + { | |
| 25 | + ++$this->handled; | |
| 26 | + $this->lastRequest = $request; | |
| 27 | + if ('/throw' === $request->getUri()->getPath()) { | |
| 28 | + throw new \RuntimeException('Escaped on purpose.'); | |
| 29 | + } | |
| 30 | + | |
| 31 | + $files = array_map(static fn (UploadedFileInterface $file): array => [ | |
| 32 | + 'name' => $file->getClientFilename(), | |
| 33 | + 'content' => (string) $file->getStream(), | |
| 34 | + ], array_filter($request->getUploadedFiles(), static fn (mixed $file): bool => $file instanceof UploadedFileInterface)); | |
| 35 | + | |
| 36 | + $body = json_encode([ | |
| 37 | + 'uri' => (string) $request->getUri(), | |
| 38 | + 'remoteAddr' => $request->getServerParams()['REMOTE_ADDR'] ?? null, | |
| 39 | + 'query' => $request->getQueryParams(), | |
| 40 | + 'parsedBody' => $request->getParsedBody(), | |
| 41 | + 'body' => (string) $request->getBody(), | |
| 42 | + 'files' => $files, | |
| 43 | + 'handled' => $this->handled, | |
| 44 | + 'resets' => $this->resets, | |
| 45 | + 'pid' => getmypid(), | |
| 46 | + ], \JSON_THROW_ON_ERROR); | |
| 47 | + | |
| 48 | + return new Response(201, [ | |
| 49 | + 'Content-Type' => 'application/json', | |
| 50 | + 'X-Multi' => ['a', 'b'], | |
| 51 | + 'Set-Cookie' => ['first=1; path=/', 'second=2; path=/'], | |
| 52 | + ], $body); | |
| 53 | + } | |
| 54 | + | |
| 55 | + public function reset(): void | |
| 56 | + { | |
| 57 | + ++$this->resets; | |
| 58 | + } | |
| 59 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +namespace JDecool\ScalewayRuntime\Tests\Fixtures; | ||
| 6 | + | ||
| 7 | +use Nyholm\Psr7\Response; | ||
| 8 | +use Psr\Http\Message\ResponseInterface; | ||
| 9 | +use Psr\Http\Message\ServerRequestInterface; | ||
| 10 | +use Psr\Http\Message\UploadedFileInterface; | ||
| 11 | +use Psr\Http\Server\RequestHandlerInterface; | ||
| 12 | +use Symfony\Contracts\Service\ResetInterface; | ||
| 13 | + | ||
| 14 | +/** | ||
| 15 | + * A PSR-15 Application describing the PSR-7 request it gets, with the response features a Function Response must keep. | ||
| 16 | + */ | ||
| 17 | +final class EchoRequestHandler implements RequestHandlerInterface, ResetInterface | ||
| 18 | +{ | ||
| 19 | + public int $handled = 0; | ||
| 20 | + public int $resets = 0; | ||
| 21 | + public ?ServerRequestInterface $lastRequest = null; | ||
| 22 | + | ||
| 23 | + public function handle(ServerRequestInterface $request): ResponseInterface | ||
| 24 | + { | ||
| 25 | + ++$this->handled; | ||
| 26 | + $this->lastRequest = $request; | ||
| 27 | + if ('/throw' === $request->getUri()->getPath()) { | ||
| 28 | + throw new \RuntimeException('Escaped on purpose.'); | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + $files = array_map(static fn (UploadedFileInterface $file): array => [ | ||
| 32 | + 'name' => $file->getClientFilename(), | ||
| 33 | + 'content' => (string) $file->getStream(), | ||
| 34 | + ], array_filter($request->getUploadedFiles(), static fn (mixed $file): bool => $file instanceof UploadedFileInterface)); | ||
| 35 | + | ||
| 36 | + $body = json_encode([ | ||
| 37 | + 'uri' => (string) $request->getUri(), | ||
| 38 | + 'remoteAddr' => $request->getServerParams()['REMOTE_ADDR'] ?? null, | ||
| 39 | + 'query' => $request->getQueryParams(), | ||
| 40 | + 'parsedBody' => $request->getParsedBody(), | ||
| 41 | + 'body' => (string) $request->getBody(), | ||
| 42 | + 'files' => $files, | ||
| 43 | + 'handled' => $this->handled, | ||
| 44 | + 'resets' => $this->resets, | ||
| 45 | + 'pid' => getmypid(), | ||
| 46 | + ], \JSON_THROW_ON_ERROR); | ||
| 47 | + | ||
| 48 | + return new Response(201, [ | ||
| 49 | + 'Content-Type' => 'application/json', | ||
| 50 | + 'X-Multi' => ['a', 'b'], | ||
| 51 | + 'Set-Cookie' => ['first=1; path=/', 'second=2; path=/'], | ||
| 52 | + ], $body); | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + public function reset(): void | ||
| 56 | + { | ||
| 57 | + ++$this->resets; | ||
| 58 | + } | ||
| 59 | +} | ||
added
tests/Fixtures/front-controllers/request-handler.php +7 -0 | new file mode 100644 | ||
| @@ -0,0 +1,7 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +use JDecool\ScalewayRuntime\Tests\Fixtures\EchoRequestHandler; | |
| 6 | + | |
| 7 | +return static fn (): EchoRequestHandler => new EchoRequestHandler(); | |
| new file mode 100644 | |||
| @@ -0,0 +1,7 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +use JDecool\ScalewayRuntime\Tests\Fixtures\EchoRequestHandler; | ||
| 6 | + | ||
| 7 | +return static fn (): EchoRequestHandler => new EchoRequestHandler(); | ||
modified
tests/HandlerTest.php +27 -0 | @@ -131,6 +131,19 @@ final class HandlerTest extends TestCase | ||
| 131 | 131 | self::assertSame(200, $handler->invoke(['path' => '/'], [])['statusCode']); |
| 132 | 132 | } |
| 133 | 133 | |
| 134 | + public function testRequestHandlerIsBuiltOnceAndKeepsServingAfterAnEscapedError(): void | |
| 135 | + { | |
| 136 | + $handler = $this->handler(['front_controller' => 'front-controllers/request-handler.php', 'debug' => false]); | |
| 137 | + | |
| 138 | + $first = $handler->invoke(['path' => '/'], []); | |
| 139 | + self::assertSame(500, $handler->invoke(['path' => '/throw'], [])['statusCode']); | |
| 140 | + self::assertStringContainsString('Escaped on purpose.', $this->errorLog()); | |
| 141 | + $third = $handler->invoke(['path' => '/'], []); | |
| 142 | + | |
| 143 | + self::assertSame(201, $first['statusCode']); | |
| 144 | + self::assertSame(3, $this->decode($third)['handled'], 'The request handler must be reused across Invocations.'); | |
| 145 | + } | |
| 146 | + | |
| 134 | 147 | public function testFrontControllerMustReturnACallable(): void |
| 135 | 148 | { |
| 136 | 149 | $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []); |
| @@ -175,6 +188,20 @@ final class HandlerTest extends TestCase | ||
| 175 | 188 | return new Handler($composerDir, $this->errorLog); |
| 176 | 189 | } |
| 177 | 190 | |
| 191 | + /** | |
| 192 | + * @param array<mixed> $response | |
| 193 | + * | |
| 194 | + * @return array<mixed> | |
| 195 | + */ | |
| 196 | + private function decode(array $response): array | |
| 197 | + { | |
| 198 | + self::assertIsString($response['body']); | |
| 199 | + $data = json_decode($response['body'], true, 512, \JSON_THROW_ON_ERROR); | |
| 200 | + self::assertIsArray($data); | |
| 201 | + | |
| 202 | + return $data; | |
| 203 | + } | |
| 204 | + | |
| 178 | 205 | private function errorLog(): string |
| 179 | 206 | { |
| 180 | 207 | rewind($this->errorLog); |
| @@ -131,6 +131,19 @@ final class HandlerTest extends TestCase | |||
| 131 | self::assertSame(200, $handler->invoke(['path' => '/'], [])['statusCode']); | 131 | self::assertSame(200, $handler->invoke(['path' => '/'], [])['statusCode']); |
| 132 | } | 132 | } |
| 133 | 133 | ||
| 134 | + public function testRequestHandlerIsBuiltOnceAndKeepsServingAfterAnEscapedError(): void | ||
| 135 | + { | ||
| 136 | + $handler = $this->handler(['front_controller' => 'front-controllers/request-handler.php', 'debug' => false]); | ||
| 137 | + | ||
| 138 | + $first = $handler->invoke(['path' => '/'], []); | ||
| 139 | + self::assertSame(500, $handler->invoke(['path' => '/throw'], [])['statusCode']); | ||
| 140 | + self::assertStringContainsString('Escaped on purpose.', $this->errorLog()); | ||
| 141 | + $third = $handler->invoke(['path' => '/'], []); | ||
| 142 | + | ||
| 143 | + self::assertSame(201, $first['statusCode']); | ||
| 144 | + self::assertSame(3, $this->decode($third)['handled'], 'The request handler must be reused across Invocations.'); | ||
| 145 | + } | ||
| 146 | + | ||
| 134 | public function testFrontControllerMustReturnACallable(): void | 147 | public function testFrontControllerMustReturnACallable(): void |
| 135 | { | 148 | { |
| 136 | $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []); | 149 | $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []); |
| @@ -175,6 +188,20 @@ final class HandlerTest extends TestCase | |||
| 175 | return new Handler($composerDir, $this->errorLog); | 188 | return new Handler($composerDir, $this->errorLog); |
| 176 | } | 189 | } |
| 177 | 190 | ||
| 191 | + /** | ||
| 192 | + * @param array<mixed> $response | ||
| 193 | + * | ||
| 194 | + * @return array<mixed> | ||
| 195 | + */ | ||
| 196 | + private function decode(array $response): array | ||
| 197 | + { | ||
| 198 | + self::assertIsString($response['body']); | ||
| 199 | + $data = json_decode($response['body'], true, 512, \JSON_THROW_ON_ERROR); | ||
| 200 | + self::assertIsArray($data); | ||
| 201 | + | ||
| 202 | + return $data; | ||
| 203 | + } | ||
| 204 | + | ||
| 178 | private function errorLog(): string | 205 | private function errorLog(): string |
| 179 | { | 206 | { |
| 180 | rewind($this->errorLog); | 207 | rewind($this->errorLog); |
modified
tests/IntegrationTest.php +36 -0 | @@ -121,6 +121,42 @@ final class IntegrationTest extends TestCase | ||
| 121 | 121 | self::assertSame($first['pid'], $second['pid']); |
| 122 | 122 | } |
| 123 | 123 | |
| 124 | + public function testRequestHandlerServesInvocationsThroughThePsr7Bridge(): void | |
| 125 | + { | |
| 126 | + [$first, $second] = $this->invoke([ | |
| 127 | + [ | |
| 128 | + 'path' => '/upload', | |
| 129 | + 'method' => 'POST', | |
| 130 | + 'headers' => [ | |
| 131 | + 'Host' => 'internal.local', | |
| 132 | + 'Content-Type' => 'multipart/form-data; boundary=b', | |
| 133 | + 'X-Forwarded-For' => '203.0.113.7', | |
| 134 | + 'X-Forwarded-Host' => 'api.example.com', | |
| 135 | + 'X-Forwarded-Proto' => 'https', | |
| 136 | + ], | |
| 137 | + 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n" | |
| 138 | + ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.csv\"\r\n\r\na,b\r\n--b--\r\n"), | |
| 139 | + 'isBase64Encoded' => true, | |
| 140 | + ], | |
| 141 | + ['path' => '/', 'headers' => ['Host' => 'internal.local']], | |
| 142 | + ], ['front_controller' => 'public/request-handler.php']); | |
| 143 | + | |
| 144 | + self::assertSame(201, $first['statusCode']); | |
| 145 | + self::assertIsArray($first['headers']); | |
| 146 | + self::assertSame(['a', 'b'], $first['headers']['X-Multi'] ?? null); | |
| 147 | + self::assertSame(['first=1; path=/', 'second=2; path=/'], $first['headers']['Set-Cookie'] ?? null); | |
| 148 | + $first = $this->json($first); | |
| 149 | + $second = $this->json($second); | |
| 150 | + | |
| 151 | + self::assertSame('https://api.example.com/upload', $first['uri']); | |
| 152 | + self::assertSame('203.0.113.7', $first['remoteAddr']); | |
| 153 | + self::assertSame(['title' => 'Report'], $first['parsedBody']); | |
| 154 | + self::assertSame(['doc' => ['name' => 'report.csv', 'content' => 'a,b']], $first['files']); | |
| 155 | + self::assertSame([], glob($this->dir.'/tmp/php*'), 'Uploaded files must be deleted after the Invocation.'); | |
| 156 | + self::assertSame(['uri' => 'http://internal.local/', 'remoteAddr' => '127.0.0.1', 'handled' => 2, 'resets' => 1], array_intersect_key($second, ['uri' => 0, 'remoteAddr' => 0, 'handled' => 0, 'resets' => 0])); | |
| 157 | + self::assertSame($first['pid'], $second['pid']); | |
| 158 | + } | |
| 159 | + | |
| 124 | 160 | /** |
| 125 | 161 | * @param list<array<string, mixed>> $events |
| 126 | 162 | * @param array<string, mixed> $options runtime options on top of "project_dir" |
| @@ -121,6 +121,42 @@ final class IntegrationTest extends TestCase | |||
| 121 | self::assertSame($first['pid'], $second['pid']); | 121 | self::assertSame($first['pid'], $second['pid']); |
| 122 | } | 122 | } |
| 123 | 123 | ||
| 124 | + public function testRequestHandlerServesInvocationsThroughThePsr7Bridge(): void | ||
| 125 | + { | ||
| 126 | + [$first, $second] = $this->invoke([ | ||
| 127 | + [ | ||
| 128 | + 'path' => '/upload', | ||
| 129 | + 'method' => 'POST', | ||
| 130 | + 'headers' => [ | ||
| 131 | + 'Host' => 'internal.local', | ||
| 132 | + 'Content-Type' => 'multipart/form-data; boundary=b', | ||
| 133 | + 'X-Forwarded-For' => '203.0.113.7', | ||
| 134 | + 'X-Forwarded-Host' => 'api.example.com', | ||
| 135 | + 'X-Forwarded-Proto' => 'https', | ||
| 136 | + ], | ||
| 137 | + 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n" | ||
| 138 | + ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"report.csv\"\r\n\r\na,b\r\n--b--\r\n"), | ||
| 139 | + 'isBase64Encoded' => true, | ||
| 140 | + ], | ||
| 141 | + ['path' => '/', 'headers' => ['Host' => 'internal.local']], | ||
| 142 | + ], ['front_controller' => 'public/request-handler.php']); | ||
| 143 | + | ||
| 144 | + self::assertSame(201, $first['statusCode']); | ||
| 145 | + self::assertIsArray($first['headers']); | ||
| 146 | + self::assertSame(['a', 'b'], $first['headers']['X-Multi'] ?? null); | ||
| 147 | + self::assertSame(['first=1; path=/', 'second=2; path=/'], $first['headers']['Set-Cookie'] ?? null); | ||
| 148 | + $first = $this->json($first); | ||
| 149 | + $second = $this->json($second); | ||
| 150 | + | ||
| 151 | + self::assertSame('https://api.example.com/upload', $first['uri']); | ||
| 152 | + self::assertSame('203.0.113.7', $first['remoteAddr']); | ||
| 153 | + self::assertSame(['title' => 'Report'], $first['parsedBody']); | ||
| 154 | + self::assertSame(['doc' => ['name' => 'report.csv', 'content' => 'a,b']], $first['files']); | ||
| 155 | + self::assertSame([], glob($this->dir.'/tmp/php*'), 'Uploaded files must be deleted after the Invocation.'); | ||
| 156 | + self::assertSame(['uri' => 'http://internal.local/', 'remoteAddr' => '127.0.0.1', 'handled' => 2, 'resets' => 1], array_intersect_key($second, ['uri' => 0, 'remoteAddr' => 0, 'handled' => 0, 'resets' => 0])); | ||
| 157 | + self::assertSame($first['pid'], $second['pid']); | ||
| 158 | + } | ||
| 159 | + | ||
| 124 | /** | 160 | /** |
| 125 | * @param list<array<string, mixed>> $events | 161 | * @param list<array<string, mixed>> $events |
| 126 | * @param array<string, mixed> $options runtime options on top of "project_dir" | 162 | * @param array<string, mixed> $options runtime options on top of "project_dir" |
added
tests/Runner/RequestHandlerKernelTest.php +132 -0 | new file mode 100644 | ||
| @@ -0,0 +1,132 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace JDecool\ScalewayRuntime\Tests\Runner; | |
| 6 | + | |
| 7 | +use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; | |
| 8 | +use JDecool\ScalewayRuntime\Runner\RequestHandlerKernel; | |
| 9 | +use JDecool\ScalewayRuntime\Tests\Fixtures\EchoRequestHandler; | |
| 10 | +use PHPUnit\Framework\TestCase; | |
| 11 | +use Psr\Http\Message\UploadedFileInterface; | |
| 12 | +use Symfony\Component\HttpFoundation\Request; | |
| 13 | + | |
| 14 | +final class RequestHandlerKernelTest extends TestCase | |
| 15 | +{ | |
| 16 | + private EchoRequestHandler $handler; | |
| 17 | + private HttpKernelRunner $runner; | |
| 18 | + | |
| 19 | + protected function setUp(): void | |
| 20 | + { | |
| 21 | + $errorLog = fopen('php://memory', 'w+'); | |
| 22 | + self::assertNotFalse($errorLog); | |
| 23 | + $this->handler = new EchoRequestHandler(); | |
| 24 | + $this->runner = new HttpKernelRunner(new RequestHandlerKernel($this->handler), $errorLog); | |
| 25 | + } | |
| 26 | + | |
| 27 | + protected function tearDown(): void | |
| 28 | + { | |
| 29 | + Request::setTrustedProxies([], 0); | |
| 30 | + } | |
| 31 | + | |
| 32 | + public function testRequestCarriesTheClientBehindThePlatformProxy(): void | |
| 33 | + { | |
| 34 | + $echo = $this->echo([ | |
| 35 | + 'path' => '/items', | |
| 36 | + 'queryStringParameters' => ['page' => '2'], | |
| 37 | + 'headers' => [ | |
| 38 | + 'Host' => 'internal.local', | |
| 39 | + 'X-Forwarded-For' => '203.0.113.7', | |
| 40 | + 'X-Forwarded-Host' => 'api.example.com', | |
| 41 | + 'X-Forwarded-Proto' => 'https', | |
| 42 | + ], | |
| 43 | + ]); | |
| 44 | + | |
| 45 | + self::assertSame('https://api.example.com/items?page=2', $echo['uri']); | |
| 46 | + self::assertSame('203.0.113.7', $echo['remoteAddr']); | |
| 47 | + self::assertSame(['page' => '2'], $echo['query']); | |
| 48 | + } | |
| 49 | + | |
| 50 | + public function testRequestWithoutForwardedHeadersComesFromThePlatformProxy(): void | |
| 51 | + { | |
| 52 | + $echo = $this->echo(['path' => '/', 'headers' => ['Host' => 'internal.local']]); | |
| 53 | + | |
| 54 | + self::assertSame('http://internal.local/', $echo['uri']); | |
| 55 | + self::assertSame('127.0.0.1', $echo['remoteAddr']); | |
| 56 | + } | |
| 57 | + | |
| 58 | + public function testEventWithoutHostGetsAParsableUri(): void | |
| 59 | + { | |
| 60 | + self::assertSame('http://localhost/', $this->echo(['path' => '/'])['uri']); | |
| 61 | + self::assertSame('https://localhost/', $this->echo(['path' => '/', 'headers' => ['X-Forwarded-Proto' => 'https']])['uri']); | |
| 62 | + } | |
| 63 | + | |
| 64 | + public function testBodiesAndUploadsReachTheHandler(): void | |
| 65 | + { | |
| 66 | + $echo = $this->echo([ | |
| 67 | + 'path' => '/', | |
| 68 | + 'method' => 'POST', | |
| 69 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | |
| 70 | + 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n" | |
| 71 | + ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\nhello\r\n--b--\r\n"), | |
| 72 | + 'isBase64Encoded' => true, | |
| 73 | + ]); | |
| 74 | + | |
| 75 | + self::assertSame(['title' => 'Report'], $echo['parsedBody']); | |
| 76 | + self::assertSame(['doc' => ['name' => 'a.txt', 'content' => 'hello']], $echo['files']); | |
| 77 | + $file = $this->handler->lastRequest?->getUploadedFiles()['doc'] ?? null; | |
| 78 | + self::assertInstanceOf(UploadedFileInterface::class, $file); | |
| 79 | + $path = $file->getStream()->getMetadata('uri'); | |
| 80 | + self::assertIsString($path); | |
| 81 | + self::assertFileDoesNotExist($path, 'Uploaded files must be deleted after the Invocation.'); | |
| 82 | + } | |
| 83 | + | |
| 84 | + public function testRawBodyReachesTheHandler(): void | |
| 85 | + { | |
| 86 | + $echo = $this->echo(['path' => '/', 'method' => 'POST', 'headers' => ['Content-Type' => 'application/json'], 'body' => '{"a":1}']); | |
| 87 | + | |
| 88 | + self::assertSame('{"a":1}', $echo['body']); | |
| 89 | + self::assertSame(['a' => 1], $echo['parsedBody']); | |
| 90 | + } | |
| 91 | + | |
| 92 | + public function testResponseKeepsStatusMultiValueHeadersAndCookies(): void | |
| 93 | + { | |
| 94 | + $functionResponse = $this->runner->invoke(['path' => '/'], []); | |
| 95 | + | |
| 96 | + self::assertSame(201, $functionResponse['statusCode']); | |
| 97 | + self::assertSame('application/json', $functionResponse['headers']['Content-Type'] ?? null); | |
| 98 | + self::assertSame(['a', 'b'], $functionResponse['headers']['X-Multi'] ?? null); | |
| 99 | + self::assertSame(['first=1; path=/', 'second=2; path=/'], $functionResponse['headers']['Set-Cookie'] ?? null); | |
| 100 | + } | |
| 101 | + | |
| 102 | + public function testResettableHandlerIsResetBeforeEachInvocationButTheFirst(): void | |
| 103 | + { | |
| 104 | + self::assertSame(0, $this->echo(['path' => '/'])['resets']); | |
| 105 | + self::assertSame(1, $this->echo(['path' => '/'])['resets']); | |
| 106 | + } | |
| 107 | + | |
| 108 | + public function testHandlerIsResetAfterAFailedInvocation(): void | |
| 109 | + { | |
| 110 | + try { | |
| 111 | + $this->runner->invoke(['path' => '/throw'], []); | |
| 112 | + self::fail('The exception must escape to the Handler.'); | |
| 113 | + } catch (\RuntimeException) { | |
| 114 | + } | |
| 115 | + | |
| 116 | + self::assertSame(1, $this->echo(['path' => '/'])['resets']); | |
| 117 | + } | |
| 118 | + | |
| 119 | + /** | |
| 120 | + * @param array<mixed> $event | |
| 121 | + * | |
| 122 | + * @return array<mixed> | |
| 123 | + */ | |
| 124 | + private function echo(array $event): array | |
| 125 | + { | |
| 126 | + $functionResponse = $this->runner->invoke($event, []); | |
| 127 | + $echo = json_decode($functionResponse['body'], true, 512, \JSON_THROW_ON_ERROR); | |
| 128 | + self::assertIsArray($echo); | |
| 129 | + | |
| 130 | + return $echo; | |
| 131 | + } | |
| 132 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,132 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +namespace JDecool\ScalewayRuntime\Tests\Runner; | ||
| 6 | + | ||
| 7 | +use JDecool\ScalewayRuntime\Runner\HttpKernelRunner; | ||
| 8 | +use JDecool\ScalewayRuntime\Runner\RequestHandlerKernel; | ||
| 9 | +use JDecool\ScalewayRuntime\Tests\Fixtures\EchoRequestHandler; | ||
| 10 | +use PHPUnit\Framework\TestCase; | ||
| 11 | +use Psr\Http\Message\UploadedFileInterface; | ||
| 12 | +use Symfony\Component\HttpFoundation\Request; | ||
| 13 | + | ||
| 14 | +final class RequestHandlerKernelTest extends TestCase | ||
| 15 | +{ | ||
| 16 | + private EchoRequestHandler $handler; | ||
| 17 | + private HttpKernelRunner $runner; | ||
| 18 | + | ||
| 19 | + protected function setUp(): void | ||
| 20 | + { | ||
| 21 | + $errorLog = fopen('php://memory', 'w+'); | ||
| 22 | + self::assertNotFalse($errorLog); | ||
| 23 | + $this->handler = new EchoRequestHandler(); | ||
| 24 | + $this->runner = new HttpKernelRunner(new RequestHandlerKernel($this->handler), $errorLog); | ||
| 25 | + } | ||
| 26 | + | ||
| 27 | + protected function tearDown(): void | ||
| 28 | + { | ||
| 29 | + Request::setTrustedProxies([], 0); | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + public function testRequestCarriesTheClientBehindThePlatformProxy(): void | ||
| 33 | + { | ||
| 34 | + $echo = $this->echo([ | ||
| 35 | + 'path' => '/items', | ||
| 36 | + 'queryStringParameters' => ['page' => '2'], | ||
| 37 | + 'headers' => [ | ||
| 38 | + 'Host' => 'internal.local', | ||
| 39 | + 'X-Forwarded-For' => '203.0.113.7', | ||
| 40 | + 'X-Forwarded-Host' => 'api.example.com', | ||
| 41 | + 'X-Forwarded-Proto' => 'https', | ||
| 42 | + ], | ||
| 43 | + ]); | ||
| 44 | + | ||
| 45 | + self::assertSame('https://api.example.com/items?page=2', $echo['uri']); | ||
| 46 | + self::assertSame('203.0.113.7', $echo['remoteAddr']); | ||
| 47 | + self::assertSame(['page' => '2'], $echo['query']); | ||
| 48 | + } | ||
| 49 | + | ||
| 50 | + public function testRequestWithoutForwardedHeadersComesFromThePlatformProxy(): void | ||
| 51 | + { | ||
| 52 | + $echo = $this->echo(['path' => '/', 'headers' => ['Host' => 'internal.local']]); | ||
| 53 | + | ||
| 54 | + self::assertSame('http://internal.local/', $echo['uri']); | ||
| 55 | + self::assertSame('127.0.0.1', $echo['remoteAddr']); | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + public function testEventWithoutHostGetsAParsableUri(): void | ||
| 59 | + { | ||
| 60 | + self::assertSame('http://localhost/', $this->echo(['path' => '/'])['uri']); | ||
| 61 | + self::assertSame('https://localhost/', $this->echo(['path' => '/', 'headers' => ['X-Forwarded-Proto' => 'https']])['uri']); | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + public function testBodiesAndUploadsReachTheHandler(): void | ||
| 65 | + { | ||
| 66 | + $echo = $this->echo([ | ||
| 67 | + 'path' => '/', | ||
| 68 | + 'method' => 'POST', | ||
| 69 | + 'headers' => ['Content-Type' => 'multipart/form-data; boundary=b'], | ||
| 70 | + 'body' => base64_encode("--b\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nReport\r\n" | ||
| 71 | + ."--b\r\nContent-Disposition: form-data; name=\"doc\"; filename=\"a.txt\"\r\n\r\nhello\r\n--b--\r\n"), | ||
| 72 | + 'isBase64Encoded' => true, | ||
| 73 | + ]); | ||
| 74 | + | ||
| 75 | + self::assertSame(['title' => 'Report'], $echo['parsedBody']); | ||
| 76 | + self::assertSame(['doc' => ['name' => 'a.txt', 'content' => 'hello']], $echo['files']); | ||
| 77 | + $file = $this->handler->lastRequest?->getUploadedFiles()['doc'] ?? null; | ||
| 78 | + self::assertInstanceOf(UploadedFileInterface::class, $file); | ||
| 79 | + $path = $file->getStream()->getMetadata('uri'); | ||
| 80 | + self::assertIsString($path); | ||
| 81 | + self::assertFileDoesNotExist($path, 'Uploaded files must be deleted after the Invocation.'); | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + public function testRawBodyReachesTheHandler(): void | ||
| 85 | + { | ||
| 86 | + $echo = $this->echo(['path' => '/', 'method' => 'POST', 'headers' => ['Content-Type' => 'application/json'], 'body' => '{"a":1}']); | ||
| 87 | + | ||
| 88 | + self::assertSame('{"a":1}', $echo['body']); | ||
| 89 | + self::assertSame(['a' => 1], $echo['parsedBody']); | ||
| 90 | + } | ||
| 91 | + | ||
| 92 | + public function testResponseKeepsStatusMultiValueHeadersAndCookies(): void | ||
| 93 | + { | ||
| 94 | + $functionResponse = $this->runner->invoke(['path' => '/'], []); | ||
| 95 | + | ||
| 96 | + self::assertSame(201, $functionResponse['statusCode']); | ||
| 97 | + self::assertSame('application/json', $functionResponse['headers']['Content-Type'] ?? null); | ||
| 98 | + self::assertSame(['a', 'b'], $functionResponse['headers']['X-Multi'] ?? null); | ||
| 99 | + self::assertSame(['first=1; path=/', 'second=2; path=/'], $functionResponse['headers']['Set-Cookie'] ?? null); | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + public function testResettableHandlerIsResetBeforeEachInvocationButTheFirst(): void | ||
| 103 | + { | ||
| 104 | + self::assertSame(0, $this->echo(['path' => '/'])['resets']); | ||
| 105 | + self::assertSame(1, $this->echo(['path' => '/'])['resets']); | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + public function testHandlerIsResetAfterAFailedInvocation(): void | ||
| 109 | + { | ||
| 110 | + try { | ||
| 111 | + $this->runner->invoke(['path' => '/throw'], []); | ||
| 112 | + self::fail('The exception must escape to the Handler.'); | ||
| 113 | + } catch (\RuntimeException) { | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + self::assertSame(1, $this->echo(['path' => '/'])['resets']); | ||
| 117 | + } | ||
| 118 | + | ||
| 119 | + /** | ||
| 120 | + * @param array<mixed> $event | ||
| 121 | + * | ||
| 122 | + * @return array<mixed> | ||
| 123 | + */ | ||
| 124 | + private function echo(array $event): array | ||
| 125 | + { | ||
| 126 | + $functionResponse = $this->runner->invoke($event, []); | ||
| 127 | + $echo = json_decode($functionResponse['body'], true, 512, \JSON_THROW_ON_ERROR); | ||
| 128 | + self::assertIsArray($echo); | ||
| 129 | + | ||
| 130 | + return $echo; | ||
| 131 | + } | ||
| 132 | +} | ||