feat: run Front Controllers returning a ResponseUnverified
The closure is called again for every Invocation, a Request argument receiving the Invocation's Request, instead of serving the Response built at startup as SymfonyRuntime's FrankenPHP worker mode does (ADR 0004). HttpKernelRunner serves it through a ResponseKernel adapter, so the conversions, proxy trust and upload cleanup stay in one place.
d8b9157 parent: eff7276 modified
GLOSSARY.md +1 -1 | @@ -25,7 +25,7 @@ The application's unchanged `public/index.php`, returning the closure that build | ||
| 25 | 25 | _Avoid_: Handler, bootstrap |
| 26 | 26 | |
| 27 | 27 | **Application**: |
| 28 | -The object built by the Front Controller closure (Kernel, PSR-15 handler, Console application, callable). | |
| 28 | +The object built by the Front Controller closure (Kernel, Response, PSR-15 handler, Console application, callable). | |
| 29 | 29 | _Avoid_: App, service |
| 30 | 30 | |
| 31 | 31 | **Warm Process**: |
| @@ -25,7 +25,7 @@ The application's unchanged `public/index.php`, returning the closure that build | |||
| 25 | _Avoid_: Handler, bootstrap | 25 | _Avoid_: Handler, bootstrap |
| 26 | 26 | ||
| 27 | **Application**: | 27 | **Application**: |
| 28 | -The object built by the Front Controller closure (Kernel, PSR-15 handler, Console application, callable). | 28 | +The object built by the Front Controller closure (Kernel, Response, PSR-15 handler, Console application, callable). |
| 29 | _Avoid_: App, service | 29 | _Avoid_: App, service |
| 30 | 30 | ||
| 31 | **Warm Process**: | 31 | **Warm Process**: |
added
docs/adr/0004-call-response-front-controllers-per-invocation.md +11 -0 | new file mode 100644 | ||
| @@ -0,0 +1,11 @@ | ||
| 1 | +# A Front Controller returning a Response is called for every Invocation | |
| 2 | + | |
| 3 | +SymfonyRuntime calls the Front Controller closure once per process: under FPM that is once per request, but its FrankenPHP worker mode serves the Response built at startup to every request, and resolves a `Request` argument from the globals of the worker's startup. | |
| 4 | +In a Warm Process that would freeze the Response (a `StreamedResponse` would even be empty from its second sending on) and make a `Request` argument meaningless. | |
| 5 | +We instead call the closure again for every Invocation, a `Request` argument receiving the Request built from the Invocation's Event, which keeps the FPM semantics and makes `fn (Request $request): Response` a function-like Front Controller. | |
| 6 | + | |
| 7 | +## Consequences | |
| 8 | + | |
| 9 | +- The Application type is only known once the closure has been called, and no Request exists before the first Invocation: a closure taking a `Request` is therefore called per Invocation without a call at startup, and must return a Response every time. | |
| 10 | +- A closure taking no `Request` is called at startup, which in practice runs inside the first Invocation; when it returns a Response, that Response answers the first Invocation and the closure is called again for the next ones. | |
| 11 | +- The closure must be cheap: it runs on every Invocation, unlike a Kernel which is built once (ADR 0002). | |
| new file mode 100644 | |||
| @@ -0,0 +1,11 @@ | |||
| 1 | +# A Front Controller returning a Response is called for every Invocation | ||
| 2 | + | ||
| 3 | +SymfonyRuntime calls the Front Controller closure once per process: under FPM that is once per request, but its FrankenPHP worker mode serves the Response built at startup to every request, and resolves a `Request` argument from the globals of the worker's startup. | ||
| 4 | +In a Warm Process that would freeze the Response (a `StreamedResponse` would even be empty from its second sending on) and make a `Request` argument meaningless. | ||
| 5 | +We instead call the closure again for every Invocation, a `Request` argument receiving the Request built from the Invocation's Event, which keeps the FPM semantics and makes `fn (Request $request): Response` a function-like Front Controller. | ||
| 6 | + | ||
| 7 | +## Consequences | ||
| 8 | + | ||
| 9 | +- The Application type is only known once the closure has been called, and no Request exists before the first Invocation: a closure taking a `Request` is therefore called per Invocation without a call at startup, and must return a Response every time. | ||
| 10 | +- A closure taking no `Request` is called at startup, which in practice runs inside the first Invocation; when it returns a Response, that Response answers the first Invocation and the closure is called again for the next ones. | ||
| 11 | +- The closure must be cheap: it runs on every Invocation, unlike a Kernel which is built once (ADR 0002). | ||
modified
docs/plan.md +1 -0 | @@ -10,6 +10,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc | ||
| 10 | 10 | - The Handler drives `ScalewayRuntime extends SymfonyRuntime` itself, without `vendor/autoload_runtime.php` (ADR 0001). |
| 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 | +- A Front Controller returning a Response is called for every Invocation, a `Request` argument receiving the Invocation's Request (ADR 0004). | |
| 13 | 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. |
| 14 | 15 | - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`). |
| 15 | 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. |
| @@ -10,6 +10,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc | |||
| 10 | - The Handler drives `ScalewayRuntime extends SymfonyRuntime` itself, without `vendor/autoload_runtime.php` (ADR 0001). | 10 | - The Handler drives `ScalewayRuntime extends SymfonyRuntime` itself, without `vendor/autoload_runtime.php` (ADR 0001). |
| 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 | - 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. | 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. |
| 14 | - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`). | 15 | - Errors escaping the Application are logged to stderr and returned as a 500 Function Response (generic body, details when `APP_DEBUG=1`). |
| 15 | - 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. | 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. |
added
src/Runner/ResponseKernel.php +38 -0 | new file mode 100644 | ||
| @@ -0,0 +1,38 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace JDecool\ScalewayRuntime\Runner; | |
| 6 | + | |
| 7 | +use Symfony\Component\HttpFoundation\Request; | |
| 8 | +use Symfony\Component\HttpFoundation\Response; | |
| 9 | +use Symfony\Component\HttpKernel\HttpKernelInterface; | |
| 10 | + | |
| 11 | +/** | |
| 12 | + * Serves a Front Controller returning a Response, so that HttpKernelRunner handles it like any Kernel. | |
| 13 | + * | |
| 14 | + * @internal | |
| 15 | + */ | |
| 16 | +final class ResponseKernel implements HttpKernelInterface | |
| 17 | +{ | |
| 18 | + /** | |
| 19 | + * @param \Closure(Request): mixed $respond calls the Front Controller closure for one Request | |
| 20 | + * @param Response|null $first the Response the closure already returned for the first Invocation | |
| 21 | + */ | |
| 22 | + public function __construct( | |
| 23 | + private readonly \Closure $respond, | |
| 24 | + private ?Response $first = null, | |
| 25 | + ) { | |
| 26 | + } | |
| 27 | + | |
| 28 | + public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response | |
| 29 | + { | |
| 30 | + $response = $this->first ?? ($this->respond)($request); | |
| 31 | + $this->first = null; | |
| 32 | + if (!$response instanceof Response) { | |
| 33 | + throw new \LogicException(\sprintf('A Front Controller returning a Response must return one for every Invocation, "%s" returned.', get_debug_type($response))); | |
| 34 | + } | |
| 35 | + | |
| 36 | + return $response; | |
| 37 | + } | |
| 38 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,38 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +namespace JDecool\ScalewayRuntime\Runner; | ||
| 6 | + | ||
| 7 | +use Symfony\Component\HttpFoundation\Request; | ||
| 8 | +use Symfony\Component\HttpFoundation\Response; | ||
| 9 | +use Symfony\Component\HttpKernel\HttpKernelInterface; | ||
| 10 | + | ||
| 11 | +/** | ||
| 12 | + * Serves a Front Controller returning a Response, so that HttpKernelRunner handles it like any Kernel. | ||
| 13 | + * | ||
| 14 | + * @internal | ||
| 15 | + */ | ||
| 16 | +final class ResponseKernel implements HttpKernelInterface | ||
| 17 | +{ | ||
| 18 | + /** | ||
| 19 | + * @param \Closure(Request): mixed $respond calls the Front Controller closure for one Request | ||
| 20 | + * @param Response|null $first the Response the closure already returned for the first Invocation | ||
| 21 | + */ | ||
| 22 | + public function __construct( | ||
| 23 | + private readonly \Closure $respond, | ||
| 24 | + private ?Response $first = null, | ||
| 25 | + ) { | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + public function handle(Request $request, int $type = self::MAIN_REQUEST, bool $catch = true): Response | ||
| 29 | + { | ||
| 30 | + $response = $this->first ?? ($this->respond)($request); | ||
| 31 | + $this->first = null; | ||
| 32 | + if (!$response instanceof Response) { | ||
| 33 | + throw new \LogicException(\sprintf('A Front Controller returning a Response must return one for every Invocation, "%s" returned.', get_debug_type($response))); | ||
| 34 | + } | ||
| 35 | + | ||
| 36 | + return $response; | ||
| 37 | + } | ||
| 38 | +} | ||
modified
src/ScalewayRuntime.php +37 -1 | @@ -6,6 +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\ResponseKernel; | |
| 10 | +use Symfony\Component\HttpFoundation\Request; | |
| 11 | +use Symfony\Component\HttpFoundation\Response; | |
| 9 | 12 | use Symfony\Component\HttpKernel\HttpKernelInterface; |
| 10 | 13 | use Symfony\Component\Runtime\SymfonyRuntime; |
| 11 | 14 | |
| @@ -18,9 +21,15 @@ use Symfony\Component\Runtime\SymfonyRuntime; | ||
| 18 | 21 | * When the project's var/ directory is not writable (the deployed code may be read-only), |
| 19 | 22 | * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR, |
| 20 | 23 | * while APP_BUILD_DIR keeps the container warmed at build time. |
| 24 | + * | |
| 25 | + * 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). | |
| 21 | 27 | */ |
| 22 | 28 | class ScalewayRuntime extends SymfonyRuntime |
| 23 | 29 | { |
| 30 | + /** The Request of the Invocation the Front Controller closure is being called for. */ | |
| 31 | + private ?Request $request = null; | |
| 32 | + | |
| 24 | 33 | /** |
| 25 | 34 | * @param array<mixed> $options see SymfonyRuntime, plus "front_controller" |
| 26 | 35 | */ |
| @@ -57,12 +66,39 @@ class ScalewayRuntime extends SymfonyRuntime | ||
| 57 | 66 | throw new \TypeError(\sprintf('Invalid return value: callable expected, "%s" returned from "%s".', get_debug_type($app), $file)); |
| 58 | 67 | } |
| 59 | 68 | |
| 60 | - [$app, $args] = $this->getResolver($app)->resolve(); | |
| 69 | + $resolver = $this->getResolver($app); | |
| 70 | + $respond = function (Request $request) use ($resolver): mixed { | |
| 71 | + $this->request = $request; | |
| 72 | + try { | |
| 73 | + [$app, $args] = $resolver->resolve(); | |
| 74 | + | |
| 75 | + return $app(...$args); | |
| 76 | + } finally { | |
| 77 | + $this->request = null; | |
| 78 | + } | |
| 79 | + }; | |
| 80 | + | |
| 81 | + // No Request exists before the first Invocation, so such a closure cannot be called yet. | |
| 82 | + foreach (new \ReflectionFunction($app(...))->getParameters() as $parameter) { | |
| 83 | + $type = $parameter->getType(); | |
| 84 | + if ($type instanceof \ReflectionNamedType && Request::class === $type->getName()) { | |
| 85 | + return new HttpKernelRunner(new ResponseKernel($respond), $errorLog); | |
| 86 | + } | |
| 87 | + } | |
| 88 | + | |
| 89 | + [$app, $args] = $resolver->resolve(); | |
| 61 | 90 | $application = $app(...$args); |
| 62 | 91 | |
| 63 | 92 | return match (true) { |
| 64 | 93 | $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog), |
| 94 | + $application instanceof Response => new HttpKernelRunner(new ResponseKernel($respond, $application), $errorLog), | |
| 65 | 95 | default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))), |
| 66 | 96 | }; |
| 67 | 97 | } |
| 98 | + | |
| 99 | + protected function resolveType(string $type): mixed | |
| 100 | + { | |
| 101 | + // SymfonyRuntime builds it from PHP globals, which never describe an Invocation. | |
| 102 | + return Request::class === $type ? $this->request : parent::resolveType($type); | |
| 103 | + } | |
| 68 | 104 | } |
| @@ -6,6 +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\ResponseKernel; | ||
| 10 | +use Symfony\Component\HttpFoundation\Request; | ||
| 11 | +use Symfony\Component\HttpFoundation\Response; | ||
| 9 | use Symfony\Component\HttpKernel\HttpKernelInterface; | 12 | use Symfony\Component\HttpKernel\HttpKernelInterface; |
| 10 | use Symfony\Component\Runtime\SymfonyRuntime; | 13 | use Symfony\Component\Runtime\SymfonyRuntime; |
| 11 | 14 | ||
| @@ -18,9 +21,15 @@ use Symfony\Component\Runtime\SymfonyRuntime; | |||
| 18 | * When the project's var/ directory is not writable (the deployed code may be read-only), | 21 | * When the project's var/ directory is not writable (the deployed code may be read-only), |
| 19 | * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR, | 22 | * the cache and log dirs move to the system temp dir through APP_CACHE_DIR and APP_LOG_DIR, |
| 20 | * while APP_BUILD_DIR keeps the container warmed at build time. | 23 | * while APP_BUILD_DIR keeps the container warmed at build time. |
| 24 | + * | ||
| 25 | + * 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). | ||
| 21 | */ | 27 | */ |
| 22 | class ScalewayRuntime extends SymfonyRuntime | 28 | class ScalewayRuntime extends SymfonyRuntime |
| 23 | { | 29 | { |
| 30 | + /** The Request of the Invocation the Front Controller closure is being called for. */ | ||
| 31 | + private ?Request $request = null; | ||
| 32 | + | ||
| 24 | /** | 33 | /** |
| 25 | * @param array<mixed> $options see SymfonyRuntime, plus "front_controller" | 34 | * @param array<mixed> $options see SymfonyRuntime, plus "front_controller" |
| 26 | */ | 35 | */ |
| @@ -57,12 +66,39 @@ class ScalewayRuntime extends SymfonyRuntime | |||
| 57 | throw new \TypeError(\sprintf('Invalid return value: callable expected, "%s" returned from "%s".', get_debug_type($app), $file)); | 66 | throw new \TypeError(\sprintf('Invalid return value: callable expected, "%s" returned from "%s".', get_debug_type($app), $file)); |
| 58 | } | 67 | } |
| 59 | 68 | ||
| 60 | - [$app, $args] = $this->getResolver($app)->resolve(); | 69 | + $resolver = $this->getResolver($app); |
| 70 | + $respond = function (Request $request) use ($resolver): mixed { | ||
| 71 | + $this->request = $request; | ||
| 72 | + try { | ||
| 73 | + [$app, $args] = $resolver->resolve(); | ||
| 74 | + | ||
| 75 | + return $app(...$args); | ||
| 76 | + } finally { | ||
| 77 | + $this->request = null; | ||
| 78 | + } | ||
| 79 | + }; | ||
| 80 | + | ||
| 81 | + // No Request exists before the first Invocation, so such a closure cannot be called yet. | ||
| 82 | + foreach (new \ReflectionFunction($app(...))->getParameters() as $parameter) { | ||
| 83 | + $type = $parameter->getType(); | ||
| 84 | + if ($type instanceof \ReflectionNamedType && Request::class === $type->getName()) { | ||
| 85 | + return new HttpKernelRunner(new ResponseKernel($respond), $errorLog); | ||
| 86 | + } | ||
| 87 | + } | ||
| 88 | + | ||
| 89 | + [$app, $args] = $resolver->resolve(); | ||
| 61 | $application = $app(...$args); | 90 | $application = $app(...$args); |
| 62 | 91 | ||
| 63 | return match (true) { | 92 | return match (true) { |
| 64 | $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog), | 93 | $application instanceof HttpKernelInterface => new HttpKernelRunner($application, $errorLog), |
| 94 | + $application instanceof Response => new HttpKernelRunner(new ResponseKernel($respond, $application), $errorLog), | ||
| 65 | default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))), | 95 | default => throw new \LogicException(\sprintf('"%s" cannot run Applications of type "%s".', static::class, get_debug_type($application))), |
| 66 | }; | 96 | }; |
| 67 | } | 97 | } |
| 98 | + | ||
| 99 | + protected function resolveType(string $type): mixed | ||
| 100 | + { | ||
| 101 | + // SymfonyRuntime builds it from PHP globals, which never describe an Invocation. | ||
| 102 | + return Request::class === $type ? $this->request : parent::resolveType($type); | ||
| 103 | + } | ||
| 68 | } | 104 | } |
added
tests/Fixtures/App/public/hello.php +21 -0 | new file mode 100644 | ||
| @@ -0,0 +1,21 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +use Symfony\Component\HttpFoundation\JsonResponse; | |
| 6 | +use Symfony\Component\HttpFoundation\Request; | |
| 7 | + | |
| 8 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 9 | + | |
| 10 | +return static function (Request $request, array $context): JsonResponse { | |
| 11 | + /** @var int $calls */ | |
| 12 | + static $calls = 0; | |
| 13 | + | |
| 14 | + return new JsonResponse([ | |
| 15 | + 'message' => 'Hello '.$request->query->getString('name').'!', | |
| 16 | + 'secure' => $request->isSecure(), | |
| 17 | + 'env' => $context['APP_ENV'], | |
| 18 | + 'calls' => ++$calls, | |
| 19 | + 'pid' => getmypid(), | |
| 20 | + ]); | |
| 21 | +}; | |
| new file mode 100644 | |||
| @@ -0,0 +1,21 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +use Symfony\Component\HttpFoundation\JsonResponse; | ||
| 6 | +use Symfony\Component\HttpFoundation\Request; | ||
| 7 | + | ||
| 8 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 9 | + | ||
| 10 | +return static function (Request $request, array $context): JsonResponse { | ||
| 11 | + /** @var int $calls */ | ||
| 12 | + static $calls = 0; | ||
| 13 | + | ||
| 14 | + return new JsonResponse([ | ||
| 15 | + 'message' => 'Hello '.$request->query->getString('name').'!', | ||
| 16 | + 'secure' => $request->isSecure(), | ||
| 17 | + 'env' => $context['APP_ENV'], | ||
| 18 | + 'calls' => ++$calls, | ||
| 19 | + 'pid' => getmypid(), | ||
| 20 | + ]); | ||
| 21 | +}; | ||
added
tests/Fixtures/front-controllers/request-response.php +10 -0 | new file mode 100644 | ||
| @@ -0,0 +1,10 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +use Symfony\Component\HttpFoundation\Request; | |
| 6 | +use Symfony\Component\HttpFoundation\Response; | |
| 7 | + | |
| 8 | +return static fn (Request $request): ?Response => '/nothing' === $request->getPathInfo() | |
| 9 | + ? null | |
| 10 | + : new Response(sprintf('Hello %s from %s', $request->query->getString('name'), $request->getClientIp())); | |
| new file mode 100644 | |||
| @@ -0,0 +1,10 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +use Symfony\Component\HttpFoundation\Request; | ||
| 6 | +use Symfony\Component\HttpFoundation\Response; | ||
| 7 | + | ||
| 8 | +return static fn (Request $request): ?Response => '/nothing' === $request->getPathInfo() | ||
| 9 | + ? null | ||
| 10 | + : new Response(sprintf('Hello %s from %s', $request->query->getString('name'), $request->getClientIp())); | ||
added
tests/Fixtures/front-controllers/response.php +12 -0 | new file mode 100644 | ||
| @@ -0,0 +1,12 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +use Symfony\Component\HttpFoundation\Response; | |
| 6 | + | |
| 7 | +return static function (): Response { | |
| 8 | + /** @var int $calls */ | |
| 9 | + static $calls = 0; | |
| 10 | + | |
| 11 | + return new Response('call #'.++$calls); | |
| 12 | +}; | |
| new file mode 100644 | |||
| @@ -0,0 +1,12 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +use Symfony\Component\HttpFoundation\Response; | ||
| 6 | + | ||
| 7 | +return static function (): Response { | ||
| 8 | + /** @var int $calls */ | ||
| 9 | + static $calls = 0; | ||
| 10 | + | ||
| 11 | + return new Response('call #'.++$calls); | ||
| 12 | +}; | ||
modified
tests/HandlerTest.php +28 -0 | @@ -103,6 +103,34 @@ final class HandlerTest extends TestCase | ||
| 103 | 103 | self::assertStringContainsString('cannot run Applications of type "stdClass"', $this->errorLog()); |
| 104 | 104 | } |
| 105 | 105 | |
| 106 | + public function testResponseFrontControllerIsCalledForEveryInvocation(): void | |
| 107 | + { | |
| 108 | + $handler = $this->handler(['front_controller' => 'front-controllers/response.php']); | |
| 109 | + | |
| 110 | + self::assertSame('call #1', $handler->invoke([], [])['body']); | |
| 111 | + self::assertSame('call #2', $handler->invoke([], [])['body']); | |
| 112 | + } | |
| 113 | + | |
| 114 | + public function testResponseFrontControllerGetsTheRequestOfEachInvocation(): void | |
| 115 | + { | |
| 116 | + $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php']); | |
| 117 | + | |
| 118 | + $first = $handler->invoke(['queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Forwarded-For' => '203.0.113.7']], []); | |
| 119 | + $second = $handler->invoke(['queryStringParameters' => ['name' => 'Grace']], []); | |
| 120 | + | |
| 121 | + self::assertSame('Hello Ada from 203.0.113.7', $first['body']); | |
| 122 | + self::assertSame('Hello Grace from 127.0.0.1', $second['body']); | |
| 123 | + } | |
| 124 | + | |
| 125 | + public function testResponseFrontControllerReturningSomethingElseFailsTheInvocation(): void | |
| 126 | + { | |
| 127 | + $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php', 'debug' => false]); | |
| 128 | + | |
| 129 | + self::assertSame(500, $handler->invoke(['path' => '/nothing'], [])['statusCode']); | |
| 130 | + self::assertStringContainsString('must return one for every Invocation, "null" returned', $this->errorLog()); | |
| 131 | + self::assertSame(200, $handler->invoke(['path' => '/'], [])['statusCode']); | |
| 132 | + } | |
| 133 | + | |
| 106 | 134 | public function testFrontControllerMustReturnACallable(): void |
| 107 | 135 | { |
| 108 | 136 | $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []); |
| @@ -103,6 +103,34 @@ final class HandlerTest extends TestCase | |||
| 103 | self::assertStringContainsString('cannot run Applications of type "stdClass"', $this->errorLog()); | 103 | self::assertStringContainsString('cannot run Applications of type "stdClass"', $this->errorLog()); |
| 104 | } | 104 | } |
| 105 | 105 | ||
| 106 | + public function testResponseFrontControllerIsCalledForEveryInvocation(): void | ||
| 107 | + { | ||
| 108 | + $handler = $this->handler(['front_controller' => 'front-controllers/response.php']); | ||
| 109 | + | ||
| 110 | + self::assertSame('call #1', $handler->invoke([], [])['body']); | ||
| 111 | + self::assertSame('call #2', $handler->invoke([], [])['body']); | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + public function testResponseFrontControllerGetsTheRequestOfEachInvocation(): void | ||
| 115 | + { | ||
| 116 | + $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php']); | ||
| 117 | + | ||
| 118 | + $first = $handler->invoke(['queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Forwarded-For' => '203.0.113.7']], []); | ||
| 119 | + $second = $handler->invoke(['queryStringParameters' => ['name' => 'Grace']], []); | ||
| 120 | + | ||
| 121 | + self::assertSame('Hello Ada from 203.0.113.7', $first['body']); | ||
| 122 | + self::assertSame('Hello Grace from 127.0.0.1', $second['body']); | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + public function testResponseFrontControllerReturningSomethingElseFailsTheInvocation(): void | ||
| 126 | + { | ||
| 127 | + $handler = $this->handler(['front_controller' => 'front-controllers/request-response.php', 'debug' => false]); | ||
| 128 | + | ||
| 129 | + self::assertSame(500, $handler->invoke(['path' => '/nothing'], [])['statusCode']); | ||
| 130 | + self::assertStringContainsString('must return one for every Invocation, "null" returned', $this->errorLog()); | ||
| 131 | + self::assertSame(200, $handler->invoke(['path' => '/'], [])['statusCode']); | ||
| 132 | + } | ||
| 133 | + | ||
| 106 | public function testFrontControllerMustReturnACallable(): void | 134 | public function testFrontControllerMustReturnACallable(): void |
| 107 | { | 135 | { |
| 108 | $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []); | 136 | $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []); |
modified
tests/IntegrationTest.php +21 -2 | @@ -103,12 +103,31 @@ final class IntegrationTest extends TestCase | ||
| 103 | 103 | self::assertSame($this->projectDir.'/var/cache/prod', $state['buildDir']); |
| 104 | 104 | } |
| 105 | 105 | |
| 106 | + public function testResponseFrontControllerIsCalledForEveryInvocationWithItsRequest(): void | |
| 107 | + { | |
| 108 | + [$first, $second] = $this->invoke([ | |
| 109 | + ['path' => '/', 'queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Forwarded-Proto' => 'https']], | |
| 110 | + ['path' => '/', 'queryStringParameters' => ['name' => 'Grace']], | |
| 111 | + ], ['front_controller' => 'public/hello.php']); | |
| 112 | + | |
| 113 | + self::assertSame(200, $first['statusCode']); | |
| 114 | + self::assertIsArray($first['headers']); | |
| 115 | + self::assertSame('application/json', $first['headers']['Content-Type'] ?? null); | |
| 116 | + $first = $this->json($first); | |
| 117 | + $second = $this->json($second); | |
| 118 | + | |
| 119 | + self::assertSame(['message' => 'Hello Ada!', 'secure' => true, 'env' => 'prod', 'calls' => 1], array_diff_key($first, ['pid' => 0])); | |
| 120 | + self::assertSame(['message' => 'Hello Grace!', 'secure' => false, 'env' => 'prod', 'calls' => 2], array_diff_key($second, ['pid' => 0])); | |
| 121 | + self::assertSame($first['pid'], $second['pid']); | |
| 122 | + } | |
| 123 | + | |
| 106 | 124 | /** |
| 107 | 125 | * @param list<array<string, mixed>> $events |
| 126 | + * @param array<string, mixed> $options runtime options on top of "project_dir" | |
| 108 | 127 | * |
| 109 | 128 | * @return array<array<mixed>> |
| 110 | 129 | */ |
| 111 | - private function invoke(array $events): array | |
| 130 | + private function invoke(array $events, array $options = []): array | |
| 112 | 131 | { |
| 113 | 132 | $driver = 'require $argv[1]; echo json_encode(array_map(fn ($event) => handle($event, []), json_decode(stream_get_contents(STDIN), true)));'; |
| 114 | 133 | $process = proc_open( |
| @@ -119,7 +138,7 @@ final class IntegrationTest extends TestCase | ||
| 119 | 138 | [ |
| 120 | 139 | 'APP_ENV' => 'prod', |
| 121 | 140 | 'APP_DEBUG' => '0', |
| 122 | - 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir], \JSON_THROW_ON_ERROR), | |
| 141 | + 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR), | |
| 123 | 142 | 'TMPDIR' => $this->dir.'/tmp', |
| 124 | 143 | 'PATH' => getenv('PATH') ?: '', |
| 125 | 144 | ], |
| @@ -103,12 +103,31 @@ final class IntegrationTest extends TestCase | |||
| 103 | self::assertSame($this->projectDir.'/var/cache/prod', $state['buildDir']); | 103 | self::assertSame($this->projectDir.'/var/cache/prod', $state['buildDir']); |
| 104 | } | 104 | } |
| 105 | 105 | ||
| 106 | + public function testResponseFrontControllerIsCalledForEveryInvocationWithItsRequest(): void | ||
| 107 | + { | ||
| 108 | + [$first, $second] = $this->invoke([ | ||
| 109 | + ['path' => '/', 'queryStringParameters' => ['name' => 'Ada'], 'headers' => ['X-Forwarded-Proto' => 'https']], | ||
| 110 | + ['path' => '/', 'queryStringParameters' => ['name' => 'Grace']], | ||
| 111 | + ], ['front_controller' => 'public/hello.php']); | ||
| 112 | + | ||
| 113 | + self::assertSame(200, $first['statusCode']); | ||
| 114 | + self::assertIsArray($first['headers']); | ||
| 115 | + self::assertSame('application/json', $first['headers']['Content-Type'] ?? null); | ||
| 116 | + $first = $this->json($first); | ||
| 117 | + $second = $this->json($second); | ||
| 118 | + | ||
| 119 | + self::assertSame(['message' => 'Hello Ada!', 'secure' => true, 'env' => 'prod', 'calls' => 1], array_diff_key($first, ['pid' => 0])); | ||
| 120 | + self::assertSame(['message' => 'Hello Grace!', 'secure' => false, 'env' => 'prod', 'calls' => 2], array_diff_key($second, ['pid' => 0])); | ||
| 121 | + self::assertSame($first['pid'], $second['pid']); | ||
| 122 | + } | ||
| 123 | + | ||
| 106 | /** | 124 | /** |
| 107 | * @param list<array<string, mixed>> $events | 125 | * @param list<array<string, mixed>> $events |
| 126 | + * @param array<string, mixed> $options runtime options on top of "project_dir" | ||
| 108 | * | 127 | * |
| 109 | * @return array<array<mixed>> | 128 | * @return array<array<mixed>> |
| 110 | */ | 129 | */ |
| 111 | - private function invoke(array $events): array | 130 | + private function invoke(array $events, array $options = []): array |
| 112 | { | 131 | { |
| 113 | $driver = 'require $argv[1]; echo json_encode(array_map(fn ($event) => handle($event, []), json_decode(stream_get_contents(STDIN), true)));'; | 132 | $driver = 'require $argv[1]; echo json_encode(array_map(fn ($event) => handle($event, []), json_decode(stream_get_contents(STDIN), true)));'; |
| 114 | $process = proc_open( | 133 | $process = proc_open( |
| @@ -119,7 +138,7 @@ final class IntegrationTest extends TestCase | |||
| 119 | [ | 138 | [ |
| 120 | 'APP_ENV' => 'prod', | 139 | 'APP_ENV' => 'prod', |
| 121 | 'APP_DEBUG' => '0', | 140 | 'APP_DEBUG' => '0', |
| 122 | - 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir], \JSON_THROW_ON_ERROR), | 141 | + 'APP_RUNTIME_OPTIONS' => json_encode(['project_dir' => $this->projectDir] + $options, \JSON_THROW_ON_ERROR), |
| 123 | 'TMPDIR' => $this->dir.'/tmp', | 142 | 'TMPDIR' => $this->dir.'/tmp', |
| 124 | 'PATH' => getenv('PATH') ?: '', | 143 | 'PATH' => getenv('PATH') ?: '', |
| 125 | ], | 144 | ], |