feat: add the scaleway-serve EmulatorUnverified
PHP's built-in server keeps its process but wipes all PHP state after each request, so it cannot host a Warm Process. It only parses HTTP and turns each request into an Event, which a router script forwards to a long-lived worker that loaded handler.php once and calls handle(), as Scaleway does. A crashed worker is replaced by a fresh one. The README documents the three tools.
c1cabea parent: 0df9229 modified
.php-cs-fixer.dist.php +4 -2 | @@ -3,8 +3,10 @@ | ||
| 3 | 3 | declare(strict_types=1); |
| 4 | 4 | |
| 5 | 5 | $finder = (new PhpCsFixer\Finder()) |
| 6 | - ->in([__DIR__.'/src', __DIR__.'/tests']) | |
| 7 | - ->append([__FILE__, __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package']); | |
| 6 | + ->in([__DIR__.'/src', __DIR__.'/tests', __DIR__.'/resources']) | |
| 7 | + // The stub users commit stays as short as possible. | |
| 8 | + ->notPath('handler.php') | |
| 9 | + ->append([__FILE__, __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package', __DIR__.'/bin/scaleway-serve']); | |
| 8 | 10 | |
| 9 | 11 | return (new PhpCsFixer\Config()) |
| 10 | 12 | ->setRiskyAllowed(true) |
| @@ -3,8 +3,10 @@ | |||
| 3 | declare(strict_types=1); | 3 | declare(strict_types=1); |
| 4 | 4 | ||
| 5 | $finder = (new PhpCsFixer\Finder()) | 5 | $finder = (new PhpCsFixer\Finder()) |
| 6 | - ->in([__DIR__.'/src', __DIR__.'/tests']) | 6 | + ->in([__DIR__.'/src', __DIR__.'/tests', __DIR__.'/resources']) |
| 7 | - ->append([__FILE__, __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package']); | 7 | + // The stub users commit stays as short as possible. |
| 8 | + ->notPath('handler.php') | ||
| 9 | + ->append([__FILE__, __DIR__.'/bin/scaleway-init', __DIR__.'/bin/scaleway-package', __DIR__.'/bin/scaleway-serve']); | ||
| 8 | 10 | ||
| 9 | return (new PhpCsFixer\Config()) | 11 | return (new PhpCsFixer\Config()) |
| 10 | ->setRiskyAllowed(true) | 12 | ->setRiskyAllowed(true) |
modified
README.md +13 -0 | @@ -7,6 +7,19 @@ A [Symfony Runtime](https://symfony.com/doc/current/components/runtime.html) tha | ||
| 7 | 7 | Work in progress: not usable yet. |
| 8 | 8 | See the [implementation plan](docs/plan.md) for the design and the roadmap. |
| 9 | 9 | |
| 10 | +## Tools | |
| 11 | + | |
| 12 | +- `vendor/bin/scaleway-init` writes the `handler.php` stub at the application root; commit it and set the function handler to `handler.handle`. | |
| 13 | + It refuses to replace a different `handler.php` unless run with `--force`. | |
| 14 | +- `vendor/bin/scaleway-package [function.zip]` builds the deployment zip: a copy of the application without local, test and secret files (see `Packager::EXCLUDES`), production dependencies installed from `composer.lock` with an authoritative class map, and the prod cache warmed up by `bin/console cache:warmup`. | |
| 15 | + It needs the `zip` PHP extension and `composer` on the `PATH`, and warns when the zip exceeds Scaleway's limits (100 MiB zipped, 500 MiB unzipped). | |
| 16 | +- `vendor/bin/scaleway-serve [127.0.0.1:8000]` starts the Emulator: each HTTP request becomes an Event passed to the application's `handle()`, and the Function Response becomes the HTTP response. | |
| 17 | + A CRON Invocation is simulated with a `POST /` carrying the trigger's arguments as JSON body. | |
| 18 | + | |
| 19 | +The Emulator runs `handle()` in one long-lived PHP process, as a Warm Process on Scaleway: code changes need a restart, and a crashed process is replaced by a fresh one. | |
| 20 | +PHP's built-in server alone could not do this, since it keeps its process but wipes all PHP state after each request. | |
| 21 | +How Scaleway fills `X-Forwarded-*`, folds repeated query keys and names headers is still assumed. | |
| 22 | + | |
| 10 | 23 | ## License |
| 11 | 24 | |
| 12 | 25 | Released under the [MIT License](LICENSE). |
| @@ -7,6 +7,19 @@ A [Symfony Runtime](https://symfony.com/doc/current/components/runtime.html) tha | |||
| 7 | Work in progress: not usable yet. | 7 | Work in progress: not usable yet. |
| 8 | See the [implementation plan](docs/plan.md) for the design and the roadmap. | 8 | See the [implementation plan](docs/plan.md) for the design and the roadmap. |
| 9 | 9 | ||
| 10 | +## Tools | ||
| 11 | + | ||
| 12 | +- `vendor/bin/scaleway-init` writes the `handler.php` stub at the application root; commit it and set the function handler to `handler.handle`. | ||
| 13 | + It refuses to replace a different `handler.php` unless run with `--force`. | ||
| 14 | +- `vendor/bin/scaleway-package [function.zip]` builds the deployment zip: a copy of the application without local, test and secret files (see `Packager::EXCLUDES`), production dependencies installed from `composer.lock` with an authoritative class map, and the prod cache warmed up by `bin/console cache:warmup`. | ||
| 15 | + It needs the `zip` PHP extension and `composer` on the `PATH`, and warns when the zip exceeds Scaleway's limits (100 MiB zipped, 500 MiB unzipped). | ||
| 16 | +- `vendor/bin/scaleway-serve [127.0.0.1:8000]` starts the Emulator: each HTTP request becomes an Event passed to the application's `handle()`, and the Function Response becomes the HTTP response. | ||
| 17 | + A CRON Invocation is simulated with a `POST /` carrying the trigger's arguments as JSON body. | ||
| 18 | + | ||
| 19 | +The Emulator runs `handle()` in one long-lived PHP process, as a Warm Process on Scaleway: code changes need a restart, and a crashed process is replaced by a fresh one. | ||
| 20 | +PHP's built-in server alone could not do this, since it keeps its process but wipes all PHP state after each request. | ||
| 21 | +How Scaleway fills `X-Forwarded-*`, folds repeated query keys and names headers is still assumed. | ||
| 22 | + | ||
| 10 | ## License | 23 | ## License |
| 11 | 24 | ||
| 12 | Released under the [MIT License](LICENSE). | 25 | Released under the [MIT License](LICENSE). |
added
bin/scaleway-serve +88 -0 | new file mode 100755 | ||
| @@ -0,0 +1,88 @@ | ||
| 1 | +#!/usr/bin/env php | |
| 2 | +<?php | |
| 3 | + | |
| 4 | +declare(strict_types=1); | |
| 5 | + | |
| 6 | +use Composer\InstalledVersions; | |
| 7 | + | |
| 8 | +$autoload = (string) realpath(is_string($_composer_autoload_path ?? null) ? $_composer_autoload_path : __DIR__.'/../vendor/autoload.php'); | |
| 9 | +require $autoload; | |
| 10 | + | |
| 11 | +if (in_array($argv[1] ?? null, ['-h', '--help'], true)) { | |
| 12 | + echo 'Usage: scaleway-serve [<host>:<port>] (default: 127.0.0.1:8000)', \PHP_EOL; | |
| 13 | + exit(0); | |
| 14 | +} | |
| 15 | + | |
| 16 | +$address = $argv[1] ?? '127.0.0.1:8000'; | |
| 17 | +$handlerFile = realpath(InstalledVersions::getRootPackage()['install_path']).'/handler.php'; | |
| 18 | +if (!is_file($handlerFile)) { | |
| 19 | + fwrite(\STDERR, "{$handlerFile} is missing: run vendor/bin/scaleway-init first.".\PHP_EOL); | |
| 20 | + exit(1); | |
| 21 | +} | |
| 22 | + | |
| 23 | +// shortcut: another process may grab the port before the worker binds it; rerun if the worker fails to listen. | |
| 24 | +$probe = stream_socket_server('tcp://127.0.0.1:0') ?: exit(1); | |
| 25 | +$workerPort = (int) substr((string) strrchr((string) stream_socket_get_name($probe, false), ':'), 1); | |
| 26 | +fclose($probe); | |
| 27 | + | |
| 28 | +/** | |
| 29 | + * @param list<string> $command | |
| 30 | + * @param array<string, string>|null $env | |
| 31 | + * | |
| 32 | + * @return resource | |
| 33 | + */ | |
| 34 | +function start(array $command, ?array $env = null) | |
| 35 | +{ | |
| 36 | + $process = proc_open($command, [\STDIN, \STDOUT, \STDERR], $pipes, null, $env); | |
| 37 | + if (false === $process) { | |
| 38 | + fwrite(\STDERR, 'Cannot start '.implode(' ', $command).\PHP_EOL); | |
| 39 | + exit(1); | |
| 40 | + } | |
| 41 | + | |
| 42 | + return $process; | |
| 43 | +} | |
| 44 | + | |
| 45 | +$startWorker = static function () use ($handlerFile, $workerPort) { | |
| 46 | + $worker = start([\PHP_BINARY, __DIR__.'/../resources/emulator/worker.php', $handlerFile, (string) $workerPort]); | |
| 47 | + // Waits until it listens, so the first requests do not find the port closed. | |
| 48 | + for ($i = 0; $i < 100 && proc_get_status($worker)['running']; ++$i) { | |
| 49 | + if (false !== $connection = @stream_socket_client('tcp://127.0.0.1:'.$workerPort)) { | |
| 50 | + fclose($connection); | |
| 51 | + break; | |
| 52 | + } | |
| 53 | + usleep(50_000); | |
| 54 | + } | |
| 55 | + | |
| 56 | + return $worker; | |
| 57 | +}; | |
| 58 | + | |
| 59 | +$worker = $startWorker(); | |
| 60 | +$server = start( | |
| 61 | + [\PHP_BINARY, '-d', 'enable_post_data_reading=0', '-d', 'expose_php=0', '-d', 'default_mimetype=', '-S', $address, __DIR__.'/../resources/emulator/router.php'], | |
| 62 | + ['SCALEWAY_EMULATOR_AUTOLOAD' => $autoload, 'SCALEWAY_EMULATOR_WORKER_PORT' => (string) $workerPort] + getenv(), | |
| 63 | +); | |
| 64 | +// Children outlive a killed parent, so a SIGTERM would leave the port and the worker busy. | |
| 65 | +if (function_exists('pcntl_async_signals')) { | |
| 66 | + pcntl_async_signals(true); | |
| 67 | + foreach ([\SIGINT, \SIGTERM] as $signal) { | |
| 68 | + pcntl_signal($signal, static function () use (&$worker, $server): never { | |
| 69 | + proc_terminate($worker); | |
| 70 | + proc_terminate($server); | |
| 71 | + exit(0); | |
| 72 | + }); | |
| 73 | + } | |
| 74 | +} | |
| 75 | +fwrite(\STDERR, "Emulator listening on http://{$address}, Warm Process pid ".proc_get_status($worker)['pid'].\PHP_EOL); | |
| 76 | + | |
| 77 | +while (($status = proc_get_status($server))['running']) { | |
| 78 | + // A dead Warm Process is replaced, as the platform starts a new instance after a crash. | |
| 79 | + if (!proc_get_status($worker)['running']) { | |
| 80 | + $worker = $startWorker(); | |
| 81 | + fwrite(\STDERR, 'Emulator: the Warm Process exited, started a new one with pid '.proc_get_status($worker)['pid'].\PHP_EOL); | |
| 82 | + // Keeps an application that cannot even load from flooding the console. | |
| 83 | + sleep(1); | |
| 84 | + } | |
| 85 | + usleep(200_000); | |
| 86 | +} | |
| 87 | +proc_terminate($worker); | |
| 88 | +exit($status['exitcode']); | |
| new file mode 100755 | |||
| @@ -0,0 +1,88 @@ | |||
| 1 | +#!/usr/bin/env php | ||
| 2 | +<?php | ||
| 3 | + | ||
| 4 | +declare(strict_types=1); | ||
| 5 | + | ||
| 6 | +use Composer\InstalledVersions; | ||
| 7 | + | ||
| 8 | +$autoload = (string) realpath(is_string($_composer_autoload_path ?? null) ? $_composer_autoload_path : __DIR__.'/../vendor/autoload.php'); | ||
| 9 | +require $autoload; | ||
| 10 | + | ||
| 11 | +if (in_array($argv[1] ?? null, ['-h', '--help'], true)) { | ||
| 12 | + echo 'Usage: scaleway-serve [<host>:<port>] (default: 127.0.0.1:8000)', \PHP_EOL; | ||
| 13 | + exit(0); | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +$address = $argv[1] ?? '127.0.0.1:8000'; | ||
| 17 | +$handlerFile = realpath(InstalledVersions::getRootPackage()['install_path']).'/handler.php'; | ||
| 18 | +if (!is_file($handlerFile)) { | ||
| 19 | + fwrite(\STDERR, "{$handlerFile} is missing: run vendor/bin/scaleway-init first.".\PHP_EOL); | ||
| 20 | + exit(1); | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +// shortcut: another process may grab the port before the worker binds it; rerun if the worker fails to listen. | ||
| 24 | +$probe = stream_socket_server('tcp://127.0.0.1:0') ?: exit(1); | ||
| 25 | +$workerPort = (int) substr((string) strrchr((string) stream_socket_get_name($probe, false), ':'), 1); | ||
| 26 | +fclose($probe); | ||
| 27 | + | ||
| 28 | +/** | ||
| 29 | + * @param list<string> $command | ||
| 30 | + * @param array<string, string>|null $env | ||
| 31 | + * | ||
| 32 | + * @return resource | ||
| 33 | + */ | ||
| 34 | +function start(array $command, ?array $env = null) | ||
| 35 | +{ | ||
| 36 | + $process = proc_open($command, [\STDIN, \STDOUT, \STDERR], $pipes, null, $env); | ||
| 37 | + if (false === $process) { | ||
| 38 | + fwrite(\STDERR, 'Cannot start '.implode(' ', $command).\PHP_EOL); | ||
| 39 | + exit(1); | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + return $process; | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +$startWorker = static function () use ($handlerFile, $workerPort) { | ||
| 46 | + $worker = start([\PHP_BINARY, __DIR__.'/../resources/emulator/worker.php', $handlerFile, (string) $workerPort]); | ||
| 47 | + // Waits until it listens, so the first requests do not find the port closed. | ||
| 48 | + for ($i = 0; $i < 100 && proc_get_status($worker)['running']; ++$i) { | ||
| 49 | + if (false !== $connection = @stream_socket_client('tcp://127.0.0.1:'.$workerPort)) { | ||
| 50 | + fclose($connection); | ||
| 51 | + break; | ||
| 52 | + } | ||
| 53 | + usleep(50_000); | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + return $worker; | ||
| 57 | +}; | ||
| 58 | + | ||
| 59 | +$worker = $startWorker(); | ||
| 60 | +$server = start( | ||
| 61 | + [\PHP_BINARY, '-d', 'enable_post_data_reading=0', '-d', 'expose_php=0', '-d', 'default_mimetype=', '-S', $address, __DIR__.'/../resources/emulator/router.php'], | ||
| 62 | + ['SCALEWAY_EMULATOR_AUTOLOAD' => $autoload, 'SCALEWAY_EMULATOR_WORKER_PORT' => (string) $workerPort] + getenv(), | ||
| 63 | +); | ||
| 64 | +// Children outlive a killed parent, so a SIGTERM would leave the port and the worker busy. | ||
| 65 | +if (function_exists('pcntl_async_signals')) { | ||
| 66 | + pcntl_async_signals(true); | ||
| 67 | + foreach ([\SIGINT, \SIGTERM] as $signal) { | ||
| 68 | + pcntl_signal($signal, static function () use (&$worker, $server): never { | ||
| 69 | + proc_terminate($worker); | ||
| 70 | + proc_terminate($server); | ||
| 71 | + exit(0); | ||
| 72 | + }); | ||
| 73 | + } | ||
| 74 | +} | ||
| 75 | +fwrite(\STDERR, "Emulator listening on http://{$address}, Warm Process pid ".proc_get_status($worker)['pid'].\PHP_EOL); | ||
| 76 | + | ||
| 77 | +while (($status = proc_get_status($server))['running']) { | ||
| 78 | + // A dead Warm Process is replaced, as the platform starts a new instance after a crash. | ||
| 79 | + if (!proc_get_status($worker)['running']) { | ||
| 80 | + $worker = $startWorker(); | ||
| 81 | + fwrite(\STDERR, 'Emulator: the Warm Process exited, started a new one with pid '.proc_get_status($worker)['pid'].\PHP_EOL); | ||
| 82 | + // Keeps an application that cannot even load from flooding the console. | ||
| 83 | + sleep(1); | ||
| 84 | + } | ||
| 85 | + usleep(200_000); | ||
| 86 | +} | ||
| 87 | +proc_terminate($worker); | ||
| 88 | +exit($status['exitcode']); | ||
modified
composer.json +2 -1 | @@ -33,7 +33,8 @@ | ||
| 33 | 33 | }, |
| 34 | 34 | "bin": [ |
| 35 | 35 | "bin/scaleway-init", |
| 36 | - "bin/scaleway-package" | |
| 36 | + "bin/scaleway-package", | |
| 37 | + "bin/scaleway-serve" | |
| 37 | 38 | ], |
| 38 | 39 | "autoload-dev": { |
| 39 | 40 | "psr-4": { |
| @@ -33,7 +33,8 @@ | |||
| 33 | }, | 33 | }, |
| 34 | "bin": [ | 34 | "bin": [ |
| 35 | "bin/scaleway-init", | 35 | "bin/scaleway-init", |
| 36 | - "bin/scaleway-package" | 36 | + "bin/scaleway-package", |
| 37 | + "bin/scaleway-serve" | ||
| 37 | ], | 38 | ], |
| 38 | "autoload-dev": { | 39 | "autoload-dev": { |
| 39 | "psr-4": { | 40 | "psr-4": { |
modified
phpstan.neon.dist +7 -0 | @@ -7,5 +7,12 @@ parameters: | ||
| 7 | 7 | paths: |
| 8 | 8 | - src |
| 9 | 9 | - tests |
| 10 | + - resources | |
| 10 | 11 | - bin/scaleway-init |
| 11 | 12 | - bin/scaleway-package |
| 13 | + - bin/scaleway-serve | |
| 14 | + excludePaths: | |
| 15 | + # The stub users commit stays as short as possible, without annotations. | |
| 16 | + - resources/handler.php | |
| 17 | + scanFiles: | |
| 18 | + - resources/handler.php | |
| @@ -7,5 +7,12 @@ parameters: | |||
| 7 | paths: | 7 | paths: |
| 8 | - src | 8 | - src |
| 9 | - tests | 9 | - tests |
| 10 | + - resources | ||
| 10 | - bin/scaleway-init | 11 | - bin/scaleway-init |
| 11 | - bin/scaleway-package | 12 | - bin/scaleway-package |
| 13 | + - bin/scaleway-serve | ||
| 14 | + excludePaths: | ||
| 15 | + # The stub users commit stays as short as possible, without annotations. | ||
| 16 | + - resources/handler.php | ||
| 17 | + scanFiles: | ||
| 18 | + - resources/handler.php | ||
added
resources/emulator/router.php +56 -0 | new file mode 100644 | ||
| @@ -0,0 +1,56 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +/* | |
| 6 | + * The php -S router of the Emulator: the built-in server parses HTTP but wipes all PHP state after each | |
| 7 | + * request, so the Handler runs in a separate long-lived worker, and this router forwards Events to it. | |
| 8 | + */ | |
| 9 | + | |
| 10 | +use JDecool\ScalewayRuntime\Emulator; | |
| 11 | + | |
| 12 | +require (string) getenv('SCALEWAY_EMULATOR_AUTOLOAD'); | |
| 13 | + | |
| 14 | +$server = static fn (string $key): string => is_string($_SERVER[$key] ?? null) ? $_SERVER[$key] : ''; | |
| 15 | +$headers = []; | |
| 16 | +foreach (getallheaders() as $name => $value) { | |
| 17 | + if (is_string($value)) { | |
| 18 | + $headers[(string) $name] = $value; | |
| 19 | + } | |
| 20 | +} | |
| 21 | +$event = Emulator::toEvent( | |
| 22 | + $server('REQUEST_METHOD'), | |
| 23 | + $server('REQUEST_URI'), | |
| 24 | + $headers, | |
| 25 | + // Raw even for form posts, as the server runs with enable_post_data_reading=0. | |
| 26 | + (string) file_get_contents('php://input'), | |
| 27 | + $server('REMOTE_ADDR'), | |
| 28 | +); | |
| 29 | + | |
| 30 | +$response = null; | |
| 31 | +$connection = @stream_socket_client('tcp://127.0.0.1:'.getenv('SCALEWAY_EMULATOR_WORKER_PORT'), $errorCode, $errorMessage); | |
| 32 | +if (false !== $connection) { | |
| 33 | + // Scaleway allows Invocations of up to 60 minutes. | |
| 34 | + stream_set_timeout($connection, 3600); | |
| 35 | + fwrite($connection, json_encode($event, \JSON_THROW_ON_ERROR)); | |
| 36 | + stream_socket_shutdown($connection, \STREAM_SHUT_WR); | |
| 37 | + $response = json_decode((string) stream_get_contents($connection), true); | |
| 38 | + fclose($connection); | |
| 39 | +} | |
| 40 | + | |
| 41 | +if (!is_array($response)) { | |
| 42 | + http_response_code(502); | |
| 43 | + header('Content-Type: text/plain; charset=UTF-8'); | |
| 44 | + echo 'Emulator: the Warm Process returned no Function Response, see its output. ', $errorMessage, \PHP_EOL; | |
| 45 | + | |
| 46 | + return; | |
| 47 | +} | |
| 48 | + | |
| 49 | +http_response_code(is_int($response['statusCode'] ?? null) ? $response['statusCode'] : 200); | |
| 50 | +foreach (is_array($response['headers'] ?? null) ? $response['headers'] : [] as $name => $values) { | |
| 51 | + foreach (array_filter((array) $values, is_scalar(...)) as $value) { | |
| 52 | + header($name.': '.$value, false); | |
| 53 | + } | |
| 54 | +} | |
| 55 | +$body = is_string($response['body'] ?? null) ? $response['body'] : ''; | |
| 56 | +echo true === ($response['isBase64Encoded'] ?? false) ? base64_decode($body) : $body; | |
| new file mode 100644 | |||
| @@ -0,0 +1,56 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +/* | ||
| 6 | + * The php -S router of the Emulator: the built-in server parses HTTP but wipes all PHP state after each | ||
| 7 | + * request, so the Handler runs in a separate long-lived worker, and this router forwards Events to it. | ||
| 8 | + */ | ||
| 9 | + | ||
| 10 | +use JDecool\ScalewayRuntime\Emulator; | ||
| 11 | + | ||
| 12 | +require (string) getenv('SCALEWAY_EMULATOR_AUTOLOAD'); | ||
| 13 | + | ||
| 14 | +$server = static fn (string $key): string => is_string($_SERVER[$key] ?? null) ? $_SERVER[$key] : ''; | ||
| 15 | +$headers = []; | ||
| 16 | +foreach (getallheaders() as $name => $value) { | ||
| 17 | + if (is_string($value)) { | ||
| 18 | + $headers[(string) $name] = $value; | ||
| 19 | + } | ||
| 20 | +} | ||
| 21 | +$event = Emulator::toEvent( | ||
| 22 | + $server('REQUEST_METHOD'), | ||
| 23 | + $server('REQUEST_URI'), | ||
| 24 | + $headers, | ||
| 25 | + // Raw even for form posts, as the server runs with enable_post_data_reading=0. | ||
| 26 | + (string) file_get_contents('php://input'), | ||
| 27 | + $server('REMOTE_ADDR'), | ||
| 28 | +); | ||
| 29 | + | ||
| 30 | +$response = null; | ||
| 31 | +$connection = @stream_socket_client('tcp://127.0.0.1:'.getenv('SCALEWAY_EMULATOR_WORKER_PORT'), $errorCode, $errorMessage); | ||
| 32 | +if (false !== $connection) { | ||
| 33 | + // Scaleway allows Invocations of up to 60 minutes. | ||
| 34 | + stream_set_timeout($connection, 3600); | ||
| 35 | + fwrite($connection, json_encode($event, \JSON_THROW_ON_ERROR)); | ||
| 36 | + stream_socket_shutdown($connection, \STREAM_SHUT_WR); | ||
| 37 | + $response = json_decode((string) stream_get_contents($connection), true); | ||
| 38 | + fclose($connection); | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +if (!is_array($response)) { | ||
| 42 | + http_response_code(502); | ||
| 43 | + header('Content-Type: text/plain; charset=UTF-8'); | ||
| 44 | + echo 'Emulator: the Warm Process returned no Function Response, see its output. ', $errorMessage, \PHP_EOL; | ||
| 45 | + | ||
| 46 | + return; | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +http_response_code(is_int($response['statusCode'] ?? null) ? $response['statusCode'] : 200); | ||
| 50 | +foreach (is_array($response['headers'] ?? null) ? $response['headers'] : [] as $name => $values) { | ||
| 51 | + foreach (array_filter((array) $values, is_scalar(...)) as $value) { | ||
| 52 | + header($name.': '.$value, false); | ||
| 53 | + } | ||
| 54 | +} | ||
| 55 | +$body = is_string($response['body'] ?? null) ? $response['body'] : ''; | ||
| 56 | +echo true === ($response['isBase64Encoded'] ?? false) ? base64_decode($body) : $body; | ||
added
resources/emulator/worker.php +41 -0 | new file mode 100644 | ||
| @@ -0,0 +1,41 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +/* | |
| 6 | + * The Warm Process of the Emulator: loads the application's handler.php once, then calls handle() | |
| 7 | + * for each Event the router forwards, as Scaleway does. Usage: worker.php <handler.php> <port>. | |
| 8 | + */ | |
| 9 | + | |
| 10 | +[, $handlerFile, $port] = ($argv ?? []) + [1 => '', 2 => '']; | |
| 11 | + | |
| 12 | +require $handlerFile; | |
| 13 | + | |
| 14 | +$server = stream_socket_server('tcp://127.0.0.1:'.$port, $errorCode, $errorMessage); | |
| 15 | +if (false === $server) { | |
| 16 | + fwrite(\STDERR, "Cannot listen on port {$port}: {$errorMessage}".\PHP_EOL); | |
| 17 | + exit(1); | |
| 18 | +} | |
| 19 | + | |
| 20 | +// Accepting only fails when interrupted; the worker then exits and the Emulator starts a new one. | |
| 21 | +while (false !== $connection = @stream_socket_accept($server, -1)) { | |
| 22 | + try { | |
| 23 | + $payload = (string) stream_get_contents($connection); | |
| 24 | + // The Emulator connects without a payload to check this worker is up. | |
| 25 | + if ('' === $payload) { | |
| 26 | + continue; | |
| 27 | + } | |
| 28 | + $event = json_decode($payload, true, 512, \JSON_THROW_ON_ERROR); | |
| 29 | + if (!is_array($event)) { | |
| 30 | + throw new UnexpectedValueException('The Event must be a JSON object.'); | |
| 31 | + } | |
| 32 | + // Scaleway's context shape is not documented; the probe function records it. | |
| 33 | + $response = handle($event, []); | |
| 34 | + fwrite($connection, json_encode($response, \JSON_THROW_ON_ERROR)); | |
| 35 | + } catch (Throwable $e) { | |
| 36 | + // Scaleway would fail the Invocation too, e.g. for a Function Response that is not JSON-encodable. | |
| 37 | + fwrite(\STDERR, 'Emulator: invalid Invocation: '.$e.\PHP_EOL); | |
| 38 | + } finally { | |
| 39 | + fclose($connection); | |
| 40 | + } | |
| 41 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,41 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +/* | ||
| 6 | + * The Warm Process of the Emulator: loads the application's handler.php once, then calls handle() | ||
| 7 | + * for each Event the router forwards, as Scaleway does. Usage: worker.php <handler.php> <port>. | ||
| 8 | + */ | ||
| 9 | + | ||
| 10 | +[, $handlerFile, $port] = ($argv ?? []) + [1 => '', 2 => '']; | ||
| 11 | + | ||
| 12 | +require $handlerFile; | ||
| 13 | + | ||
| 14 | +$server = stream_socket_server('tcp://127.0.0.1:'.$port, $errorCode, $errorMessage); | ||
| 15 | +if (false === $server) { | ||
| 16 | + fwrite(\STDERR, "Cannot listen on port {$port}: {$errorMessage}".\PHP_EOL); | ||
| 17 | + exit(1); | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +// Accepting only fails when interrupted; the worker then exits and the Emulator starts a new one. | ||
| 21 | +while (false !== $connection = @stream_socket_accept($server, -1)) { | ||
| 22 | + try { | ||
| 23 | + $payload = (string) stream_get_contents($connection); | ||
| 24 | + // The Emulator connects without a payload to check this worker is up. | ||
| 25 | + if ('' === $payload) { | ||
| 26 | + continue; | ||
| 27 | + } | ||
| 28 | + $event = json_decode($payload, true, 512, \JSON_THROW_ON_ERROR); | ||
| 29 | + if (!is_array($event)) { | ||
| 30 | + throw new UnexpectedValueException('The Event must be a JSON object.'); | ||
| 31 | + } | ||
| 32 | + // Scaleway's context shape is not documented; the probe function records it. | ||
| 33 | + $response = handle($event, []); | ||
| 34 | + fwrite($connection, json_encode($response, \JSON_THROW_ON_ERROR)); | ||
| 35 | + } catch (Throwable $e) { | ||
| 36 | + // Scaleway would fail the Invocation too, e.g. for a Function Response that is not JSON-encodable. | ||
| 37 | + fwrite(\STDERR, 'Emulator: invalid Invocation: '.$e.\PHP_EOL); | ||
| 38 | + } finally { | ||
| 39 | + fclose($connection); | ||
| 40 | + } | ||
| 41 | +} | ||
added
src/Emulator.php +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace JDecool\ScalewayRuntime; | |
| 6 | + | |
| 7 | +/** | |
| 8 | + * Turns a real HTTP request into the Event Scaleway would pass to the Handler. | |
| 9 | + * | |
| 10 | + * Shape from https://www.scaleway.com/en/docs/serverless-functions/reference-content/code-examples/; | |
| 11 | + * how the platform canonicalizes headers, folds repeated query keys and fills X-Forwarded-* is | |
| 12 | + * an assumption until the probe function settles it. | |
| 13 | + */ | |
| 14 | +final class Emulator | |
| 15 | +{ | |
| 16 | + /** | |
| 17 | + * @param array<string, string> $headers | |
| 18 | + * | |
| 19 | + * @return array{path: string, queryStringParameters: array<string, string>, body: string, headers: array<string, string>, method: string, isBase64Encoded: bool} | |
| 20 | + */ | |
| 21 | + public static function toEvent(string $method, string $uri, array $headers, string $body, string $clientAddress): array | |
| 22 | + { | |
| 23 | + [$path, $queryString] = explode('?', $uri, 2) + [1 => '']; | |
| 24 | + | |
| 25 | + // A map of strings, like the platform's: the last value of a repeated key wins and "a[]" stays a plain key. | |
| 26 | + $query = []; | |
| 27 | + foreach (explode('&', $queryString) as $pair) { | |
| 28 | + [$name, $value] = explode('=', $pair, 2) + [1 => '']; | |
| 29 | + if ('' !== $name) { | |
| 30 | + $query[urldecode($name)] = urldecode($value); | |
| 31 | + } | |
| 32 | + } | |
| 33 | + | |
| 34 | + $canonical = []; | |
| 35 | + foreach ($headers as $name => $value) { | |
| 36 | + $name = ucwords(strtolower($name), '-'); | |
| 37 | + $canonical[$name] = isset($canonical[$name]) ? $canonical[$name].', '.$value : $value; | |
| 38 | + } | |
| 39 | + // As a reverse proxy does: the peer is appended to the client's chain. | |
| 40 | + $canonical['X-Forwarded-For'] = isset($canonical['X-Forwarded-For']) ? $canonical['X-Forwarded-For'].', '.$clientAddress : $clientAddress; | |
| 41 | + $canonical['X-Forwarded-Proto'] = 'http'; | |
| 42 | + | |
| 43 | + // JSON carries the Event, so a body that is not UTF-8 text travels base64-encoded. | |
| 44 | + $binary = 1 !== preg_match('//u', $body); | |
| 45 | + | |
| 46 | + return [ | |
| 47 | + 'path' => $path, | |
| 48 | + 'queryStringParameters' => $query, | |
| 49 | + 'body' => $binary ? base64_encode($body) : $body, | |
| 50 | + 'headers' => $canonical, | |
| 51 | + 'method' => strtoupper($method), | |
| 52 | + 'isBase64Encoded' => $binary, | |
| 53 | + ]; | |
| 54 | + } | |
| 55 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +namespace JDecool\ScalewayRuntime; | ||
| 6 | + | ||
| 7 | +/** | ||
| 8 | + * Turns a real HTTP request into the Event Scaleway would pass to the Handler. | ||
| 9 | + * | ||
| 10 | + * Shape from https://www.scaleway.com/en/docs/serverless-functions/reference-content/code-examples/; | ||
| 11 | + * how the platform canonicalizes headers, folds repeated query keys and fills X-Forwarded-* is | ||
| 12 | + * an assumption until the probe function settles it. | ||
| 13 | + */ | ||
| 14 | +final class Emulator | ||
| 15 | +{ | ||
| 16 | + /** | ||
| 17 | + * @param array<string, string> $headers | ||
| 18 | + * | ||
| 19 | + * @return array{path: string, queryStringParameters: array<string, string>, body: string, headers: array<string, string>, method: string, isBase64Encoded: bool} | ||
| 20 | + */ | ||
| 21 | + public static function toEvent(string $method, string $uri, array $headers, string $body, string $clientAddress): array | ||
| 22 | + { | ||
| 23 | + [$path, $queryString] = explode('?', $uri, 2) + [1 => '']; | ||
| 24 | + | ||
| 25 | + // A map of strings, like the platform's: the last value of a repeated key wins and "a[]" stays a plain key. | ||
| 26 | + $query = []; | ||
| 27 | + foreach (explode('&', $queryString) as $pair) { | ||
| 28 | + [$name, $value] = explode('=', $pair, 2) + [1 => '']; | ||
| 29 | + if ('' !== $name) { | ||
| 30 | + $query[urldecode($name)] = urldecode($value); | ||
| 31 | + } | ||
| 32 | + } | ||
| 33 | + | ||
| 34 | + $canonical = []; | ||
| 35 | + foreach ($headers as $name => $value) { | ||
| 36 | + $name = ucwords(strtolower($name), '-'); | ||
| 37 | + $canonical[$name] = isset($canonical[$name]) ? $canonical[$name].', '.$value : $value; | ||
| 38 | + } | ||
| 39 | + // As a reverse proxy does: the peer is appended to the client's chain. | ||
| 40 | + $canonical['X-Forwarded-For'] = isset($canonical['X-Forwarded-For']) ? $canonical['X-Forwarded-For'].', '.$clientAddress : $clientAddress; | ||
| 41 | + $canonical['X-Forwarded-Proto'] = 'http'; | ||
| 42 | + | ||
| 43 | + // JSON carries the Event, so a body that is not UTF-8 text travels base64-encoded. | ||
| 44 | + $binary = 1 !== preg_match('//u', $body); | ||
| 45 | + | ||
| 46 | + return [ | ||
| 47 | + 'path' => $path, | ||
| 48 | + 'queryStringParameters' => $query, | ||
| 49 | + 'body' => $binary ? base64_encode($body) : $body, | ||
| 50 | + 'headers' => $canonical, | ||
| 51 | + 'method' => strtoupper($method), | ||
| 52 | + 'isBase64Encoded' => $binary, | ||
| 53 | + ]; | ||
| 54 | + } | ||
| 55 | +} | ||
added
tests/EmulatorTest.php +55 -0 | new file mode 100644 | ||
| @@ -0,0 +1,55 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace JDecool\ScalewayRuntime\Tests; | |
| 6 | + | |
| 7 | +use JDecool\ScalewayRuntime\Emulator; | |
| 8 | +use JDecool\ScalewayRuntime\HttpConverter; | |
| 9 | +use PHPUnit\Framework\TestCase; | |
| 10 | + | |
| 11 | +final class EmulatorTest extends TestCase | |
| 12 | +{ | |
| 13 | + public function testTextRequestBecomesAPlainEvent(): void | |
| 14 | + { | |
| 15 | + $event = Emulator::toEvent('post', '/users/42?sort=name&filter%5Brole%5D=admin+user&flag', [ | |
| 16 | + 'content-type' => 'application/json', | |
| 17 | + 'X-Forwarded-For' => '203.0.113.7', | |
| 18 | + ], '{"name":"Zoé"}', '127.0.0.1'); | |
| 19 | + | |
| 20 | + self::assertSame([ | |
| 21 | + 'path' => '/users/42', | |
| 22 | + 'queryStringParameters' => ['sort' => 'name', 'filter[role]' => 'admin user', 'flag' => ''], | |
| 23 | + 'body' => '{"name":"Zoé"}', | |
| 24 | + 'headers' => [ | |
| 25 | + 'Content-Type' => 'application/json', | |
| 26 | + 'X-Forwarded-For' => '203.0.113.7, 127.0.0.1', | |
| 27 | + 'X-Forwarded-Proto' => 'http', | |
| 28 | + ], | |
| 29 | + 'method' => 'POST', | |
| 30 | + 'isBase64Encoded' => false, | |
| 31 | + ], $event); | |
| 32 | + } | |
| 33 | + | |
| 34 | + public function testBinaryBodyIsBase64Encoded(): void | |
| 35 | + { | |
| 36 | + $event = Emulator::toEvent('PUT', '/', [], "\xFF\x00\xFE", '127.0.0.1'); | |
| 37 | + | |
| 38 | + self::assertTrue($event['isBase64Encoded']); | |
| 39 | + self::assertSame("\xFF\x00\xFE", base64_decode($event['body'], true)); | |
| 40 | + } | |
| 41 | + | |
| 42 | + public function testRepeatedQueryKeyKeepsTheLastValue(): void | |
| 43 | + { | |
| 44 | + self::assertSame(['a' => '2'], Emulator::toEvent('GET', '/?a=1&a=2', [], '', '::1')['queryStringParameters']); | |
| 45 | + } | |
| 46 | + | |
| 47 | + public function testEventRoundTripsThroughTheConverter(): void | |
| 48 | + { | |
| 49 | + $request = HttpConverter::toRequest(Emulator::toEvent('GET', '/search?q=caf%C3%A9&page%5Bsize%5D=10', ['Host' => 'example.test'], '', '192.0.2.1')); | |
| 50 | + | |
| 51 | + self::assertSame('/search', $request->getPathInfo()); | |
| 52 | + self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all()); | |
| 53 | + self::assertSame('example.test', $request->getHost()); | |
| 54 | + } | |
| 55 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,55 @@ | |||
| 1 | +<?php | ||
| 2 | + | ||
| 3 | +declare(strict_types=1); | ||
| 4 | + | ||
| 5 | +namespace JDecool\ScalewayRuntime\Tests; | ||
| 6 | + | ||
| 7 | +use JDecool\ScalewayRuntime\Emulator; | ||
| 8 | +use JDecool\ScalewayRuntime\HttpConverter; | ||
| 9 | +use PHPUnit\Framework\TestCase; | ||
| 10 | + | ||
| 11 | +final class EmulatorTest extends TestCase | ||
| 12 | +{ | ||
| 13 | + public function testTextRequestBecomesAPlainEvent(): void | ||
| 14 | + { | ||
| 15 | + $event = Emulator::toEvent('post', '/users/42?sort=name&filter%5Brole%5D=admin+user&flag', [ | ||
| 16 | + 'content-type' => 'application/json', | ||
| 17 | + 'X-Forwarded-For' => '203.0.113.7', | ||
| 18 | + ], '{"name":"Zoé"}', '127.0.0.1'); | ||
| 19 | + | ||
| 20 | + self::assertSame([ | ||
| 21 | + 'path' => '/users/42', | ||
| 22 | + 'queryStringParameters' => ['sort' => 'name', 'filter[role]' => 'admin user', 'flag' => ''], | ||
| 23 | + 'body' => '{"name":"Zoé"}', | ||
| 24 | + 'headers' => [ | ||
| 25 | + 'Content-Type' => 'application/json', | ||
| 26 | + 'X-Forwarded-For' => '203.0.113.7, 127.0.0.1', | ||
| 27 | + 'X-Forwarded-Proto' => 'http', | ||
| 28 | + ], | ||
| 29 | + 'method' => 'POST', | ||
| 30 | + 'isBase64Encoded' => false, | ||
| 31 | + ], $event); | ||
| 32 | + } | ||
| 33 | + | ||
| 34 | + public function testBinaryBodyIsBase64Encoded(): void | ||
| 35 | + { | ||
| 36 | + $event = Emulator::toEvent('PUT', '/', [], "\xFF\x00\xFE", '127.0.0.1'); | ||
| 37 | + | ||
| 38 | + self::assertTrue($event['isBase64Encoded']); | ||
| 39 | + self::assertSame("\xFF\x00\xFE", base64_decode($event['body'], true)); | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + public function testRepeatedQueryKeyKeepsTheLastValue(): void | ||
| 43 | + { | ||
| 44 | + self::assertSame(['a' => '2'], Emulator::toEvent('GET', '/?a=1&a=2', [], '', '::1')['queryStringParameters']); | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + public function testEventRoundTripsThroughTheConverter(): void | ||
| 48 | + { | ||
| 49 | + $request = HttpConverter::toRequest(Emulator::toEvent('GET', '/search?q=caf%C3%A9&page%5Bsize%5D=10', ['Host' => 'example.test'], '', '192.0.2.1')); | ||
| 50 | + | ||
| 51 | + self::assertSame('/search', $request->getPathInfo()); | ||
| 52 | + self::assertSame(['q' => 'café', 'page' => ['size' => '10']], $request->query->all()); | ||
| 53 | + self::assertSame('example.test', $request->getHost()); | ||
| 54 | + } | ||
| 55 | +} | ||