Scaleway Runtime
A Symfony Runtime that runs Symfony and PHP applications on Scaleway Serverless Functions.
Scaleway calls a PHP function handle($event, $context) for each Invocation.
This package provides that function, boots your unchanged public/index.php once per Warm Process, turns each Event into a Symfony Request and each Response back into a Function Response.
It also ships the tools to package the function and to run it locally.
Vocabulary (Invocation, Event, Warm Process...) is defined in GLOSSARY.md, design decisions in docs/adr.
[!IMPORTANT]
The platform facts the runtime relies on were measured on Scaleway with the probe, see docs/probe-results.md.
The runtime itself has only run through the Emulator so far, and the package is not on Packagist yet.
Contents
- Requirements
- Installation
- Configuration
- Supported Applications
- CRON triggers and Command Invocations
- Packaging
- Deployment
- Local development with the Emulator
- Warm Processes
- Limitations and platform caveats
- Contributing
Requirements
- The Scaleway PHP runtimes
php84orphp85(PHP 8.4 or later). - Symfony 7.4 or 8.x components (
symfony/runtime,symfony/http-kernel,symfony/http-foundation). - To build the deployment zip: the
zipPHP extension. - macOS or Linux for the packaging and Emulator tools (see Windows).
Installation
composer require jdecool/scaleway-runtime
vendor/bin/scaleway-init
scaleway-init writes handler.php at the root of your application:
<?php
require __DIR__.'/vendor/autoload.php';
function handle(array $event, mixed $context): array
{
return JDecool\ScalewayRuntime\Handler::handle($event, $context);
}
Commit it.
scaleway-init refuses to replace a handler.php that differs from this stub, unless run with --force.
Your Front Controller stays as it is, require_once dirname(__DIR__).'/vendor/autoload_runtime.php' included.
That file is generated by the symfony/runtime Composer plugin, so the plugin must be allowed (config.allow-plugins.symfony/runtime), as Symfony Flex applications already do.
The Handler has already loaded vendor/autoload.php when the Front Controller runs, so autoload_runtime.php returns early and the runtime of this package takes over.
Configuration
Function handler
Set the handler of the Scaleway function to handler.handle.
Front Controller
The Front Controller defaults to public/index.php, relative to the project dir.
Choose another one with the front_controller runtime option, in composer.json:
{
"extra": {
"runtime": {
"front_controller": "public/api.php"
}
}
}
Or with the APP_RUNTIME_OPTIONS environment variable, a JSON object that wins over extra.runtime:
APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}'
The other SymfonyRuntime options (project_dir, env_var_name, dotenv_path...) work as usual.
extra.runtime.class and APP_RUNTIME are ignored: they name the runtime the same application uses elsewhere (FPM, FrankenPHP), and the Handler always uses JDecool\ScalewayRuntime\ScalewayRuntime.
Environment variables
Set these on the function, in production:
| Variable | Kind | Why |
|---|---|---|
APP_SECRET |
Secret | Symfony's kernel.secret, used to sign URLs, cookies and CSRF tokens. |
SCALEWAY_HOST |
Plain | The public host of the function, for absolute URLs, see Host. |
SCALEWAY_CRON_SECRET |
Secret | Only to run console commands from CRON triggers, see Command Invocations. |
APP_ENV |
Plain | Only to run another env than prod, see below. |
The .env file is shipped in the zip, and the one Symfony generates says APP_ENV=dev, whose error pages show stack traces to anyone.
So the runtime runs prod when the function's environment sets no APP_ENV (or an empty one), whatever the .env files say (ADR 0006).
Only an APP_ENV variable of the function, or the env runtime option, picks another env.
APP_DEBUG follows: off in prod, unless set by the function's environment or a .env file.
The Emulator runs dev instead, unless it is started with an APP_ENV.
For every other variable, real environment variables win over .env files, as usual with Symfony's Dotenv.
.env.local, .env.local.php and .env.*.local are never shipped.
Host
No Host header reaches the function, so the runtime cannot know the domain it is called on.
Every Request gets the host of the host runtime option, which defaults to the SCALEWAY_HOST environment variable, then to localhost:
SCALEWAY_HOST=api.example.com
The scheme comes from the platform's X-Forwarded-Proto (https for HTTP calls), the port is the scheme's default.
Absolute URLs (UrlGeneratorInterface::ABSOLUTE_URL, signed URLs, redirects built from the Request) are only right once the host is set.
Set it to the function's domain (its domain_name on Scaleway) or to its custom domain.
With Terraform, a function cannot reference its own domain_name in its variables (the reference would be a cycle): use a custom domain, or set the variable after a first apply.
An application configuring framework.trusted_hosts answers every Request with a 400 until the host is set to one of its trusted hosts.
Cache and writable directories
The code directory is writable on Scaleway, so the Kernel builds its cache in var/cache at the first Invocation of each Warm Process, which pays the container compilation once.
To pay it at deploy time instead, warm the cache from a Composer script, which Scaleway runs after installing the dependencies:
{
"scripts": {
"post-install-cmd": ["@php bin/console cache:warmup --env=prod"]
}
}
Only do it when the warmup needs no secret: the function's environment variables are not available at deploy time, and a failing script does not fail the deployment, the first Invocation then building the cache as usual.
[!WARNING]
Symfony Flex'sauto-scriptsalso run at deploy time, with theAPP_ENVof the shipped.env, usuallydev:cache:clearthen fails silently, its dev bundles not being installed with--no-dev.
Make them env-explicit ("cache:clear --env=prod": "symfony-cmd"), or removecache:clearfrom them and warm the cache as above.
When the project's var/ directory (or the project dir, without var/) is not writable, the runtime sets, unless your application already did:
APP_CACHE_DIRto<temp dir>/cacheandAPP_LOG_DIRto<temp dir>/log;APP_BUILD_DIRtovar/cache, only whenvar/cache/<env>holds a container warmed before, so that it is used as is.
Kernels using MicroKernelTrait read these variables.
Other Kernels must override getCacheDir(), getBuildDir() and getLogDir() themselves.
Logs written to files are lost with the instance: send them to php://stderr instead, which the runtime also uses for its own errors.
Errors
An exception escaping the Application (a Kernel failing to boot, an unsupported Front Controller...) is logged to stderr and answered with a 500.
Its body is Internal Server Error, or the full exception when APP_DEBUG is true.
A Kernel that failed to boot is built again from scratch on the next Invocation.
Errors the Kernel handles itself get Symfony's web error pages, as the runtime sets APP_RUNTIME_MODE=web=1&worker=1 unless your environment sets it.
Outside a web SAPI, FrameworkBundle would pick its CLI error renderer instead, which dumps the exception even in prod.
Supported Applications
The Front Controller returns a closure, as with any Symfony Runtime.
The type of what that closure returns, the Application, decides how Invocations are served.
HttpKernel
The usual Symfony Front Controller:
<?php // public/index.php
use App\Kernel;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return function (array $context) {
return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};
The Kernel is booted once per Warm Process and serves every Invocation, see Warm Processes.
Any HttpKernelInterface works; a KernelInterface also runs Command Invocations.
Response
A closure returning a Response is called again for every Invocation, without any Kernel.
A Request argument receives the Invocation's Request:
<?php // public/hello.php
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return static function (Request $request): JsonResponse {
return new JsonResponse(['message' => sprintf('Hello %s!', $request->query->get('name', 'World'))]);
};
Keep the closure cheap, as it runs on every Invocation, and make it return a Response every time.
See ADR 0004.
PSR-15 request handler
A closure returning a Psr\Http\Server\RequestHandlerInterface builds it once per Warm Process.
It needs two more packages:
composer require symfony/psr-http-message-bridge nyholm/psr7
<?php // public/index.php
use App\ApiHandler;
use Psr\Http\Server\RequestHandlerInterface;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return static fn (): RequestHandlerInterface => new ApiHandler();
The PSR-7 request carries the client address, scheme, host and port the runtime resolved (see Client IP and trusted proxies), in its URI and in the REMOTE_ADDR, HTTPS, HTTP_HOST and SERVER_PORT server params.
A handler implementing Symfony\Contracts\Service\ResetInterface is reset before every Invocation but the first.
A malformed host is answered with a 400 before reaching the handler.
Console Application or Command
A Front Controller returning a Console Application or a Command only serves Command Invocations, and answers every other Invocation with a 403.
Symfony's bin/console is such a Front Controller:
APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}'
A single Command runs whatever command the Command Invocation names:
<?php // bin/cleanup.php
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';
return static fn (): Command => (new Command('app:cleanup'))
->setCode(static function (InputInterface $input, OutputInterface $output): int {
$output->writeln('Cleaned up');
return Command::SUCCESS;
});
This needs symfony/console, and symfony/framework-bundle for a Symfony\Bundle\FrameworkBundle\Console\Application.
Raw callable
A closure returning another Closure talks to Scaleway without any translation.
The inner closure is built once per Warm Process and receives every Event and context as they are, CRON Invocations included:
<?php // public/raw.php
return static fn (): Closure => static fn (array $event, mixed $context): array => [
'statusCode' => 200,
'headers' => ['Content-Type' => 'text/plain'],
'body' => 'Hello from '.($event['path'] ?? '/'),
];
It must return a Function Response: an int statusCode, optional headers mapping names to a string or a list of strings, a string body and an optional bool isBase64Encoded.
Other keys are dropped, and any other return value fails the Invocation with a 500.
Command Invocations are not routed: the raw callable gets their Event like any other.
An invokable object is not taken for a raw callable; return $object(...) to make it one.
CRON triggers and Command Invocations
CRON triggers
A CRON trigger calls the Application with a POST / whose JSON body holds the trigger's arguments, over plain http and without client address (getClientIp() is 127.0.0.1).
With a Kernel, handle it like any route:
#[Route('/', methods: ['POST'])]
public function cron(Request $request): Response
{
$args = $request->toArray(); // the trigger's arguments
// ...
}
Any HTTP client can call POST / too: tell CRON Invocations apart with a secret of your own in the arguments, or run a command instead.
Command Invocations
A CRON trigger may run a console command instead, through the Console Application of the same Kernel.
- Generate a random secret, for instance with
openssl rand -hex 32. - Set it as the
SCALEWAY_CRON_SECRETsecret environment variable of the function. - Give the CRON trigger these arguments:
{"command": "app:sync", "args": {"source": "s3", "--force": true, "--tag": ["a", "b"]}, "secret": "<SCALEWAY_CRON_SECRET>"}
args is optional, and maps argument names, and option names with their dashes, to values, as Symfony's ArrayInput does.
The command runs without interaction: questions get their default answer.
Services are reset around each command, so it shares no state with the Invocations before and after it.
| Outcome | Function Response |
|---|---|
| Exit code 0 | 200, the command output as plain text body |
| Any other exit code | 500, the command output as plain text body, also logged to stderr |
args not a JSON object |
500 |
The Front Controller returns a Response, a PSR-15 handler or a plain HttpKernelInterface |
500, as there is no Console Application to run the command |
Security model
A body only becomes a Command Invocation when both hold:
- the Event carries neither
X-Real-IpnorX-Envoy-External-Address, which the platform sets on every HTTP call, overwriting what the client sends, and which CRON Events lack; - its
secretmatchesSCALEWAY_CRON_SECRET, compared in constant time.
Otherwise the body reaches the Application as a plain HTTP body on POST /, and a rejected body carrying a secret is logged (without its value).
So no HTTP call can run a command, even with the secret, and without SCALEWAY_CRON_SECRET, or with an empty one, Command Invocations are off.
The first check relies on undocumented platform behaviour, which is why the secret stays required.
Keep in mind that:
- the secret is stored in clear in the trigger's arguments, readable by anyone who can read the function's triggers or the Terraform state;
- rotating it means updating the variable and every CRON trigger together.
See ADR 0005 for the alternatives considered.
Packaging
vendor/bin/scaleway-package [function.zip]
It zips your application as it is, composer.json and composer.lock included, but without vendor/ nor var/: Scaleway runs composer install --no-dev from the shipped lock at deploy time, Composer scripts included, and replaces any shipped vendor/ (ADR 0008).
Executable bits are kept, and symbolic links are followed: their target is zipped.
It refuses to build the zip, as Scaleway would install something else or fail without failing the deployment, when:
handler.phporcomposer.lockis missing;composer.lockis not up to date withcomposer.json;composer.jsondeclares apathrepository, orcomposer.lockinstalls a package from a local path: Scaleway cannot resolve them.
| Shipped | Not shipped |
|---|---|
Your code, composer.json, composer.lock, handler.php |
vendor/ and var/ (installed and built on the platform) |
.env, .env.prod... as they are |
tests/, phpunit.xml(.dist), .phpunit.cache, .phpunit.result.cache, .php-cs-fixer.cache |
.env.local, .env.local.php, .env.*.local |
|
.git, .idea, .vscode, .DS_Store, node_modules anywhere |
|
.terraform, *.tfstate, *.tfstate.* anywhere (Terraform state holds secrets in clear) |
The full list is Packager::EXCLUDES in src/Packager.php.
Scaleway accepts zips up to 100 MiB, and up to 500 MiB of unzipped code (limits).
scaleway-package warns when the zip or its content exceeds either, but still writes it.
Deployment
example/terraform deploys the example application with its php85 runtime, handler.handle, APP_ENV=prod, the APP_SECRET and SCALEWAY_CRON_SECRET secrets, an optional SCALEWAY_HOST, a CRON trigger calling POST / and one running a command.
Its README gives the commands.
That Terraform code was written against the scaleway/scaleway provider v2.92 documentation and has never been applied; the probe's, written the same way, has.
Redeploy by running scaleway-package again, then terraform apply.
Replacing a function, for instance to change its runtime, deletes its CRON triggers on Scaleway's side: give them a lifecycle { replace_triggered_by = [scaleway_function.<name>.id] }, as the example does, so the same apply recreates them.
Local development with the Emulator
vendor/bin/scaleway-serve [127.0.0.1:8000]
The Emulator turns each HTTP request into an Event, calls your handle() and turns the Function Response back into the HTTP response.
handle() runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code.
It sets APP_ENV=dev unless started with an APP_ENV, as the deployed function defaults to prod.
A crashed process is replaced by a fresh one, as Scaleway starts a new instance.
PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory.
The Event and the context are built the way the platform builds them (measured):
- the
httpMethod,queryStringParameters(sorted by key, the last value of a repeated key winning,[]without query string) and other keys of the platform; - header names in
Title-Case, repeated headers joined with,, noHost; X-Real-Ip,X-Envoy-External-Address,X-Request-IdandX-Forwarded-Proto: httpsset whatever the client sends, the client'sX-Forwarded-Forkept in front of its address, itsX-Forwarded-Hostpassed through;- empty, multipart and non UTF-8 bodies base64-encoded with
isBase64Encoded: true, text bodies without the flag.
So the Requests are https, and their host is localhost unless you set SCALEWAY_HOST, as on the platform.
No HTTP call can be a CRON Invocation, so the Emulator turns a POST on its reserved /_scaleway/cron path into a CRON Event whose arguments are the request body:
curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"job": "cleanup"}'
Simulate a Command Invocation by starting the Emulator with SCALEWAY_CRON_SECRET set, and sending the Command Invocation body the same way:
SCALEWAY_CRON_SECRET=local-secret vendor/bin/scaleway-serve
curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}'
To run what gets deployed, install the zip the way Scaleway does, without the function's variables, then serve it in prod:
vendor/bin/scaleway-package
unzip -q function.zip -d /tmp/function
composer install --working-dir=/tmp/function --no-dev
APP_ENV=prod APP_SECRET=local php /tmp/function/vendor/bin/scaleway-serve
The example's e2e/deploy-locally.sh does the same with the runtime of this repository.
Warm Processes
The Application is built once per Warm Process and reused by the following Invocations, like with FrankenPHP's worker mode or RoadRunner (ADR 0002).
Scaleway keeps processes warm: consecutive Invocations of an instance run in the same PHP process.
Between Invocations, for a Kernel:
terminate()runs after each Invocation, and a failure in it is logged without changing the Function Response;- the
services_resetterresets the services taggedkernel.resetbefore the next request, as Symfony's Kernel does; - uploaded files are deleted, and output buffers the Application left open are closed.
Everything else survives, so your application must be safe for long-running execution:
- do not keep per-request state in static properties or in services that do not implement
ResetInterface; - in-memory caches and collections grow across Invocations unless reset;
- connections (database, HTTP clients) may have been closed by the server while the process was idle;
exit()or a fatal error ends the process, and the next Invocation pays a cold start.
Limitations and platform caveats
Requests and responses
- Superglobals:
$_GET,$_POST,$_COOKIE,$_FILESand the request entries of$_SERVER(REQUEST_URI,HTTP_*...) are not populated per Invocation.
Read theRequestobject instead;Request::createFromGlobals()does not describe the Invocation. - Output: only the returned
Responsereaches the client.
echooutside the Response,header()andhttp_response_code()do not: Scaleway does not put stdout in the response body. - Query strings: the Event carries
queryStringParametersas a map, so a repeated key such asa=1&a=2, ortags[]=a&tags[]=b, reaches the Application with its last value only, and the keys arrive sorted, not in the order the client sent them.
Keys are then parsed like PHP does, soa.bbecomesa_banda[b]nests. - Form bodies:
application/x-www-form-urlencodedbodies are parsed forPOST,PUT,DELETE,PATCHandQUERY,multipart/form-dataonly forPOST, as PHP does.
Uploaded files areUploadedFileobjects in test mode:move()works,is_uploaded_file()does not. - Cookies: request cookie names are taken verbatim: unlike PHP's
$_COOKIE, dots and spaces are not turned into underscores anda[b]does not nest. - Streaming:
StreamedResponseandBinaryFileResponseare buffered into one Function Response; Server-Sent Events and long downloads are not possible.
Bodies that are not valid UTF-8 are sent base64-encoded, and decoded by the platform. - PSR-15 responses go through Symfony's
Response, which addsCache-Control: no-cache, privateandDatewhen they are missing. - HEAD requests: only FrameworkBundle's
ResponseListenerstrips the body of aHEADresponse, but the platform sends none anyway. - Request size: Scaleway rejects request bodies over 6 MiB with a
413, before they reach the function. - CORS: Scaleway adds
Access-Control-Allow-Origin: *andAccess-Control-Allow-Headers: Content-Typeto every response, whatever the Application sends.
Any website can therefore read the responses of a public function from a browser, though without the user's cookies: do not rely on the same-origin policy to protect them. - Uncaught failures: the runtime turns exceptions into a 500 itself, but a fatal error or
exit()ends the Warm Process, and Scaleway answers a failed Invocation with a500whose body isError while executing function.
Client IP and trusted proxies
The runtime trusts no proxy, as clients can forge most forwarding headers on Scaleway (ADR 0007):
| Request | From | Why |
|---|---|---|
getClientIp() |
X-Real-Ip, 127.0.0.1 without it (CRON Invocations) |
Set by the platform, whatever the client sends |
isSecure(), getScheme(), port |
X-Forwarded-Proto, the scheme's default port |
Set by the platform (https, http for CRON Invocations) |
getHost() |
The host option |
No Host header reaches the function |
X-Forwarded-For (the client's value is kept in front), X-Forwarded-Host, X-Forwarded-Port and Forwarded are passed through from the client: they reach the Application as plain headers, and nothing trusts them.
Headers whose name holds an underscore (X_Real_Ip) are dropped, as nginx and Apache do, since PHP would read them as the platform's ones.
[!CAUTION]
Do not configureframework.trusted_proxies: the client is already resolved, and trustingREMOTE_ADDRor private ranges would make Symfony trust those forgeable headers again.
Trusted proxies your application configures still apply, as usual.
Composer at deploy time
Scaleway runs composer install --no-dev in the function's directory when the zip holds a composer.json at its root, replacing any shipped vendor/.
Every locked package must therefore be downloadable from Scaleway, and the function's environment variables are not available to Composer scripts.
A failing install or script does not fail the deployment: the function becomes ready anyway, so check its first Invocations after a deploy.
Windows
scaleway-serve relies on Unix sockets: it runs on macOS and Linux, not on Windows outside WSL, and scaleway-package is only tested on macOS and Linux.
Without the pcntl extension, stopping the Emulator with kill may leave its PHP processes running.
Not measured
The probe settled every platform fact the runtime relies on (results), except:
- where stdout, stderr and uncaught exceptions are logged (Cockpit);
- whether a deployment whose Composer install or script fails serves the new code or keeps the previous version.
Contributing
composer install
composer check # PHP-CS-Fixer (dry run), PHPStan (max level) and PHPUnit
composer cs-fix # applies the coding style
CI runs composer validate --strict and composer check on PHP 8.4 and 8.5, each against Symfony 7.4 and 8.x, the whole Symfony stack being pinned through Flex's SYMFONY_REQUIRE.
It also runs the end-to-end scenarios of the example application through the Emulator, in dev and on its zip installed like Scaleway does (e2e/deploy-locally.sh).
The example installs the runtime of the checkout with composer link-runtime, see its README.
The repository holds:
src/,bin/,resources/: the package;tests/: PHPUnit tests, packaging included;example/: a demo Symfony application requiring the package, with Terraform code to deploy it;probe/: a dependency-free function measuring the platform facts, and its results;docs/: the implementation plan and the ADRs.
License
Released under the MIT License.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 |
|