jdecool/scaleway-runtimepublic Fork
⑂ f833a3d
Commits
⬇ Clone ▾
git clone https://git.rickub.com/jdecool/scaleway-runtime.git
git clone ssh://git@rickub.com/jdecool/scaleway-runtime.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

feat: run Front Controllers returning a raw callableUnverified

A Closure returned by the Front Controller closure is built once per Warm
Process and gets every Event and context untouched, CRON Invocations
included without Command Invocation routing. Its return value is checked
against the documented Function Response shape, anything else being a 500.
Jérémy DECOOL committed 2026-11-14T02:12:10+01:00 Browse files
f833a3d parent: e9c211e
modified docs/plan.md +2 -1
@@ -18,6 +18,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc
1818 - `vendor/bin/scaleway-package` builds a zip with `vendor/` (`--no-dev --classmap-authoritative`, from `composer.lock`) and a warmed prod cache, excluding `var/`, `tests/`, `.env.local` (ADR 0003).
1919 - CRON Invocations become `POST /` HTTP requests by default; a JSON body `{"command": "...", "args": {...}, "secret": "..."}` whose secret matches `SCALEWAY_CRON_SECRET` makes it a Command Invocation run through the Console Application of the same Kernel, non-interactive, `args` mapped to an `ArrayInput`; the exit code 0 yields a 200 and any other a 500, both with the command output (ADR 0005).
2020 - A Front Controller returning a Console `Application` or a `Command` serves Command Invocations only and answers a 403 to the others; services are reset before and after each command, as no HTTP request follows to trigger the Kernel's own reset.
21+- A Front Controller closure returning a `Closure` makes it a raw callable `fn (array $event, mixed $context): array`, built once like a Kernel (GenericRuntime would run it as a zero-argument script, meaningless per Invocation; invokable objects keep their type-based dispatch, a `$object(...)` turns one into a raw callable); it gets every Event and context untouched, CRON Invocations included without Command Invocation routing (raw means raw), and its return value must be the documented Function Response shape (int `statusCode`, `headers` of strings or lists of strings, string `body`, optional bool `isBase64Encoded`), undocumented keys dropped, anything else being a 500.
2122 - Tests: PHPUnit on conversions, GitHub Actions CI (PHPUnit, PHPStan max, PHP-CS-Fixer; PHP 8.4/8.5 x Symfony 7.4/8.x), local Emulator `vendor/bin/scaleway-serve`, manual real E2E deployed with Terraform.
2223
2324 ## Phases
@@ -30,5 +31,5 @@ Each phase ends with green CI checks locally, a commit series, and an independen
3031 4. **Response Application**: a Front Controller returning a Symfony `Response`.
3132 5. **PSR-15 Application**: `RequestHandlerInterface` via `symfony/psr-http-message-bridge` and `nyholm/psr7` (suggested dependencies).
3233 6. **Console Application and CRON routing**: Command Invocations, Console `Application` / `Command` Front Controllers.
33-7. **Raw callable Application**: `fn(array $event, array $context): array`.
34+7. **Raw callable Application**: `fn(array $event, mixed $context): array`.
3435 8. **Documentation**: full README (install, configure, deploy, limitations), probe results folded into the docs.
@@ -18,6 +18,7 @@ Vocabulary follows [GLOSSARY.md](../GLOSSARY.md); decisions are recorded in [doc
18 - `vendor/bin/scaleway-package` builds a zip with `vendor/` (`--no-dev --classmap-authoritative`, from `composer.lock`) and a warmed prod cache, excluding `var/`, `tests/`, `.env.local` (ADR 0003).18 - `vendor/bin/scaleway-package` builds a zip with `vendor/` (`--no-dev --classmap-authoritative`, from `composer.lock`) and a warmed prod cache, excluding `var/`, `tests/`, `.env.local` (ADR 0003).
19 - CRON Invocations become `POST /` HTTP requests by default; a JSON body `{"command": "...", "args": {...}, "secret": "..."}` whose secret matches `SCALEWAY_CRON_SECRET` makes it a Command Invocation run through the Console Application of the same Kernel, non-interactive, `args` mapped to an `ArrayInput`; the exit code 0 yields a 200 and any other a 500, both with the command output (ADR 0005).19 - CRON Invocations become `POST /` HTTP requests by default; a JSON body `{"command": "...", "args": {...}, "secret": "..."}` whose secret matches `SCALEWAY_CRON_SECRET` makes it a Command Invocation run through the Console Application of the same Kernel, non-interactive, `args` mapped to an `ArrayInput`; the exit code 0 yields a 200 and any other a 500, both with the command output (ADR 0005).
20 - A Front Controller returning a Console `Application` or a `Command` serves Command Invocations only and answers a 403 to the others; services are reset before and after each command, as no HTTP request follows to trigger the Kernel's own reset.20 - A Front Controller returning a Console `Application` or a `Command` serves Command Invocations only and answers a 403 to the others; services are reset before and after each command, as no HTTP request follows to trigger the Kernel's own reset.
21+- A Front Controller closure returning a `Closure` makes it a raw callable `fn (array $event, mixed $context): array`, built once like a Kernel (GenericRuntime would run it as a zero-argument script, meaningless per Invocation; invokable objects keep their type-based dispatch, a `$object(...)` turns one into a raw callable); it gets every Event and context untouched, CRON Invocations included without Command Invocation routing (raw means raw), and its return value must be the documented Function Response shape (int `statusCode`, `headers` of strings or lists of strings, string `body`, optional bool `isBase64Encoded`), undocumented keys dropped, anything else being a 500.
21 - Tests: PHPUnit on conversions, GitHub Actions CI (PHPUnit, PHPStan max, PHP-CS-Fixer; PHP 8.4/8.5 x Symfony 7.4/8.x), local Emulator `vendor/bin/scaleway-serve`, manual real E2E deployed with Terraform.22 - Tests: PHPUnit on conversions, GitHub Actions CI (PHPUnit, PHPStan max, PHP-CS-Fixer; PHP 8.4/8.5 x Symfony 7.4/8.x), local Emulator `vendor/bin/scaleway-serve`, manual real E2E deployed with Terraform.
22 23
23 ## Phases24 ## Phases
@@ -30,5 +31,5 @@ Each phase ends with green CI checks locally, a commit series, and an independen
30 4. **Response Application**: a Front Controller returning a Symfony `Response`.31 4. **Response Application**: a Front Controller returning a Symfony `Response`.
31 5. **PSR-15 Application**: `RequestHandlerInterface` via `symfony/psr-http-message-bridge` and `nyholm/psr7` (suggested dependencies).32 5. **PSR-15 Application**: `RequestHandlerInterface` via `symfony/psr-http-message-bridge` and `nyholm/psr7` (suggested dependencies).
32 6. **Console Application and CRON routing**: Command Invocations, Console `Application` / `Command` Front Controllers.33 6. **Console Application and CRON routing**: Command Invocations, Console `Application` / `Command` Front Controllers.
33-7. **Raw callable Application**: `fn(array $event, array $context): array`.34+7. **Raw callable Application**: `fn(array $event, mixed $context): array`.
34 8. **Documentation**: full README (install, configure, deploy, limitations), probe results folded into the docs.35 8. **Documentation**: full README (install, configure, deploy, limitations), probe results folded into the docs.
modified src/HttpConverter.php +1 -1
@@ -12,7 +12,7 @@ use Symfony\Component\HttpFoundation\Response;
1212 /**
1313 * Converts an Event into a Symfony Request, and a Symfony Response into a Function Response.
1414 *
15- * @phpstan-type FunctionResponse array{statusCode: int, headers: array<string, string|list<string>>, body: string, isBase64Encoded?: true}
15+ * @phpstan-type FunctionResponse array{statusCode: int, headers: array<string, string|list<string>>, body: string, isBase64Encoded?: bool}
1616 */
1717 final class HttpConverter
1818 {
@@ -12,7 +12,7 @@ use Symfony\Component\HttpFoundation\Response;
12 /**12 /**
13 * Converts an Event into a Symfony Request, and a Symfony Response into a Function Response.13 * Converts an Event into a Symfony Request, and a Symfony Response into a Function Response.
14 *14 *
15- * @phpstan-type FunctionResponse array{statusCode: int, headers: array<string, string|list<string>>, body: string, isBase64Encoded?: true}15+ * @phpstan-type FunctionResponse array{statusCode: int, headers: array<string, string|list<string>>, body: string, isBase64Encoded?: bool}
16 */16 */
17 final class HttpConverter17 final class HttpConverter
18 {18 {
added src/Runner/CallableRunner.php +55 -0
new file mode 100644
@@ -0,0 +1,55 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Runner;
6+
7+/**
8+ * Hands each Event and context to a raw callable, and the Function Response it returns back to Scaleway.
9+ *
10+ * Raw means raw: there is no HTTP conversion and no Command Invocation routing, CRON Invocations included;
11+ * the callable owns whatever state it keeps across Invocations.
12+ */
13+final readonly class CallableRunner implements InvocationRunner
14+{
15+ /**
16+ * @param \Closure(array<mixed>, mixed): mixed $callable
17+ */
18+ public function __construct(
19+ private \Closure $callable,
20+ ) {
21+ }
22+
23+ public function invoke(array $event, mixed $context): array
24+ {
25+ $response = ($this->callable)($event, $context);
26+
27+ // Scaleway only documents this shape for PHP, and what it makes of anything else is unknown: keys it does
28+ // not document are dropped rather than passed along.
29+ $fields = \is_array($response) ? $response : [];
30+ $statusCode = $fields['statusCode'] ?? null;
31+ $headers = $fields['headers'] ?? null;
32+ $body = $fields['body'] ?? null;
33+ $base64 = $fields['isBase64Encoded'] ?? false;
34+ if (!\is_int($statusCode) || !self::isHeaders($headers) || !\is_string($body) || !\is_bool($base64)) {
35+ throw new \UnexpectedValueException(\sprintf('A raw callable must return a Function Response: an array with an int "statusCode", "headers" mapping names to a string or a list of strings, a string "body" and an optional bool "isBase64Encoded"; "%s" returned.', get_debug_type($response)));
36+ }
37+
38+ $functionResponse = ['statusCode' => $statusCode, 'headers' => $headers, 'body' => $body];
39+ if (\array_key_exists('isBase64Encoded', $fields)) {
40+ $functionResponse['isBase64Encoded'] = $base64;
41+ }
42+
43+ return $functionResponse;
44+ }
45+
46+ /**
47+ * @phpstan-assert-if-true array<string, string|list<string>> $headers
48+ */
49+ private static function isHeaders(mixed $headers): bool
50+ {
51+ // Closures rather than is_string(...), as array_all() passes the key too and internal functions reject extra arguments.
52+ return \is_array($headers) && array_all($headers, static fn (mixed $value, int|string $name): bool => \is_string($name)
53+ && (\is_string($value) || \is_array($value) && array_is_list($value) && array_all($value, static fn (mixed $item): bool => \is_string($item))));
54+ }
55+}
new file mode 100644
@@ -0,0 +1,55 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Runner;
6+
7+/**
8+ * Hands each Event and context to a raw callable, and the Function Response it returns back to Scaleway.
9+ *
10+ * Raw means raw: there is no HTTP conversion and no Command Invocation routing, CRON Invocations included;
11+ * the callable owns whatever state it keeps across Invocations.
12+ */
13+final readonly class CallableRunner implements InvocationRunner
14+{
15+ /**
16+ * @param \Closure(array<mixed>, mixed): mixed $callable
17+ */
18+ public function __construct(
19+ private \Closure $callable,
20+ ) {
21+ }
22+
23+ public function invoke(array $event, mixed $context): array
24+ {
25+ $response = ($this->callable)($event, $context);
26+
27+ // Scaleway only documents this shape for PHP, and what it makes of anything else is unknown: keys it does
28+ // not document are dropped rather than passed along.
29+ $fields = \is_array($response) ? $response : [];
30+ $statusCode = $fields['statusCode'] ?? null;
31+ $headers = $fields['headers'] ?? null;
32+ $body = $fields['body'] ?? null;
33+ $base64 = $fields['isBase64Encoded'] ?? false;
34+ if (!\is_int($statusCode) || !self::isHeaders($headers) || !\is_string($body) || !\is_bool($base64)) {
35+ throw new \UnexpectedValueException(\sprintf('A raw callable must return a Function Response: an array with an int "statusCode", "headers" mapping names to a string or a list of strings, a string "body" and an optional bool "isBase64Encoded"; "%s" returned.', get_debug_type($response)));
36+ }
37+
38+ $functionResponse = ['statusCode' => $statusCode, 'headers' => $headers, 'body' => $body];
39+ if (\array_key_exists('isBase64Encoded', $fields)) {
40+ $functionResponse['isBase64Encoded'] = $base64;
41+ }
42+
43+ return $functionResponse;
44+ }
45+
46+ /**
47+ * @phpstan-assert-if-true array<string, string|list<string>> $headers
48+ */
49+ private static function isHeaders(mixed $headers): bool
50+ {
51+ // Closures rather than is_string(...), as array_all() passes the key too and internal functions reject extra arguments.
52+ return \is_array($headers) && array_all($headers, static fn (mixed $value, int|string $name): bool => \is_string($name)
53+ && (\is_string($value) || \is_array($value) && array_is_list($value) && array_all($value, static fn (mixed $item): bool => \is_string($item))));
54+ }
55+}
modified src/ScalewayRuntime.php +10 -0
@@ -4,6 +4,7 @@ declare(strict_types=1);
44
55 namespace JDecool\ScalewayRuntime;
66
7+use JDecool\ScalewayRuntime\Runner\CallableRunner;
78 use JDecool\ScalewayRuntime\Runner\ConsoleRunner;
89 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;
910 use JDecool\ScalewayRuntime\Runner\InvocationRunner;
@@ -35,6 +36,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
3536 *
3637 * Command Invocations run through the Console Application of a Kernel, or of a Front Controller returning a
3738 * Console Application or a Command, which then answers any other Invocation with a 403.
39+ *
40+ * A Closure returned by the Front Controller closure is a raw callable, built once and reused like a Kernel:
41+ * it gets every Event and context as they are, CRON Invocations included, and returns the Function Response.
3842 */
3943 class ScalewayRuntime extends SymfonyRuntime
4044 {
@@ -100,6 +104,12 @@ class ScalewayRuntime extends SymfonyRuntime
100104 [$app, $args] = $resolver->resolve();
101105 $application = $app(...$args);
102106
107+ // GenericRuntime would run a returned Closure as a script taking no arguments, which means nothing per
108+ // Invocation; objects keep being dispatched on their type, so an invokable one is never taken for it.
109+ if ($application instanceof \Closure) {
110+ return new CallableRunner($application);
111+ }
112+
103113 if ($application instanceof Command) {
104114 $command = $application;
105115 $application = new Application();
@@ -4,6 +4,7 @@ declare(strict_types=1);
4 4
5 namespace JDecool\ScalewayRuntime;5 namespace JDecool\ScalewayRuntime;
6 6
7+use JDecool\ScalewayRuntime\Runner\CallableRunner;
7 use JDecool\ScalewayRuntime\Runner\ConsoleRunner;8 use JDecool\ScalewayRuntime\Runner\ConsoleRunner;
8 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;9 use JDecool\ScalewayRuntime\Runner\HttpKernelRunner;
9 use JDecool\ScalewayRuntime\Runner\InvocationRunner;10 use JDecool\ScalewayRuntime\Runner\InvocationRunner;
@@ -35,6 +36,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
35 *36 *
36 * Command Invocations run through the Console Application of a Kernel, or of a Front Controller returning a37 * Command Invocations run through the Console Application of a Kernel, or of a Front Controller returning a
37 * Console Application or a Command, which then answers any other Invocation with a 403.38 * Console Application or a Command, which then answers any other Invocation with a 403.
39+ *
40+ * A Closure returned by the Front Controller closure is a raw callable, built once and reused like a Kernel:
41+ * it gets every Event and context as they are, CRON Invocations included, and returns the Function Response.
38 */42 */
39 class ScalewayRuntime extends SymfonyRuntime43 class ScalewayRuntime extends SymfonyRuntime
40 {44 {
@@ -100,6 +104,12 @@ class ScalewayRuntime extends SymfonyRuntime
100 [$app, $args] = $resolver->resolve();104 [$app, $args] = $resolver->resolve();
101 $application = $app(...$args);105 $application = $app(...$args);
102 106
107+ // GenericRuntime would run a returned Closure as a script taking no arguments, which means nothing per
108+ // Invocation; objects keep being dispatched on their type, so an invokable one is never taken for it.
109+ if ($application instanceof \Closure) {
110+ return new CallableRunner($application);
111+ }
112+
103 if ($application instanceof Command) {113 if ($application instanceof Command) {
104 $command = $application;114 $command = $application;
105 $application = new Application();115 $application = new Application();
added tests/Fixtures/App/public/raw.php +17 -0
new file mode 100644
@@ -0,0 +1,17 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
6+
7+return static function (): Closure {
8+ $calls = 0;
9+
10+ return static function (array $event, mixed $context) use (&$calls): array {
11+ return [
12+ 'statusCode' => 200,
13+ 'headers' => ['Content-Type' => 'application/json'],
14+ 'body' => json_encode(['event' => $event, 'calls' => ++$calls, 'pid' => getmypid()], \JSON_THROW_ON_ERROR),
15+ ];
16+ };
17+};
new file mode 100644
@@ -0,0 +1,17 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
6+
7+return static function (): Closure {
8+ $calls = 0;
9+
10+ return static function (array $event, mixed $context) use (&$calls): array {
11+ return [
12+ 'statusCode' => 200,
13+ 'headers' => ['Content-Type' => 'application/json'],
14+ 'body' => json_encode(['event' => $event, 'calls' => ++$calls, 'pid' => getmypid()], \JSON_THROW_ON_ERROR),
15+ ];
16+ };
17+};
added tests/Fixtures/front-controllers/raw.php +34 -0
new file mode 100644
@@ -0,0 +1,34 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;
6+
7+// Counts its builds in RecordingKernel::$builds, and fails while RecordingKernel::$failingBuilds is positive.
8+return static function (): Closure {
9+ ++RecordingKernel::$builds;
10+ if (RecordingKernel::$failingBuilds > 0) {
11+ --RecordingKernel::$failingBuilds;
12+
13+ throw new RuntimeException('Build failed on purpose.');
14+ }
15+ $calls = 0;
16+
17+ return static function (array $event, mixed $context) use (&$calls): mixed {
18+ ++$calls;
19+
20+ return match ($event['path'] ?? null) {
21+ '/throw' => throw new LogicException('Escaped on purpose.'),
22+ '/invalid' => ['statusCode' => '200', 'headers' => [], 'body' => 'not an int status'],
23+ '/bad-header' => ['statusCode' => 200, 'headers' => ['X-Bad' => ['a' => 'b']], 'body' => ''],
24+ '/string' => 'plain body',
25+ default => [
26+ 'statusCode' => 202,
27+ 'headers' => ['Content-Type' => 'application/json', 'X-Multi' => ['a', 'b']],
28+ 'body' => json_encode(['calls' => $calls, 'event' => $event, 'context' => $context], \JSON_THROW_ON_ERROR),
29+ 'isBase64Encoded' => false,
30+ 'multiValueHeaders' => [],
31+ ],
32+ };
33+ };
34+};
new file mode 100644
@@ -0,0 +1,34 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+use JDecool\ScalewayRuntime\Tests\Fixtures\RecordingKernel;
6+
7+// Counts its builds in RecordingKernel::$builds, and fails while RecordingKernel::$failingBuilds is positive.
8+return static function (): Closure {
9+ ++RecordingKernel::$builds;
10+ if (RecordingKernel::$failingBuilds > 0) {
11+ --RecordingKernel::$failingBuilds;
12+
13+ throw new RuntimeException('Build failed on purpose.');
14+ }
15+ $calls = 0;
16+
17+ return static function (array $event, mixed $context) use (&$calls): mixed {
18+ ++$calls;
19+
20+ return match ($event['path'] ?? null) {
21+ '/throw' => throw new LogicException('Escaped on purpose.'),
22+ '/invalid' => ['statusCode' => '200', 'headers' => [], 'body' => 'not an int status'],
23+ '/bad-header' => ['statusCode' => 200, 'headers' => ['X-Bad' => ['a' => 'b']], 'body' => ''],
24+ '/string' => 'plain body',
25+ default => [
26+ 'statusCode' => 202,
27+ 'headers' => ['Content-Type' => 'application/json', 'X-Multi' => ['a', 'b']],
28+ 'body' => json_encode(['calls' => $calls, 'event' => $event, 'context' => $context], \JSON_THROW_ON_ERROR),
29+ 'isBase64Encoded' => false,
30+ 'multiValueHeaders' => [],
31+ ],
32+ };
33+ };
34+};
modified tests/HandlerTest.php +62 -0
@@ -258,6 +258,68 @@ final class HandlerTest extends TestCase
258258 self::assertSame('handled #1 /', $handler->invoke(['path' => '/'], [])['body']);
259259 }
260260
261+ public function testRawCallableIsBuiltOnceAndGetsEveryEventAndContextUntouched(): void
262+ {
263+ $handler = $this->handler(['front_controller' => 'front-controllers/raw.php']);
264+ $event = ['path' => '/', 'httpMethod' => 'GET', 'headers' => ['X-Forwarded-For' => '203.0.113.7'], 'body' => 'raw'];
265+
266+ $first = $handler->invoke($event, ['memoryLimitInMb' => 128]);
267+ $second = $handler->invoke(['path' => '/again'], null);
268+
269+ self::assertSame(202, $first['statusCode']);
270+ self::assertSame(['Content-Type' => 'application/json', 'X-Multi' => ['a', 'b']], $first['headers']);
271+ self::assertFalse($first['isBase64Encoded'] ?? null);
272+ self::assertArrayNotHasKey('multiValueHeaders', $first, 'Keys Scaleway does not document must be dropped.');
273+ self::assertSame(['calls' => 1, 'event' => $event, 'context' => ['memoryLimitInMb' => 128]], $this->decode($first));
274+ self::assertSame(['calls' => 2, 'event' => ['path' => '/again'], 'context' => null], $this->decode($second));
275+ self::assertSame(1, RecordingKernel::$builds);
276+ }
277+
278+ public function testRawCallableGetsCommandInvocationsAsPlainEvents(): void
279+ {
280+ $event = $this->commandEvent('app:greet');
281+
282+ $response = $this->handler(['front_controller' => 'front-controllers/raw.php'])->invoke($event, []);
283+
284+ self::assertSame($event, $this->decode($response)['event']);
285+ }
286+
287+ public function testFailedRawCallableBuildIsRetriedOnNextInvocation(): void
288+ {
289+ RecordingKernel::$failingBuilds = 1;
290+ $handler = $this->handler(['front_controller' => 'front-controllers/raw.php', 'debug' => false]);
291+
292+ self::assertSame(500, $handler->invoke([], [])['statusCode']);
293+ self::assertStringContainsString('Build failed on purpose.', $this->errorLog());
294+ self::assertSame(202, $handler->invoke([], [])['statusCode']);
295+ self::assertSame(2, RecordingKernel::$builds);
296+ }
297+
298+ /**
299+ * @return iterable<string, array{string, string}>
300+ */
301+ public static function failingRawCallables(): iterable
302+ {
303+ yield 'exception' => ['/throw', 'LogicException: Escaped on purpose.'];
304+ yield 'non-int status' => ['/invalid', 'must return a Function Response'];
305+ yield 'nested header value' => ['/bad-header', 'must return a Function Response'];
306+ yield 'plain string' => ['/string', '"string" returned'];
307+ }
308+
309+ #[DataProvider('failingRawCallables')]
310+ public function testFailingRawCallableIsA500AndTheProcessKeepsServing(string $path, string $message): void
311+ {
312+ $handler = $this->handler(['front_controller' => 'front-controllers/raw.php', 'debug' => false]);
313+
314+ self::assertSame([
315+ 'statusCode' => 500,
316+ 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'],
317+ 'body' => 'Internal Server Error',
318+ ], $handler->invoke(['path' => $path], []));
319+ self::assertStringContainsString($message, $this->errorLog());
320+ self::assertSame(['calls' => 2], array_intersect_key($this->decode($handler->invoke([], [])), ['calls' => 0]));
321+ }
322+
261323 public function testFrontControllerMustReturnACallable(): void
262324 {
263325 $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []);
@@ -258,6 +258,68 @@ final class HandlerTest extends TestCase
258 self::assertSame('handled #1 /', $handler->invoke(['path' => '/'], [])['body']);258 self::assertSame('handled #1 /', $handler->invoke(['path' => '/'], [])['body']);
259 }259 }
260 260
261+ public function testRawCallableIsBuiltOnceAndGetsEveryEventAndContextUntouched(): void
262+ {
263+ $handler = $this->handler(['front_controller' => 'front-controllers/raw.php']);
264+ $event = ['path' => '/', 'httpMethod' => 'GET', 'headers' => ['X-Forwarded-For' => '203.0.113.7'], 'body' => 'raw'];
265+
266+ $first = $handler->invoke($event, ['memoryLimitInMb' => 128]);
267+ $second = $handler->invoke(['path' => '/again'], null);
268+
269+ self::assertSame(202, $first['statusCode']);
270+ self::assertSame(['Content-Type' => 'application/json', 'X-Multi' => ['a', 'b']], $first['headers']);
271+ self::assertFalse($first['isBase64Encoded'] ?? null);
272+ self::assertArrayNotHasKey('multiValueHeaders', $first, 'Keys Scaleway does not document must be dropped.');
273+ self::assertSame(['calls' => 1, 'event' => $event, 'context' => ['memoryLimitInMb' => 128]], $this->decode($first));
274+ self::assertSame(['calls' => 2, 'event' => ['path' => '/again'], 'context' => null], $this->decode($second));
275+ self::assertSame(1, RecordingKernel::$builds);
276+ }
277+
278+ public function testRawCallableGetsCommandInvocationsAsPlainEvents(): void
279+ {
280+ $event = $this->commandEvent('app:greet');
281+
282+ $response = $this->handler(['front_controller' => 'front-controllers/raw.php'])->invoke($event, []);
283+
284+ self::assertSame($event, $this->decode($response)['event']);
285+ }
286+
287+ public function testFailedRawCallableBuildIsRetriedOnNextInvocation(): void
288+ {
289+ RecordingKernel::$failingBuilds = 1;
290+ $handler = $this->handler(['front_controller' => 'front-controllers/raw.php', 'debug' => false]);
291+
292+ self::assertSame(500, $handler->invoke([], [])['statusCode']);
293+ self::assertStringContainsString('Build failed on purpose.', $this->errorLog());
294+ self::assertSame(202, $handler->invoke([], [])['statusCode']);
295+ self::assertSame(2, RecordingKernel::$builds);
296+ }
297+
298+ /**
299+ * @return iterable<string, array{string, string}>
300+ */
301+ public static function failingRawCallables(): iterable
302+ {
303+ yield 'exception' => ['/throw', 'LogicException: Escaped on purpose.'];
304+ yield 'non-int status' => ['/invalid', 'must return a Function Response'];
305+ yield 'nested header value' => ['/bad-header', 'must return a Function Response'];
306+ yield 'plain string' => ['/string', '"string" returned'];
307+ }
308+
309+ #[DataProvider('failingRawCallables')]
310+ public function testFailingRawCallableIsA500AndTheProcessKeepsServing(string $path, string $message): void
311+ {
312+ $handler = $this->handler(['front_controller' => 'front-controllers/raw.php', 'debug' => false]);
313+
314+ self::assertSame([
315+ 'statusCode' => 500,
316+ 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'],
317+ 'body' => 'Internal Server Error',
318+ ], $handler->invoke(['path' => $path], []));
319+ self::assertStringContainsString($message, $this->errorLog());
320+ self::assertSame(['calls' => 2], array_intersect_key($this->decode($handler->invoke([], [])), ['calls' => 0]));
321+ }
322+
261 public function testFrontControllerMustReturnACallable(): void323 public function testFrontControllerMustReturnACallable(): void
262 {324 {
263 $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []);325 $this->handler(['front_controller' => 'front-controllers/not-callable.php', 'debug' => false])->invoke([], []);
modified tests/IntegrationTest.php +15 -0
@@ -121,6 +121,21 @@ final class IntegrationTest extends TestCase
121121 self::assertSame($first['pid'], $second['pid']);
122122 }
123123
124+ public function testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void
125+ {
126+ $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];
127+ $http = ['path' => '/state', 'method' => 'GET', 'headers' => ['Host' => 'internal.local'], 'isBase64Encoded' => false];
128+
129+ [$first, $second] = $this->invoke([$http, $cron], ['front_controller' => 'public/raw.php']);
130+
131+ self::assertSame(['Content-Type' => 'application/json'], $first['headers']);
132+ $first = $this->json($first);
133+ $second = $this->json($second);
134+ self::assertSame(['event' => $http, 'calls' => 1], array_diff_key($first, ['pid' => 0]));
135+ self::assertSame(['event' => $cron, 'calls' => 2], array_diff_key($second, ['pid' => 0]), 'A raw callable gets Command Invocations as they are.');
136+ self::assertSame($first['pid'], $second['pid']);
137+ }
138+
124139 public function testRequestHandlerServesInvocationsThroughThePsr7Bridge(): void
125140 {
126141 [$first, $second] = $this->invoke([
@@ -121,6 +121,21 @@ 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 testRawCallableIsBuiltOnceAndGetsEveryEventUntouchedCronIncluded(): void
125+ {
126+ $cron = ['method' => 'POST', 'path' => '/', 'body' => '{"command":"app:count","secret":"cron-secret"}'];
127+ $http = ['path' => '/state', 'method' => 'GET', 'headers' => ['Host' => 'internal.local'], 'isBase64Encoded' => false];
128+
129+ [$first, $second] = $this->invoke([$http, $cron], ['front_controller' => 'public/raw.php']);
130+
131+ self::assertSame(['Content-Type' => 'application/json'], $first['headers']);
132+ $first = $this->json($first);
133+ $second = $this->json($second);
134+ self::assertSame(['event' => $http, 'calls' => 1], array_diff_key($first, ['pid' => 0]));
135+ self::assertSame(['event' => $cron, 'calls' => 2], array_diff_key($second, ['pid' => 0]), 'A raw callable gets Command Invocations as they are.');
136+ self::assertSame($first['pid'], $second['pid']);
137+ }
138+
124 public function testRequestHandlerServesInvocationsThroughThePsr7Bridge(): void139 public function testRequestHandlerServesInvocationsThroughThePsr7Bridge(): void
125 {140 {
126 [$first, $second] = $this->invoke([141 [$first, $second] = $this->invoke([