docs: split the README into a documentation folder organised by domainUnverified
The README keeps the introduction, requirements and installation, and points to docs/README.md, an index of guides grouped by domain (using the runtime, shipping, developing). The contribution workflow moves to CONTRIBUTING.md, and docs/adr/README.md indexes the decision records.
a4d5dea parent: b1ce229 added
CONTRIBUTING.md +20 -0 | new file mode 100644 | ||
| @@ -0,0 +1,20 @@ | ||
| 1 | +# Contributing | |
| 2 | + | |
| 3 | +```sh | |
| 4 | +composer install | |
| 5 | +composer check # PHP-CS-Fixer (dry run), PHPStan (max level) and PHPUnit | |
| 6 | +composer cs-fix # applies the coding style | |
| 7 | +``` | |
| 8 | + | |
| 9 | +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`. | |
| 10 | +It also runs the [end-to-end scenarios](example/e2e/run.sh) of the [example application](example) through the Emulator, in dev and on its zip installed like Scaleway does ([e2e/deploy-locally.sh](example/e2e/deploy-locally.sh)). | |
| 11 | +The example installs the runtime of the checkout with `composer link-runtime`, see its [README](example/README.md#run-it-locally). | |
| 12 | +A weekly workflow measures the Function Runtimes on Scaleway again, and opens a pull request when the catalogue changes, see [docs/probe-results.md](docs/probe-results.md#function-runtime-catalogue). | |
| 13 | + | |
| 14 | +The repository holds: | |
| 15 | + | |
| 16 | +- `src/`, `bin/`, `resources/`: the package; | |
| 17 | +- `tests/`: PHPUnit tests, packaging included; | |
| 18 | +- `example/`: a demo Symfony application requiring the package, with Terraform code to deploy it; | |
| 19 | +- `probe/`: a dependency-free function measuring the platform facts, its [results](docs/probe-results.md), and the generator of the [Function Runtime Catalogue](docs/probe-results.md#function-runtime-catalogue); | |
| 20 | +- `docs/`: the [user documentation](docs/README.md) and the [ADRs](docs/adr/README.md). | |
| new file mode 100644 | |||
| @@ -0,0 +1,20 @@ | |||
| 1 | +# Contributing | ||
| 2 | + | ||
| 3 | +```sh | ||
| 4 | +composer install | ||
| 5 | +composer check # PHP-CS-Fixer (dry run), PHPStan (max level) and PHPUnit | ||
| 6 | +composer cs-fix # applies the coding style | ||
| 7 | +``` | ||
| 8 | + | ||
| 9 | +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`. | ||
| 10 | +It also runs the [end-to-end scenarios](example/e2e/run.sh) of the [example application](example) through the Emulator, in dev and on its zip installed like Scaleway does ([e2e/deploy-locally.sh](example/e2e/deploy-locally.sh)). | ||
| 11 | +The example installs the runtime of the checkout with `composer link-runtime`, see its [README](example/README.md#run-it-locally). | ||
| 12 | +A weekly workflow measures the Function Runtimes on Scaleway again, and opens a pull request when the catalogue changes, see [docs/probe-results.md](docs/probe-results.md#function-runtime-catalogue). | ||
| 13 | + | ||
| 14 | +The repository holds: | ||
| 15 | + | ||
| 16 | +- `src/`, `bin/`, `resources/`: the package; | ||
| 17 | +- `tests/`: PHPUnit tests, packaging included; | ||
| 18 | +- `example/`: a demo Symfony application requiring the package, with Terraform code to deploy it; | ||
| 19 | +- `probe/`: a dependency-free function measuring the platform facts, its [results](docs/probe-results.md), and the generator of the [Function Runtime Catalogue](docs/probe-results.md#function-runtime-catalogue); | ||
| 20 | +- `docs/`: the [user documentation](docs/README.md) and the [ADRs](docs/adr/README.md). | ||
modified
README.md +10 -632 | @@ -6,35 +6,18 @@ Scaleway calls a PHP function `handle($event, $context)` for each Invocation. | ||
| 6 | 6 | 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. |
| 7 | 7 | It also ships the tools to package the function and to run it locally. |
| 8 | 8 | |
| 9 | -Vocabulary (Invocation, Event, Warm Process...) is defined in [GLOSSARY.md](GLOSSARY.md), design decisions in [docs/adr](docs/adr). | |
| 9 | +Vocabulary (Invocation, Event, Warm Process...) is defined in [GLOSSARY.md](GLOSSARY.md), design decisions in [docs/adr](docs/adr/README.md). | |
| 10 | 10 | |
| 11 | 11 | > [!IMPORTANT] |
| 12 | 12 | > The platform facts the runtime relies on were measured on Scaleway with the [probe](probe), see [docs/probe-results.md](docs/probe-results.md). |
| 13 | 13 | > The [example application](example) runs on Scaleway: its scenarios, CRON triggers and Command Invocations were checked on a deployment. |
| 14 | 14 | |
| 15 | -## Contents | |
| 16 | - | |
| 17 | -- [Requirements](#requirements) | |
| 18 | -- [Installation](#installation) | |
| 19 | -- [Configuration](#configuration) | |
| 20 | -- [Supported Applications](#supported-applications) | |
| 21 | -- [Static Files](#static-files) | |
| 22 | -- [CRON triggers and Command Invocations](#cron-triggers-and-command-invocations) | |
| 23 | -- [Compatibility check](#compatibility-check) | |
| 24 | -- [Packaging](#packaging) | |
| 25 | -- [Deployment](#deployment) | |
| 26 | -- [Logs](#logs) | |
| 27 | -- [Local development with the Emulator](#local-development-with-the-emulator) | |
| 28 | -- [Warm Processes](#warm-processes) | |
| 29 | -- [Limitations and platform caveats](#limitations-and-platform-caveats) | |
| 30 | -- [Contributing](#contributing) | |
| 31 | - | |
| 32 | 15 | ## Requirements |
| 33 | 16 | |
| 34 | 17 | - The Scaleway PHP runtimes `php84` or `php85` (PHP 8.4 or later). |
| 35 | 18 | - Symfony 7.4 or 8.x components (`symfony/runtime`, `symfony/http-kernel`, `symfony/http-foundation`). |
| 36 | 19 | - To build the deployment zip: the `zip` PHP extension. |
| 37 | -- macOS or Linux for the packaging and Emulator tools (see [Windows](#windows)). | |
| 20 | +- macOS or Linux for the packaging and Emulator tools (see [Windows](docs/local-development.md#windows)). | |
| 38 | 21 | |
| 39 | 22 | ## Installation |
| 40 | 23 | |
| @@ -63,624 +46,19 @@ Your Front Controller stays as it is, `require_once dirname(__DIR__).'/vendor/au | ||
| 63 | 46 | 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. |
| 64 | 47 | 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. |
| 65 | 48 | |
| 66 | -## Configuration | |
| 67 | - | |
| 68 | -### Function handler | |
| 69 | - | |
| 70 | -Set the handler of the Scaleway function to `handler.handle`. | |
| 71 | - | |
| 72 | -### Front Controller | |
| 73 | - | |
| 74 | -The Front Controller defaults to `public/index.php`, relative to the project dir. | |
| 75 | -Choose another one with the `front_controller` runtime option, in `composer.json`: | |
| 76 | - | |
| 77 | -```json | |
| 78 | -{ | |
| 79 | - "extra": { | |
| 80 | - "runtime": { | |
| 81 | - "front_controller": "public/api.php" | |
| 82 | - } | |
| 83 | - } | |
| 84 | -} | |
| 85 | -``` | |
| 86 | - | |
| 87 | -Or with the `APP_RUNTIME_OPTIONS` environment variable, a JSON object that wins over `extra.runtime`: | |
| 88 | - | |
| 89 | -```sh | |
| 90 | -APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | |
| 91 | -``` | |
| 92 | - | |
| 93 | -The other `SymfonyRuntime` options (`project_dir`, `env_var_name`, `dotenv_path`...) work as usual. | |
| 94 | -`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`. | |
| 95 | - | |
| 96 | -### Environment variables | |
| 97 | - | |
| 98 | -Set these on the function, in production: | |
| 99 | - | |
| 100 | -| Variable | Kind | Why | | |
| 101 | -| --- | --- | --- | | |
| 102 | -| `APP_SECRET` | Secret | Symfony's `kernel.secret`, used to sign URLs, cookies and CSRF tokens. | | |
| 103 | -| `SCALEWAY_HOST` | Plain | The public host of the function, for absolute URLs, see [Host](#host). | | |
| 104 | -| `SCALEWAY_CRON_SECRET` | Secret | Only to run console commands from CRON triggers, see [Command Invocations](#command-invocations). | | |
| 105 | -| `APP_ENV` | Plain | Only to run another env than `prod`, see below. | | |
| 106 | - | |
| 107 | -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. | |
| 108 | -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](docs/adr/0006-default-to-the-prod-env.md)). | |
| 109 | -Only an `APP_ENV` variable of the function, or the `env` runtime option, picks another env. | |
| 110 | -`APP_DEBUG` follows: off in `prod`, unless set by the function's environment or a `.env` file. | |
| 111 | -The Emulator runs `dev` instead, unless it is started with an `APP_ENV`. | |
| 112 | - | |
| 113 | -For every other variable, real environment variables win over `.env` files, as usual with Symfony's Dotenv. | |
| 114 | -`.env.local`, `.env.local.php` and `.env.*.local` are never shipped. | |
| 115 | - | |
| 116 | -### Host | |
| 117 | - | |
| 118 | -No `Host` header reaches the function, so the runtime cannot know the domain it is called on. | |
| 119 | -Every Request gets the host of the `host` runtime option, which defaults to the `SCALEWAY_HOST` environment variable, then to `localhost`: | |
| 120 | - | |
| 121 | -```sh | |
| 122 | -SCALEWAY_HOST=api.example.com | |
| 123 | -``` | |
| 124 | - | |
| 125 | -The scheme comes from the platform's `X-Forwarded-Proto` (`https` for HTTP calls), the port is the scheme's default. | |
| 126 | -Absolute URLs (`UrlGeneratorInterface::ABSOLUTE_URL`, signed URLs, redirects built from the Request) are only right once the host is set. | |
| 127 | -Set it to the function's domain (its `domain_name` on Scaleway) or to its custom domain. | |
| 128 | -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. | |
| 129 | -An application configuring `framework.trusted_hosts` answers every Request with a 400 until the host is set to one of its trusted hosts. | |
| 130 | -Both were [measured on Scaleway](docs/probe-results.md#absolute-urls), forged `X-Forwarded-Host` and `Forwarded` headers never changing the host. | |
| 131 | - | |
| 132 | -### Cache and writable directories | |
| 133 | - | |
| 134 | -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. | |
| 135 | -To pay it at deploy time instead, warm the cache from a Composer script, which Scaleway runs after installing the dependencies: | |
| 136 | - | |
| 137 | -```json | |
| 138 | -{ | |
| 139 | - "scripts": { | |
| 140 | - "post-install-cmd": ["@php bin/console cache:warmup --env=prod"] | |
| 141 | - } | |
| 142 | -} | |
| 143 | -``` | |
| 144 | - | |
| 145 | -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. | |
| 146 | - | |
| 147 | -> [!WARNING] | |
| 148 | -> Symfony Flex's `auto-scripts` also run at deploy time, with the `APP_ENV` of the shipped `.env`, usually `dev`: `cache:clear` then fails silently, its dev bundles not being installed with `--no-dev`. | |
| 149 | -> Make them env-explicit (`"cache:clear --env=prod": "symfony-cmd"`), or remove `cache:clear` from them and warm the cache as above. | |
| 150 | - | |
| 151 | -When the project's `var/` directory (or the project dir, without `var/`) is not writable, the runtime sets, unless your application already did: | |
| 152 | - | |
| 153 | -- `APP_CACHE_DIR` to `<temp dir>/cache` and `APP_LOG_DIR` to `<temp dir>/log`; | |
| 154 | -- `APP_BUILD_DIR` to `var/cache`, only when `var/cache/<env>` holds a container warmed before, so that it is used as is. | |
| 155 | - | |
| 156 | -Kernels using `MicroKernelTrait` read these variables. | |
| 157 | -Other Kernels must override `getCacheDir()`, `getBuildDir()` and `getLogDir()` themselves. | |
| 158 | -Logs written to files are lost with the instance: send them to `php://stderr` instead, which the runtime also uses for its own errors. | |
| 159 | - | |
| 160 | -### Errors | |
| 161 | - | |
| 162 | -An exception escaping the Application (a Kernel failing to boot, an unsupported Front Controller...) is logged to stderr ([Logs](#logs)) and answered with a 500. | |
| 163 | -Its body is `Internal Server Error`, or the full exception when `APP_DEBUG` is true. | |
| 164 | -A Kernel that failed to boot is built again from scratch on the next Invocation. | |
| 165 | - | |
| 166 | -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. | |
| 167 | -Outside a web SAPI, FrameworkBundle would pick its CLI error renderer instead, which dumps the exception even in `prod`. | |
| 168 | - | |
| 169 | -## Supported Applications | |
| 170 | - | |
| 171 | -The Front Controller returns a closure, as with any Symfony Runtime. | |
| 172 | -The type of what that closure returns, the Application, decides how Invocations are served. | |
| 173 | - | |
| 174 | -### HttpKernel | |
| 175 | - | |
| 176 | -The usual Symfony Front Controller: | |
| 177 | - | |
| 178 | -```php | |
| 179 | -<?php // public/index.php | |
| 180 | - | |
| 181 | -use App\Kernel; | |
| 182 | - | |
| 183 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 184 | - | |
| 185 | -return function (array $context) { | |
| 186 | - return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); | |
| 187 | -}; | |
| 188 | -``` | |
| 189 | - | |
| 190 | -The Kernel is booted once per Warm Process and serves every Invocation, see [Warm Processes](#warm-processes). | |
| 191 | -Any `HttpKernelInterface` works; a `KernelInterface` also runs [Command Invocations](#command-invocations). | |
| 192 | - | |
| 193 | -### Response | |
| 194 | - | |
| 195 | -A closure returning a `Response` is called again for every Invocation, without any Kernel. | |
| 196 | -A `Request` argument receives the Invocation's Request: | |
| 197 | - | |
| 198 | -```php | |
| 199 | -<?php // public/hello.php | |
| 200 | - | |
| 201 | -use Symfony\Component\HttpFoundation\JsonResponse; | |
| 202 | -use Symfony\Component\HttpFoundation\Request; | |
| 203 | - | |
| 204 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 205 | - | |
| 206 | -return static function (Request $request): JsonResponse { | |
| 207 | - return new JsonResponse(['message' => sprintf('Hello %s!', $request->query->get('name', 'World'))]); | |
| 208 | -}; | |
| 209 | -``` | |
| 210 | - | |
| 211 | -Keep the closure cheap, as it runs on every Invocation, and make it return a `Response` every time. | |
| 212 | -See [ADR 0004](docs/adr/0004-call-response-front-controllers-per-invocation.md). | |
| 213 | - | |
| 214 | -### PSR-15 request handler | |
| 215 | - | |
| 216 | -A closure returning a `Psr\Http\Server\RequestHandlerInterface` builds it once per Warm Process. | |
| 217 | -It needs two more packages: | |
| 218 | - | |
| 219 | -```sh | |
| 220 | -composer require symfony/psr-http-message-bridge nyholm/psr7 | |
| 221 | -``` | |
| 222 | - | |
| 223 | -```php | |
| 224 | -<?php // public/index.php | |
| 225 | - | |
| 226 | -use App\ApiHandler; | |
| 227 | -use Psr\Http\Server\RequestHandlerInterface; | |
| 228 | - | |
| 229 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 230 | - | |
| 231 | -return static fn (): RequestHandlerInterface => new ApiHandler(); | |
| 232 | -``` | |
| 233 | - | |
| 234 | -The PSR-7 request carries the client address, scheme, host and port the runtime resolved (see [Client IP and trusted proxies](#client-ip-and-trusted-proxies)), in its URI and in the `REMOTE_ADDR`, `HTTPS`, `HTTP_HOST` and `SERVER_PORT` server params. | |
| 235 | -A handler implementing `Symfony\Contracts\Service\ResetInterface` is reset before every Invocation but the first. | |
| 236 | -A malformed host is answered with a 400 before reaching the handler. | |
| 237 | - | |
| 238 | -### Console Application or Command | |
| 239 | - | |
| 240 | -A Front Controller returning a Console `Application` or a `Command` only serves [Command Invocations](#command-invocations), and answers every other Invocation with a 403. | |
| 241 | -Symfony's `bin/console` is such a Front Controller: | |
| 242 | - | |
| 243 | -```sh | |
| 244 | -APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | |
| 245 | -``` | |
| 246 | - | |
| 247 | -A single `Command` runs whatever `command` the Command Invocation names: | |
| 248 | - | |
| 249 | -```php | |
| 250 | -<?php // bin/cleanup.php | |
| 251 | - | |
| 252 | -use Symfony\Component\Console\Command\Command; | |
| 253 | -use Symfony\Component\Console\Input\InputInterface; | |
| 254 | -use Symfony\Component\Console\Output\OutputInterface; | |
| 255 | - | |
| 256 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 257 | - | |
| 258 | -return static fn (): Command => (new Command('app:cleanup')) | |
| 259 | - ->setCode(static function (InputInterface $input, OutputInterface $output): int { | |
| 260 | - $output->writeln('Cleaned up'); | |
| 261 | - | |
| 262 | - return Command::SUCCESS; | |
| 263 | - }); | |
| 264 | -``` | |
| 265 | - | |
| 266 | -This needs `symfony/console`, and `symfony/framework-bundle` for a `Symfony\Bundle\FrameworkBundle\Console\Application`. | |
| 267 | - | |
| 268 | -### Raw callable | |
| 269 | - | |
| 270 | -A closure returning another `Closure` talks to Scaleway without any translation. | |
| 271 | -The inner closure is built once per Warm Process and receives every Event and context as they are, CRON Invocations included: | |
| 272 | - | |
| 273 | -```php | |
| 274 | -<?php // public/raw.php | |
| 275 | - | |
| 276 | -return static fn (): Closure => static fn (array $event, mixed $context): array => [ | |
| 277 | - 'statusCode' => 200, | |
| 278 | - 'headers' => ['Content-Type' => 'text/plain'], | |
| 279 | - 'body' => 'Hello from '.($event['path'] ?? '/'), | |
| 280 | -]; | |
| 281 | -``` | |
| 282 | - | |
| 283 | -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`. | |
| 284 | -Other keys are dropped, and any other return value fails the Invocation with a 500. | |
| 285 | -Command Invocations are not routed: the raw callable gets their Event like any other. | |
| 286 | -An invokable object is not taken for a raw callable; return `$object(...)` to make it one. | |
| 287 | - | |
| 288 | -## Static Files | |
| 289 | - | |
| 290 | -The runtime serves the files of `public/` itself, before building the Application: stylesheets, JavaScript, images, fonts, `favicon.ico`, `robots.txt`, and what AssetMapper or Webpack Encore compile there. | |
| 291 | -Such an Invocation pays no Kernel boot, and is answered even when the Application fails to build ([ADR 0009](docs/adr/0009-serve-static-files-from-the-function.md)). | |
| 292 | - | |
| 293 | -A file is served when: | |
| 294 | - | |
| 295 | -- the request is a `GET` or a `HEAD`; | |
| 296 | -- the path names a regular file under `<project_dir>/public`, a symbolic link leading out of it excluded; | |
| 297 | -- no segment of the path starts with a dot (`..`, `.env`, `.htaccess`), but for a leading `/.well-known/`; | |
| 298 | -- its extension is not `.php`. | |
| 299 | - | |
| 300 | -Every other request goes to the Application, directories included: there is no index file nor directory listing. | |
| 301 | - | |
| 302 | -> [!IMPORTANT] | |
| 303 | -> A file wins over a route of the same path. | |
| 304 | -> An application answering `/robots.txt` from a controller while shipping `public/robots.txt` gets the file: delete the file to keep the route. | |
| 305 | - | |
| 306 | -### Responses | |
| 307 | - | |
| 308 | -- The `Content-Type` comes from the extension, `application/octet-stream` for an unknown one, without charset. | |
| 309 | -- Each response carries `X-Content-Type-Options: nosniff`, and an `ETag` of the bytes it sends: a matching `If-None-Match` gets a `304` without body. | |
| 310 | -- `Cache-Control` is `public, max-age=0, must-revalidate`: browsers keep the file but check it on each use. | |
| 311 | -- It is `public, max-age=31536000, immutable` for a file whose name changes with its content: one that a `manifest.json` in its directory, or in one above, maps from another name. | |
| 312 | - AssetMapper's `public/assets/manifest.json` and Webpack Encore's `public/build/manifest.json` (with versioning) are such manifests. | |
| 313 | - Names alone are not trusted, as `font-awesome.css` would look as digested as `app-mH7q4W_.css`. | |
| 314 | -- `Range` requests get the whole file with a `200`. | |
| 315 | - | |
| 316 | -No CDN stands in front of a function: every request for a Static File is an Invocation, billed and possibly paying a cold start. | |
| 317 | -Long-lived caching of digested files is what spares most of them. | |
| 318 | - | |
| 319 | -### Compression | |
| 320 | - | |
| 321 | -A file is sent compressed when the client accepts it, in this order: | |
| 322 | - | |
| 323 | -1. a precompressed variant shipped next to it, `app.css.br`, then `app.css.zst`, then `app.css.gz`, written by any build step; | |
| 324 | -2. otherwise, when the `static_compression` runtime option is set, the file compressed by the runtime. | |
| 325 | - | |
| 326 | -```json | |
| 327 | -{ | |
| 328 | - "extra": { | |
| 329 | - "runtime": { | |
| 330 | - "static_compression": "gzip" | |
| 331 | - } | |
| 332 | - } | |
| 333 | -} | |
| 334 | -``` | |
| 335 | - | |
| 336 | -`static_compression` is `false` by default, `"gzip"`, `"zstd"` or `"br"`, each needing its extension (`zlib`, `zstd`, `brotli`): any other value, or one whose extension is not loaded, answers every Invocation with a 500 until fixed. | |
| 337 | -The Scaleway `php85` runtime loads `zlib` and `zstd` but not `brotli`: use `"zstd"` or `"gzip"` there, and ship `.br` variants built beforehand for brotli. | |
| 338 | -The runtime only compresses textual files (`text/*`, JavaScript, JSON, XML, SVG, WebAssembly) of at least 1 KiB, and keeps the results in memory for the Warm Process, up to 32 MiB. | |
| 339 | - | |
| 340 | -The order of preference is the runtime's: only a `q=0` in `Accept-Encoding` refuses an encoding. | |
| 341 | -Compressed responses carry `Content-Encoding`, an `ETag` of their own and `Vary: Accept-Encoding`. | |
| 342 | -A request for `app.css.gz` itself gets that file, as any other. | |
| 343 | - | |
| 344 | -### Limits | |
| 345 | - | |
| 346 | -- A Static File must fit in one Function Response, base64-encoded when it is binary, which takes a third more. | |
| 347 | - Scaleway enforces no limit, but responses of 10 MiB and more intermittently fail with a `504` after 60 seconds ([measured](docs/probe-results.md#size-and-encodings)). | |
| 348 | - The runtime therefore refuses Static Files over 6 MiB in a Function Response: it answers a 500 and logs the file, and `scaleway-package` warns about such files. | |
| 349 | -- A file written at runtime under `public/`, such as an upload, is only served by the instance that wrote it, each instance having its own disk. | |
| 350 | -- Store uploads, large files and busy sites' assets on Object Storage, behind Edge Services or not, and point `framework.assets.base_urls` to it. | |
| 351 | -- `assets:install` boots the Kernel: at deploy time, run it from a `post-install-cmd` with an explicit env, `@php bin/console assets:install public --env=prod`, for the same reasons as [`cache:warmup`](#cache-and-writable-directories). | |
| 352 | - | |
| 353 | -## CRON triggers and Command Invocations | |
| 49 | +## Documentation | |
| 354 | 50 | |
| 355 | -### CRON triggers | |
| 51 | +The [documentation index](docs/README.md) lists every guide. The usual path: | |
| 356 | 52 | |
| 357 | -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`). | |
| 358 | -With a Kernel, handle it like any route: | |
| 359 | - | |
| 360 | -```php | |
| 361 | -#[Route('/', methods: ['POST'])] | |
| 362 | -public function cron(Request $request): Response | |
| 363 | -{ | |
| 364 | - $args = $request->toArray(); // the trigger's arguments | |
| 365 | - // ... | |
| 366 | -} | |
| 367 | -``` | |
| 368 | - | |
| 369 | -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. | |
| 370 | - | |
| 371 | -### Command Invocations | |
| 372 | - | |
| 373 | -A CRON trigger may run a console command instead, through the Console Application of the same Kernel. | |
| 374 | - | |
| 375 | -1. Generate a random secret, for instance with `openssl rand -hex 32`. | |
| 376 | -2. Set it as the `SCALEWAY_CRON_SECRET` secret environment variable of the function. | |
| 377 | -3. Give the CRON trigger these arguments: | |
| 378 | - | |
| 379 | -```json | |
| 380 | -{"command": "app:sync", "args": {"source": "s3", "--force": true, "--tag": ["a", "b"]}, "secret": "<SCALEWAY_CRON_SECRET>"} | |
| 381 | -``` | |
| 382 | - | |
| 383 | -`args` is optional, and maps argument names, and option names with their dashes, to values, as Symfony's `ArrayInput` does. | |
| 384 | -The command runs without interaction: questions get their default answer. | |
| 385 | -Services are reset around each command, so it shares no state with the Invocations before and after it. | |
| 386 | - | |
| 387 | -| Outcome | Function Response | | |
| 388 | -| --- | --- | | |
| 389 | -| Exit code 0 | 200, the command output as plain text body | | |
| 390 | -| Any other exit code | 500, the command output as plain text body, also logged to stderr | | |
| 391 | -| `args` not a JSON object | 500 | | |
| 392 | -| 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 | | |
| 393 | - | |
| 394 | -Nothing shows the Function Response of a CRON Invocation, and a failed one is not retried: the [logs](#logs) are where the outcome of a command shows up, so log what it does ([measured](docs/probe-results.md#cron-invocations)). | |
| 395 | - | |
| 396 | -### Security model | |
| 397 | - | |
| 398 | -A body only becomes a Command Invocation when both hold: | |
| 399 | - | |
| 400 | -- the Event carries neither `X-Real-Ip` nor `X-Envoy-External-Address`, which the platform sets on every HTTP call, overwriting what the client sends, and which CRON Events lack; | |
| 401 | -- its `secret` matches `SCALEWAY_CRON_SECRET`, compared in constant time. | |
| 402 | - | |
| 403 | -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). | |
| 404 | -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. | |
| 405 | -The first check relies on undocumented platform behaviour, which is why the secret stays required. | |
| 406 | - | |
| 407 | -Keep in mind that: | |
| 408 | - | |
| 409 | -- 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; | |
| 410 | -- rotating it means updating the variable and every CRON trigger together. | |
| 411 | - | |
| 412 | -See [ADR 0005](docs/adr/0005-authenticate-command-invocations-with-a-shared-secret.md) for the alternatives considered. | |
| 413 | - | |
| 414 | -## Compatibility check | |
| 415 | - | |
| 416 | -```sh | |
| 417 | -vendor/bin/scaleway-doctor --runtime=php84 | |
| 418 | -``` | |
| 419 | - | |
| 420 | -A Platform Requirement (`php` or `ext-*`) the Function Runtime does not meet makes Scaleway's `composer install` fail at deploy time, without failing the deployment: every Invocation then answers a `500` (see [Composer at deploy time](#composer-at-deploy-time)). | |
| 421 | -`scaleway-doctor` checks, before you deploy, the Platform Requirements that install checks, against the Function Runtime the function declares, named by `--runtime` (`php84` or `php85`). | |
| 422 | -It never guesses it from your local PHP. | |
| 423 | -It reads `composer.json` and `composer.lock`, needs neither Scaleway credentials nor network access, and refuses a stale lock as [`scaleway-package`](#packaging) does. | |
| 424 | - | |
| 425 | -It checks what `composer install --no-dev` checks on Scaleway: | |
| 426 | - | |
| 427 | -- the root requirements the lock records, and those of every locked production package, development ones excluded; | |
| 428 | -- each one met by the Function Runtime, or by a `provide` or `replace` of the application or of a locked package; | |
| 429 | -- constraints evaluated by Composer's own engine, against the PHP and extension versions Composer would see on Scaleway. | |
| 430 | - | |
| 431 | -Each requirement is: | |
| 432 | - | |
| 433 | -- **satisfied**, when the measured version matches; | |
| 434 | -- **incompatible**, when the extension is not loaded, or the measured version of PHP or of the extension does not match; | |
| 435 | -- **unknown**, for the platform packages the catalogue does not measure, as `lib-icu` or `php-64bit`. | |
| 436 | - | |
| 437 | -Composer's own APIs (`composer`, `composer-plugin-api`, `composer-runtime-api`) are not checked: Scaleway installs with Composer 2. | |
| 438 | - | |
| 439 | -The report, on stderr, lists the incompatible and unknown requirements, with what declares them and what the Function Runtime provides: | |
| 440 | - | |
| 441 | -```text | |
| 442 | -INCOMPATIBLE ext-foo * required by acme/bar v2.1.0 php84: not loaded (measured 2026-11-22) | |
| 443 | - php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions. | |
| 444 | -UNKNOWN lib-icu >=72 required by symfony/intl v8.0.3 not in the Function Runtime Catalogue | |
| 445 | - | |
| 446 | -48 satisfied, 1 unknown, 1 incompatible on php84 (measured 2026-11-22) | |
| 447 | -This covers declared Platform Requirements only, not whether the application runs. | |
| 448 | -``` | |
| 449 | - | |
| 450 | -It exits with `0` when every requirement is satisfied or only unknowns remain, and with `1` on an incompatible requirement or an invalid input. | |
| 451 | -For an incompatible requirement, it names the other Function Runtimes that meet it, if any. | |
| 452 | -Otherwise, custom extensions or versions need [Serverless Containers](https://www.scaleway.com/en/serverless-containers/), which this package does not target. | |
| 453 | - | |
| 454 | -What each Function Runtime provides comes from the Function Runtime Catalogue shipped with the package, [resources/function-runtimes.php](resources/function-runtimes.php). | |
| 455 | -It holds measurements only, made on Scaleway with the [probe](probe), each a complete inventory: an extension it does not list is not loaded. | |
| 456 | -A measurement describes the Function Runtime on its date, which the report shows, not a guarantee that Scaleway keeps the same versions. | |
| 457 | -The measured PHP patch version is authoritative: if Scaleway has upgraded PHP since, update the package for a newer catalogue. | |
| 458 | - | |
| 459 | -The [Emulator](#local-development-with-the-emulator) runs on your local PHP, which may load extensions or versions the Function Runtime lacks: an application working locally can still fail to install on Scaleway, which is what this check catches. | |
| 460 | -A successful check covers declared Platform Requirements only: an extension used without being required is not checked, and calling a route after the deployment, as [Composer at deploy time](#composer-at-deploy-time) shows, remains the proof that it works. | |
| 461 | - | |
| 462 | -## Packaging | |
| 463 | - | |
| 464 | -```sh | |
| 465 | -vendor/bin/scaleway-package [--runtime=php84] [function.zip] | |
| 466 | -``` | |
| 467 | - | |
| 468 | -With `--runtime`, it first runs the [compatibility check](#compatibility-check) against that Function Runtime, and refuses to build the zip on an incompatible Platform Requirement. | |
| 469 | - | |
| 470 | -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](docs/adr/0008-let-scaleway-install-the-dependencies.md)). | |
| 471 | -Executable bits are kept, and symbolic links are followed: their target is zipped. | |
| 472 | - | |
| 473 | -It refuses to build the zip, as Scaleway would install something else or fail without failing the deployment, when: | |
| 474 | - | |
| 475 | -- `handler.php` or `composer.lock` is missing; | |
| 476 | -- `composer.lock` is not up to date with `composer.json`; | |
| 477 | -- `composer.json` declares a `path` repository, or `composer.lock` installs a package from a local path: Scaleway cannot resolve them. | |
| 478 | - | |
| 479 | -| Shipped | Not shipped | | |
| 480 | -| --- | --- | | |
| 481 | -| Your code, `composer.json`, `composer.lock`, `handler.php` | `vendor/` and `var/` (installed and built on the platform) | | |
| 482 | -| `.env`, `.env.prod`... as they are | `tests/`, `phpunit.xml(.dist)`, `.phpunit.cache`, `.phpunit.result.cache`, `.php-cs-fixer.cache` | | |
| 483 | -| | `.env.local`, `.env.local.php`, `.env.*.local` | | |
| 484 | -| | `.git`, `.idea`, `.vscode`, `.DS_Store`, `node_modules` anywhere | | |
| 485 | -| | `.terraform`, `*.tfstate`, `*.tfstate.*` anywhere (Terraform state holds secrets in clear) | | |
| 486 | - | |
| 487 | -The full list is `Packager::EXCLUDES` in [src/Packager.php](src/Packager.php). | |
| 488 | - | |
| 489 | -Scaleway accepts zips up to 100 MiB, and up to 500 MiB of unzipped code ([limits](https://www.scaleway.com/en/docs/serverless-functions/reference-content/functions-limitations/)). | |
| 490 | -`scaleway-package` warns when the zip or its content exceeds either, but still writes it. | |
| 491 | - | |
| 492 | -## Deployment | |
| 493 | - | |
| 494 | -[example/terraform](example/terraform/main.tf) deploys the [example application](example) 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. | |
| 495 | -Its [README](example/README.md#deploy-it) gives the commands. | |
| 496 | -That Terraform code was written against the `scaleway/scaleway` provider v2.92 documentation and has never been applied; the [probe](probe/terraform/main.tf)'s, written the same way, has. | |
| 497 | - | |
| 498 | -Redeploy by running `scaleway-package` again, then `terraform apply`. | |
| 499 | -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. | |
| 500 | - | |
| 501 | -## Logs | |
| 502 | - | |
| 503 | -Scaleway sends what the function writes to stdout and stderr to [Cockpit](https://www.scaleway.com/en/docs/cockpit/), in the project's `Scaleway Logs` data source, about 2 seconds after it is written. | |
| 504 | -The runtime logs its own failures to stderr, as Monolog does with a `php://stderr` handler. | |
| 505 | -Without Monolog, Symfony's fallback logger writes to stderr too, but from the `error` level only: lower it as the [example](example/config/services.yaml) does. | |
| 506 | -Each line is one log entry: a stack trace spans one entry per line, and a line over 16 KiB is split into 16 KiB entries and cut after 64 KiB. | |
| 507 | -Every entry has the `debug` level, stderr ones included, except the continuations of a split line, whose level is `unknown`: filter on the `stream` field instead. | |
| 508 | -An entry looks like this, with the `resource_id` label holding the function's UUID: | |
| 509 | - | |
| 510 | -```json | |
| 511 | -{"message":"DEBUG - Invocation failed: RuntimeException: ... in /home/app/function/src/Kernel.php:12 source=user stream=stderr","stream":"stderr","resource_instance":"<namespace>-<function>-00001-deployment-<id>"} | |
| 512 | -``` | |
| 513 | - | |
| 514 | -In the console, open Cockpit's Grafana (`scw cockpit grafana get` prints its URL) and the `Serverless Functions Logs` dashboard, or Explore with the `Scaleway Logs` data source. | |
| 515 | - | |
| 516 | -From the command line, query Loki's HTTP API with a token that can only read logs: | |
| 517 | - | |
| 518 | -```sh | |
| 519 | -LOKI_URL=$(scw cockpit data-source list origin=scaleway types.0=logs -o json | jq -r '.[0].url') | |
| 520 | -FUNCTION_ID=$(scw function function list name=<function name> -o json | jq -r '.[0].id') | |
| 521 | -# The secret key is only shown at creation: keep it in memory rather than in a file that could get committed. | |
| 522 | -TOKEN=$(scw cockpit token create name=read-logs token-scopes.0=read_only_logs -o json) | |
| 523 | -LOKI_TOKEN=$(jq -r .secret_key <<< "$TOKEN") | |
| 524 | - | |
| 525 | -curl -sS -G "$LOKI_URL/loki/api/v1/query_range" -H "Authorization: Bearer $LOKI_TOKEN" \ | |
| 526 | - --data-urlencode "query={resource_id=\"$FUNCTION_ID\"} | json | stream=\"stderr\" | line_format \"{{.message}}\"" \ | |
| 527 | - --data-urlencode since=1h --data-urlencode limit=1000 \ | |
| 528 | - | jq -r '[.data.result[].values[]] | sort_by(.[0]) | .[][1]' | |
| 529 | - | |
| 530 | -scw cockpit token delete token-id=$(jq -r .id <<< "$TOKEN") | |
| 531 | -``` | |
| 532 | - | |
| 533 | -Token names are unique within a project: if a `read-logs` token was left behind, `token create` fails with `resource already exists`, so delete it first. | |
| 534 | -Without the `stream="stderr"` filter, the query also returns stdout and the platform's own lines (`Function Triggered: /`, `Function is now ready to serve requests!`). | |
| 535 | - | |
| 536 | -## Local development with the Emulator | |
| 537 | - | |
| 538 | -```sh | |
| 539 | -vendor/bin/scaleway-serve [127.0.0.1:8000] | |
| 540 | -``` | |
| 541 | - | |
| 542 | -The Emulator turns each HTTP request into an Event, calls your `handle()` and turns the Function Response back into the HTTP response. | |
| 543 | -`handle()` runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code. | |
| 544 | -It sets `APP_ENV=dev` unless started with an `APP_ENV`, as the deployed function defaults to `prod`. | |
| 545 | -A crashed process is replaced by a fresh one, as Scaleway starts a new instance. | |
| 546 | - | |
| 547 | -PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory. | |
| 548 | - | |
| 549 | -The Event and the context are built the way the platform builds them ([measured](docs/probe-results.md)): | |
| 550 | - | |
| 551 | -- the `httpMethod`, `queryStringParameters` (sorted by key, the last value of a repeated key winning, `[]` without query string) and other keys of the platform; | |
| 552 | -- header names in `Title-Case`, repeated headers joined with `, `, no `Host`; | |
| 553 | -- `X-Real-Ip`, `X-Envoy-External-Address`, `X-Request-Id` and `X-Forwarded-Proto: https` set whatever the client sends, the client's `X-Forwarded-For` kept in front of its address, its `X-Forwarded-Host` passed through; | |
| 554 | -- empty, multipart and non UTF-8 bodies base64-encoded with `isBase64Encoded: true`, text bodies without the flag. | |
| 555 | - | |
| 556 | -So the Requests are `https`, and their host is `localhost` unless you set `SCALEWAY_HOST`, as on the platform. | |
| 557 | - | |
| 558 | -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: | |
| 559 | - | |
| 560 | -```sh | |
| 561 | -curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"job": "cleanup"}' | |
| 562 | -``` | |
| 563 | - | |
| 564 | -Simulate a Command Invocation by starting the Emulator with `SCALEWAY_CRON_SECRET` set, and sending the [Command Invocation body](#command-invocations) the same way: | |
| 565 | - | |
| 566 | -```sh | |
| 567 | -SCALEWAY_CRON_SECRET=local-secret vendor/bin/scaleway-serve | |
| 568 | -curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}' | |
| 569 | -``` | |
| 570 | - | |
| 571 | -To run what gets deployed, install the zip the way Scaleway does, without the function's variables, then serve it in `prod`: | |
| 572 | - | |
| 573 | -```sh | |
| 574 | -vendor/bin/scaleway-package | |
| 575 | -unzip -q function.zip -d /tmp/function | |
| 576 | -composer install --working-dir=/tmp/function --no-dev | |
| 577 | -APP_ENV=prod APP_SECRET=local php /tmp/function/vendor/bin/scaleway-serve | |
| 578 | -``` | |
| 579 | - | |
| 580 | -The [example](example/README.md#run-it-locally)'s `e2e/deploy-locally.sh` does the same with the runtime of this repository. | |
| 581 | - | |
| 582 | -## Warm Processes | |
| 583 | - | |
| 584 | -The Application is built once per Warm Process and reused by the following Invocations, like with FrankenPHP's worker mode or RoadRunner ([ADR 0002](docs/adr/0002-reuse-application-across-invocations.md)). | |
| 585 | -Scaleway keeps processes warm: consecutive Invocations of an instance run in the same PHP process. | |
| 586 | - | |
| 587 | -Between Invocations, for a Kernel: | |
| 588 | - | |
| 589 | -- `terminate()` runs after each Invocation, and a failure in it is logged without changing the Function Response; | |
| 590 | -- the `services_resetter` resets the services tagged `kernel.reset` before the next request, as Symfony's Kernel does; | |
| 591 | -- uploaded files are deleted, and output buffers the Application left open are closed. | |
| 592 | - | |
| 593 | -Everything else survives, so your application must be safe for long-running execution: | |
| 594 | - | |
| 595 | -- do not keep per-request state in static properties or in services that do not implement `ResetInterface`; | |
| 596 | -- in-memory caches and collections grow across Invocations unless reset; | |
| 597 | -- connections (database, HTTP clients) may have been closed by the server while the process was idle; | |
| 598 | -- `exit()` or a fatal error ends the process, and the next Invocation pays a cold start. | |
| 599 | - | |
| 600 | -## Limitations and platform caveats | |
| 601 | - | |
| 602 | -### Requests and responses | |
| 603 | - | |
| 604 | -- **Superglobals**: `$_GET`, `$_POST`, `$_COOKIE`, `$_FILES` and the request entries of `$_SERVER` (`REQUEST_URI`, `HTTP_*`...) are not populated per Invocation. | |
| 605 | - Read the `Request` object instead; `Request::createFromGlobals()` does not describe the Invocation. | |
| 606 | -- **Output**: only the returned `Response` reaches the client. | |
| 607 | - `echo` outside the Response, `header()` and `http_response_code()` do not: Scaleway does not put stdout in the response body. | |
| 608 | -- **Query strings**: the Event carries `queryStringParameters` as a map, so a repeated key such as `a=1&a=2`, or `tags[]=a&tags[]=b`, reaches the Application with its last value only, and the keys arrive sorted, not in the order the client sent them. | |
| 609 | - Keys are then parsed like PHP does, so `a.b` becomes `a_b` and `a[b]` nests. | |
| 610 | -- **Form bodies**: `application/x-www-form-urlencoded` bodies are parsed for `POST`, `PUT`, `DELETE`, `PATCH` and `QUERY`, `multipart/form-data` only for `POST`, as PHP does. | |
| 611 | - Uploaded files are `UploadedFile` objects in test mode: `move()` works, `is_uploaded_file()` does not. | |
| 612 | -- **Cookies**: request cookie names are taken verbatim: unlike PHP's `$_COOKIE`, dots and spaces are not turned into underscores and `a[b]` does not nest. | |
| 613 | -- **Streaming**: `StreamedResponse` and `BinaryFileResponse` are buffered into one Function Response; Server-Sent Events and long downloads are not possible. | |
| 614 | - Bodies that are not valid UTF-8 are sent base64-encoded, and decoded by the platform. | |
| 615 | -- **PSR-15 responses** go through Symfony's `Response`, which adds `Cache-Control: no-cache, private` and `Date` when they are missing. | |
| 616 | -- **HEAD requests**: only FrameworkBundle's `ResponseListener` strips the body of a `HEAD` response, but the platform sends none anyway. | |
| 617 | -- **Request size**: Scaleway rejects request bodies over 6 MiB with a `413`, before they reach the function. | |
| 618 | -- **CORS**: Scaleway adds `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: Content-Type` to every response, whatever the Application sends. | |
| 619 | - 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. | |
| 620 | -- **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 a `500` whose body is `Error while executing function`. | |
| 621 | - | |
| 622 | -### Client IP and trusted proxies | |
| 623 | - | |
| 624 | -The runtime trusts no proxy, as clients can forge most forwarding headers on Scaleway ([ADR 0007](docs/adr/0007-trust-only-headers-the-platform-overwrites.md)): | |
| 625 | - | |
| 626 | -| Request | From | Why | | |
| 627 | -| --- | --- | --- | | |
| 628 | -| `getClientIp()` | `X-Real-Ip`, `127.0.0.1` without it (CRON Invocations) | Set by the platform, whatever the client sends | | |
| 629 | -| `isSecure()`, `getScheme()`, port | `X-Forwarded-Proto`, the scheme's default port | Set by the platform (`https`, `http` for CRON Invocations) | | |
| 630 | -| `getHost()` | The [`host` option](#host) | No `Host` header reaches the function | | |
| 631 | - | |
| 632 | -`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. | |
| 633 | -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. | |
| 634 | - | |
| 635 | -> [!CAUTION] | |
| 636 | -> Do not configure `framework.trusted_proxies`: the client is already resolved, and trusting `REMOTE_ADDR` or private ranges would make Symfony trust those forgeable headers again. | |
| 637 | -> Trusted proxies your application configures still apply, as usual. | |
| 638 | - | |
| 639 | -### Composer at deploy time | |
| 640 | - | |
| 641 | -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/`. | |
| 642 | -Every locked package must therefore be downloadable from Scaleway, and the function's environment variables are not available to Composer scripts. | |
| 643 | -The lock must also install on the function's runtime: set `config.platform.php` in `composer.json` to its PHP version (`8.4` for `php84`, `8.5` for `php85`) so that `composer update` resolves for it. | |
| 644 | -`config.platform` only steers Composer's resolution: run the [compatibility check](#compatibility-check), or package with `--runtime`, to check the lock against what Scaleway provides. | |
| 645 | -A failing install or script does not fail the deployment, and Scaleway serves the new code anyway, never the previous version ([measured](docs/probe-results.md#failed-scripts-and-installs)): | |
| 646 | - | |
| 647 | -- a failing script runs once `vendor/` and its autoloader are complete, so the new code works, without what the script should have done (a warmed cache, generated files...); | |
| 648 | -- a failing install, from a package Scaleway cannot download or a platform requirement its runtime does not meet, leaves no `vendor/` at all: every Invocation answers a `500`, the first one of each instance logging `Failed to open stream` for `vendor/autoload.php` on stdout, the next ones `Class "JDecool\ScalewayRuntime\Handler" not found` on stderr. | |
| 649 | - | |
| 650 | -Neither shows anywhere: the function is `ready`, its `error_message` and `build_message` stay empty, and Composer's output reaches neither Cockpit nor `scw`. | |
| 651 | -So after each deploy, call a route that should answer a `200`, and check the function's [logs](#logs) if it does not: | |
| 652 | - | |
| 653 | -```sh | |
| 654 | -curl -sS -o /dev/null -w '%{http_code}\n' "https://$(scw function function list name=<function name> -o json | jq -r '.[0].domain_name')/<route>" | |
| 655 | -``` | |
| 656 | - | |
| 657 | -Keep deploy-time scripts to what the application can do without, as a cache warmup the first Invocation redoes, and run whatever it needs at runtime instead. | |
| 658 | - | |
| 659 | -### Windows | |
| 660 | - | |
| 661 | -`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. | |
| 662 | -Without the `pcntl` extension, stopping the Emulator with `kill` may leave its PHP processes running. | |
| 53 | +1. [Configuration](docs/configuration.md): the function handler, the Front Controller, environment variables and the host. | |
| 54 | +2. [Supported Applications](docs/applications.md): what a Front Controller may return, from a Kernel to a raw callable. | |
| 55 | +3. [Local development with the Emulator](docs/local-development.md): running the function on your machine. | |
| 56 | +4. [Packaging](docs/packaging.md) and [Deployment](docs/deployment.md): shipping it to Scaleway, after a [compatibility check](docs/compatibility-check.md). | |
| 57 | +5. [Logs](docs/logs.md): seeing what the function did. | |
| 663 | 58 | |
| 664 | 59 | ## Contributing |
| 665 | 60 | |
| 666 | -```sh | |
| 667 | -composer install | |
| 668 | -composer check # PHP-CS-Fixer (dry run), PHPStan (max level) and PHPUnit | |
| 669 | -composer cs-fix # applies the coding style | |
| 670 | -``` | |
| 671 | - | |
| 672 | -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`. | |
| 673 | -It also runs the [end-to-end scenarios](example/e2e/run.sh) of the [example application](example) through the Emulator, in dev and on its zip installed like Scaleway does ([e2e/deploy-locally.sh](example/e2e/deploy-locally.sh)). | |
| 674 | -The example installs the runtime of the checkout with `composer link-runtime`, see its [README](example/README.md#run-it-locally). | |
| 675 | -A weekly workflow measures the Function Runtimes on Scaleway again, and opens a pull request when the catalogue changes, see [docs/probe-results.md](docs/probe-results.md#function-runtime-catalogue). | |
| 676 | - | |
| 677 | -The repository holds: | |
| 678 | - | |
| 679 | -- `src/`, `bin/`, `resources/`: the package; | |
| 680 | -- `tests/`: PHPUnit tests, packaging included; | |
| 681 | -- `example/`: a demo Symfony application requiring the package, with Terraform code to deploy it; | |
| 682 | -- `probe/`: a dependency-free function measuring the platform facts, its [results](docs/probe-results.md), and the generator of the [Function Runtime Catalogue](docs/probe-results.md#function-runtime-catalogue); | |
| 683 | -- `docs/`: the [ADRs](docs/adr). | |
| 61 | +See [CONTRIBUTING.md](CONTRIBUTING.md). | |
| 684 | 62 | |
| 685 | 63 | ## License |
| 686 | 64 | |
| @@ -6,35 +6,18 @@ Scaleway calls a PHP function `handle($event, $context)` for each Invocation. | |||
| 6 | 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. | 6 | 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. |
| 7 | It also ships the tools to package the function and to run it locally. | 7 | It also ships the tools to package the function and to run it locally. |
| 8 | 8 | ||
| 9 | -Vocabulary (Invocation, Event, Warm Process...) is defined in [GLOSSARY.md](GLOSSARY.md), design decisions in [docs/adr](docs/adr). | 9 | +Vocabulary (Invocation, Event, Warm Process...) is defined in [GLOSSARY.md](GLOSSARY.md), design decisions in [docs/adr](docs/adr/README.md). |
| 10 | 10 | ||
| 11 | > [!IMPORTANT] | 11 | > [!IMPORTANT] |
| 12 | > The platform facts the runtime relies on were measured on Scaleway with the [probe](probe), see [docs/probe-results.md](docs/probe-results.md). | 12 | > The platform facts the runtime relies on were measured on Scaleway with the [probe](probe), see [docs/probe-results.md](docs/probe-results.md). |
| 13 | > The [example application](example) runs on Scaleway: its scenarios, CRON triggers and Command Invocations were checked on a deployment. | 13 | > The [example application](example) runs on Scaleway: its scenarios, CRON triggers and Command Invocations were checked on a deployment. |
| 14 | 14 | ||
| 15 | -## Contents | ||
| 16 | - | ||
| 17 | -- [Requirements](#requirements) | ||
| 18 | -- [Installation](#installation) | ||
| 19 | -- [Configuration](#configuration) | ||
| 20 | -- [Supported Applications](#supported-applications) | ||
| 21 | -- [Static Files](#static-files) | ||
| 22 | -- [CRON triggers and Command Invocations](#cron-triggers-and-command-invocations) | ||
| 23 | -- [Compatibility check](#compatibility-check) | ||
| 24 | -- [Packaging](#packaging) | ||
| 25 | -- [Deployment](#deployment) | ||
| 26 | -- [Logs](#logs) | ||
| 27 | -- [Local development with the Emulator](#local-development-with-the-emulator) | ||
| 28 | -- [Warm Processes](#warm-processes) | ||
| 29 | -- [Limitations and platform caveats](#limitations-and-platform-caveats) | ||
| 30 | -- [Contributing](#contributing) | ||
| 31 | - | ||
| 32 | ## Requirements | 15 | ## Requirements |
| 33 | 16 | ||
| 34 | - The Scaleway PHP runtimes `php84` or `php85` (PHP 8.4 or later). | 17 | - The Scaleway PHP runtimes `php84` or `php85` (PHP 8.4 or later). |
| 35 | - Symfony 7.4 or 8.x components (`symfony/runtime`, `symfony/http-kernel`, `symfony/http-foundation`). | 18 | - Symfony 7.4 or 8.x components (`symfony/runtime`, `symfony/http-kernel`, `symfony/http-foundation`). |
| 36 | - To build the deployment zip: the `zip` PHP extension. | 19 | - To build the deployment zip: the `zip` PHP extension. |
| 37 | -- macOS or Linux for the packaging and Emulator tools (see [Windows](#windows)). | 20 | +- macOS or Linux for the packaging and Emulator tools (see [Windows](docs/local-development.md#windows)). |
| 38 | 21 | ||
| 39 | ## Installation | 22 | ## Installation |
| 40 | 23 | ||
| @@ -63,624 +46,19 @@ Your Front Controller stays as it is, `require_once dirname(__DIR__).'/vendor/au | |||
| 63 | 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. | 46 | 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. |
| 64 | 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. | 47 | 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. |
| 65 | 48 | ||
| 66 | -## Configuration | 49 | +## Documentation |
| 67 | - | ||
| 68 | -### Function handler | ||
| 69 | - | ||
| 70 | -Set the handler of the Scaleway function to `handler.handle`. | ||
| 71 | - | ||
| 72 | -### Front Controller | ||
| 73 | - | ||
| 74 | -The Front Controller defaults to `public/index.php`, relative to the project dir. | ||
| 75 | -Choose another one with the `front_controller` runtime option, in `composer.json`: | ||
| 76 | - | ||
| 77 | -```json | ||
| 78 | -{ | ||
| 79 | - "extra": { | ||
| 80 | - "runtime": { | ||
| 81 | - "front_controller": "public/api.php" | ||
| 82 | - } | ||
| 83 | - } | ||
| 84 | -} | ||
| 85 | -``` | ||
| 86 | - | ||
| 87 | -Or with the `APP_RUNTIME_OPTIONS` environment variable, a JSON object that wins over `extra.runtime`: | ||
| 88 | - | ||
| 89 | -```sh | ||
| 90 | -APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | ||
| 91 | -``` | ||
| 92 | - | ||
| 93 | -The other `SymfonyRuntime` options (`project_dir`, `env_var_name`, `dotenv_path`...) work as usual. | ||
| 94 | -`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`. | ||
| 95 | - | ||
| 96 | -### Environment variables | ||
| 97 | - | ||
| 98 | -Set these on the function, in production: | ||
| 99 | - | ||
| 100 | -| Variable | Kind | Why | | ||
| 101 | -| --- | --- | --- | | ||
| 102 | -| `APP_SECRET` | Secret | Symfony's `kernel.secret`, used to sign URLs, cookies and CSRF tokens. | | ||
| 103 | -| `SCALEWAY_HOST` | Plain | The public host of the function, for absolute URLs, see [Host](#host). | | ||
| 104 | -| `SCALEWAY_CRON_SECRET` | Secret | Only to run console commands from CRON triggers, see [Command Invocations](#command-invocations). | | ||
| 105 | -| `APP_ENV` | Plain | Only to run another env than `prod`, see below. | | ||
| 106 | - | ||
| 107 | -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. | ||
| 108 | -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](docs/adr/0006-default-to-the-prod-env.md)). | ||
| 109 | -Only an `APP_ENV` variable of the function, or the `env` runtime option, picks another env. | ||
| 110 | -`APP_DEBUG` follows: off in `prod`, unless set by the function's environment or a `.env` file. | ||
| 111 | -The Emulator runs `dev` instead, unless it is started with an `APP_ENV`. | ||
| 112 | - | ||
| 113 | -For every other variable, real environment variables win over `.env` files, as usual with Symfony's Dotenv. | ||
| 114 | -`.env.local`, `.env.local.php` and `.env.*.local` are never shipped. | ||
| 115 | - | ||
| 116 | -### Host | ||
| 117 | - | ||
| 118 | -No `Host` header reaches the function, so the runtime cannot know the domain it is called on. | ||
| 119 | -Every Request gets the host of the `host` runtime option, which defaults to the `SCALEWAY_HOST` environment variable, then to `localhost`: | ||
| 120 | - | ||
| 121 | -```sh | ||
| 122 | -SCALEWAY_HOST=api.example.com | ||
| 123 | -``` | ||
| 124 | - | ||
| 125 | -The scheme comes from the platform's `X-Forwarded-Proto` (`https` for HTTP calls), the port is the scheme's default. | ||
| 126 | -Absolute URLs (`UrlGeneratorInterface::ABSOLUTE_URL`, signed URLs, redirects built from the Request) are only right once the host is set. | ||
| 127 | -Set it to the function's domain (its `domain_name` on Scaleway) or to its custom domain. | ||
| 128 | -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. | ||
| 129 | -An application configuring `framework.trusted_hosts` answers every Request with a 400 until the host is set to one of its trusted hosts. | ||
| 130 | -Both were [measured on Scaleway](docs/probe-results.md#absolute-urls), forged `X-Forwarded-Host` and `Forwarded` headers never changing the host. | ||
| 131 | - | ||
| 132 | -### Cache and writable directories | ||
| 133 | - | ||
| 134 | -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. | ||
| 135 | -To pay it at deploy time instead, warm the cache from a Composer script, which Scaleway runs after installing the dependencies: | ||
| 136 | - | ||
| 137 | -```json | ||
| 138 | -{ | ||
| 139 | - "scripts": { | ||
| 140 | - "post-install-cmd": ["@php bin/console cache:warmup --env=prod"] | ||
| 141 | - } | ||
| 142 | -} | ||
| 143 | -``` | ||
| 144 | - | ||
| 145 | -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. | ||
| 146 | - | ||
| 147 | -> [!WARNING] | ||
| 148 | -> Symfony Flex's `auto-scripts` also run at deploy time, with the `APP_ENV` of the shipped `.env`, usually `dev`: `cache:clear` then fails silently, its dev bundles not being installed with `--no-dev`. | ||
| 149 | -> Make them env-explicit (`"cache:clear --env=prod": "symfony-cmd"`), or remove `cache:clear` from them and warm the cache as above. | ||
| 150 | - | ||
| 151 | -When the project's `var/` directory (or the project dir, without `var/`) is not writable, the runtime sets, unless your application already did: | ||
| 152 | - | ||
| 153 | -- `APP_CACHE_DIR` to `<temp dir>/cache` and `APP_LOG_DIR` to `<temp dir>/log`; | ||
| 154 | -- `APP_BUILD_DIR` to `var/cache`, only when `var/cache/<env>` holds a container warmed before, so that it is used as is. | ||
| 155 | - | ||
| 156 | -Kernels using `MicroKernelTrait` read these variables. | ||
| 157 | -Other Kernels must override `getCacheDir()`, `getBuildDir()` and `getLogDir()` themselves. | ||
| 158 | -Logs written to files are lost with the instance: send them to `php://stderr` instead, which the runtime also uses for its own errors. | ||
| 159 | - | ||
| 160 | -### Errors | ||
| 161 | - | ||
| 162 | -An exception escaping the Application (a Kernel failing to boot, an unsupported Front Controller...) is logged to stderr ([Logs](#logs)) and answered with a 500. | ||
| 163 | -Its body is `Internal Server Error`, or the full exception when `APP_DEBUG` is true. | ||
| 164 | -A Kernel that failed to boot is built again from scratch on the next Invocation. | ||
| 165 | - | ||
| 166 | -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. | ||
| 167 | -Outside a web SAPI, FrameworkBundle would pick its CLI error renderer instead, which dumps the exception even in `prod`. | ||
| 168 | - | ||
| 169 | -## Supported Applications | ||
| 170 | - | ||
| 171 | -The Front Controller returns a closure, as with any Symfony Runtime. | ||
| 172 | -The type of what that closure returns, the Application, decides how Invocations are served. | ||
| 173 | - | ||
| 174 | -### HttpKernel | ||
| 175 | - | ||
| 176 | -The usual Symfony Front Controller: | ||
| 177 | - | ||
| 178 | -```php | ||
| 179 | -<?php // public/index.php | ||
| 180 | - | ||
| 181 | -use App\Kernel; | ||
| 182 | - | ||
| 183 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 184 | - | ||
| 185 | -return function (array $context) { | ||
| 186 | - return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); | ||
| 187 | -}; | ||
| 188 | -``` | ||
| 189 | - | ||
| 190 | -The Kernel is booted once per Warm Process and serves every Invocation, see [Warm Processes](#warm-processes). | ||
| 191 | -Any `HttpKernelInterface` works; a `KernelInterface` also runs [Command Invocations](#command-invocations). | ||
| 192 | - | ||
| 193 | -### Response | ||
| 194 | - | ||
| 195 | -A closure returning a `Response` is called again for every Invocation, without any Kernel. | ||
| 196 | -A `Request` argument receives the Invocation's Request: | ||
| 197 | - | ||
| 198 | -```php | ||
| 199 | -<?php // public/hello.php | ||
| 200 | - | ||
| 201 | -use Symfony\Component\HttpFoundation\JsonResponse; | ||
| 202 | -use Symfony\Component\HttpFoundation\Request; | ||
| 203 | - | ||
| 204 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 205 | - | ||
| 206 | -return static function (Request $request): JsonResponse { | ||
| 207 | - return new JsonResponse(['message' => sprintf('Hello %s!', $request->query->get('name', 'World'))]); | ||
| 208 | -}; | ||
| 209 | -``` | ||
| 210 | - | ||
| 211 | -Keep the closure cheap, as it runs on every Invocation, and make it return a `Response` every time. | ||
| 212 | -See [ADR 0004](docs/adr/0004-call-response-front-controllers-per-invocation.md). | ||
| 213 | - | ||
| 214 | -### PSR-15 request handler | ||
| 215 | - | ||
| 216 | -A closure returning a `Psr\Http\Server\RequestHandlerInterface` builds it once per Warm Process. | ||
| 217 | -It needs two more packages: | ||
| 218 | - | ||
| 219 | -```sh | ||
| 220 | -composer require symfony/psr-http-message-bridge nyholm/psr7 | ||
| 221 | -``` | ||
| 222 | - | ||
| 223 | -```php | ||
| 224 | -<?php // public/index.php | ||
| 225 | - | ||
| 226 | -use App\ApiHandler; | ||
| 227 | -use Psr\Http\Server\RequestHandlerInterface; | ||
| 228 | - | ||
| 229 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 230 | - | ||
| 231 | -return static fn (): RequestHandlerInterface => new ApiHandler(); | ||
| 232 | -``` | ||
| 233 | - | ||
| 234 | -The PSR-7 request carries the client address, scheme, host and port the runtime resolved (see [Client IP and trusted proxies](#client-ip-and-trusted-proxies)), in its URI and in the `REMOTE_ADDR`, `HTTPS`, `HTTP_HOST` and `SERVER_PORT` server params. | ||
| 235 | -A handler implementing `Symfony\Contracts\Service\ResetInterface` is reset before every Invocation but the first. | ||
| 236 | -A malformed host is answered with a 400 before reaching the handler. | ||
| 237 | - | ||
| 238 | -### Console Application or Command | ||
| 239 | - | ||
| 240 | -A Front Controller returning a Console `Application` or a `Command` only serves [Command Invocations](#command-invocations), and answers every other Invocation with a 403. | ||
| 241 | -Symfony's `bin/console` is such a Front Controller: | ||
| 242 | - | ||
| 243 | -```sh | ||
| 244 | -APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | ||
| 245 | -``` | ||
| 246 | - | ||
| 247 | -A single `Command` runs whatever `command` the Command Invocation names: | ||
| 248 | - | ||
| 249 | -```php | ||
| 250 | -<?php // bin/cleanup.php | ||
| 251 | - | ||
| 252 | -use Symfony\Component\Console\Command\Command; | ||
| 253 | -use Symfony\Component\Console\Input\InputInterface; | ||
| 254 | -use Symfony\Component\Console\Output\OutputInterface; | ||
| 255 | - | ||
| 256 | -require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 257 | - | ||
| 258 | -return static fn (): Command => (new Command('app:cleanup')) | ||
| 259 | - ->setCode(static function (InputInterface $input, OutputInterface $output): int { | ||
| 260 | - $output->writeln('Cleaned up'); | ||
| 261 | - | ||
| 262 | - return Command::SUCCESS; | ||
| 263 | - }); | ||
| 264 | -``` | ||
| 265 | - | ||
| 266 | -This needs `symfony/console`, and `symfony/framework-bundle` for a `Symfony\Bundle\FrameworkBundle\Console\Application`. | ||
| 267 | - | ||
| 268 | -### Raw callable | ||
| 269 | - | ||
| 270 | -A closure returning another `Closure` talks to Scaleway without any translation. | ||
| 271 | -The inner closure is built once per Warm Process and receives every Event and context as they are, CRON Invocations included: | ||
| 272 | - | ||
| 273 | -```php | ||
| 274 | -<?php // public/raw.php | ||
| 275 | - | ||
| 276 | -return static fn (): Closure => static fn (array $event, mixed $context): array => [ | ||
| 277 | - 'statusCode' => 200, | ||
| 278 | - 'headers' => ['Content-Type' => 'text/plain'], | ||
| 279 | - 'body' => 'Hello from '.($event['path'] ?? '/'), | ||
| 280 | -]; | ||
| 281 | -``` | ||
| 282 | - | ||
| 283 | -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`. | ||
| 284 | -Other keys are dropped, and any other return value fails the Invocation with a 500. | ||
| 285 | -Command Invocations are not routed: the raw callable gets their Event like any other. | ||
| 286 | -An invokable object is not taken for a raw callable; return `$object(...)` to make it one. | ||
| 287 | - | ||
| 288 | -## Static Files | ||
| 289 | - | ||
| 290 | -The runtime serves the files of `public/` itself, before building the Application: stylesheets, JavaScript, images, fonts, `favicon.ico`, `robots.txt`, and what AssetMapper or Webpack Encore compile there. | ||
| 291 | -Such an Invocation pays no Kernel boot, and is answered even when the Application fails to build ([ADR 0009](docs/adr/0009-serve-static-files-from-the-function.md)). | ||
| 292 | - | ||
| 293 | -A file is served when: | ||
| 294 | - | ||
| 295 | -- the request is a `GET` or a `HEAD`; | ||
| 296 | -- the path names a regular file under `<project_dir>/public`, a symbolic link leading out of it excluded; | ||
| 297 | -- no segment of the path starts with a dot (`..`, `.env`, `.htaccess`), but for a leading `/.well-known/`; | ||
| 298 | -- its extension is not `.php`. | ||
| 299 | - | ||
| 300 | -Every other request goes to the Application, directories included: there is no index file nor directory listing. | ||
| 301 | - | ||
| 302 | -> [!IMPORTANT] | ||
| 303 | -> A file wins over a route of the same path. | ||
| 304 | -> An application answering `/robots.txt` from a controller while shipping `public/robots.txt` gets the file: delete the file to keep the route. | ||
| 305 | - | ||
| 306 | -### Responses | ||
| 307 | - | ||
| 308 | -- The `Content-Type` comes from the extension, `application/octet-stream` for an unknown one, without charset. | ||
| 309 | -- Each response carries `X-Content-Type-Options: nosniff`, and an `ETag` of the bytes it sends: a matching `If-None-Match` gets a `304` without body. | ||
| 310 | -- `Cache-Control` is `public, max-age=0, must-revalidate`: browsers keep the file but check it on each use. | ||
| 311 | -- It is `public, max-age=31536000, immutable` for a file whose name changes with its content: one that a `manifest.json` in its directory, or in one above, maps from another name. | ||
| 312 | - AssetMapper's `public/assets/manifest.json` and Webpack Encore's `public/build/manifest.json` (with versioning) are such manifests. | ||
| 313 | - Names alone are not trusted, as `font-awesome.css` would look as digested as `app-mH7q4W_.css`. | ||
| 314 | -- `Range` requests get the whole file with a `200`. | ||
| 315 | - | ||
| 316 | -No CDN stands in front of a function: every request for a Static File is an Invocation, billed and possibly paying a cold start. | ||
| 317 | -Long-lived caching of digested files is what spares most of them. | ||
| 318 | - | ||
| 319 | -### Compression | ||
| 320 | - | ||
| 321 | -A file is sent compressed when the client accepts it, in this order: | ||
| 322 | - | ||
| 323 | -1. a precompressed variant shipped next to it, `app.css.br`, then `app.css.zst`, then `app.css.gz`, written by any build step; | ||
| 324 | -2. otherwise, when the `static_compression` runtime option is set, the file compressed by the runtime. | ||
| 325 | - | ||
| 326 | -```json | ||
| 327 | -{ | ||
| 328 | - "extra": { | ||
| 329 | - "runtime": { | ||
| 330 | - "static_compression": "gzip" | ||
| 331 | - } | ||
| 332 | - } | ||
| 333 | -} | ||
| 334 | -``` | ||
| 335 | - | ||
| 336 | -`static_compression` is `false` by default, `"gzip"`, `"zstd"` or `"br"`, each needing its extension (`zlib`, `zstd`, `brotli`): any other value, or one whose extension is not loaded, answers every Invocation with a 500 until fixed. | ||
| 337 | -The Scaleway `php85` runtime loads `zlib` and `zstd` but not `brotli`: use `"zstd"` or `"gzip"` there, and ship `.br` variants built beforehand for brotli. | ||
| 338 | -The runtime only compresses textual files (`text/*`, JavaScript, JSON, XML, SVG, WebAssembly) of at least 1 KiB, and keeps the results in memory for the Warm Process, up to 32 MiB. | ||
| 339 | - | ||
| 340 | -The order of preference is the runtime's: only a `q=0` in `Accept-Encoding` refuses an encoding. | ||
| 341 | -Compressed responses carry `Content-Encoding`, an `ETag` of their own and `Vary: Accept-Encoding`. | ||
| 342 | -A request for `app.css.gz` itself gets that file, as any other. | ||
| 343 | - | ||
| 344 | -### Limits | ||
| 345 | - | ||
| 346 | -- A Static File must fit in one Function Response, base64-encoded when it is binary, which takes a third more. | ||
| 347 | - Scaleway enforces no limit, but responses of 10 MiB and more intermittently fail with a `504` after 60 seconds ([measured](docs/probe-results.md#size-and-encodings)). | ||
| 348 | - The runtime therefore refuses Static Files over 6 MiB in a Function Response: it answers a 500 and logs the file, and `scaleway-package` warns about such files. | ||
| 349 | -- A file written at runtime under `public/`, such as an upload, is only served by the instance that wrote it, each instance having its own disk. | ||
| 350 | -- Store uploads, large files and busy sites' assets on Object Storage, behind Edge Services or not, and point `framework.assets.base_urls` to it. | ||
| 351 | -- `assets:install` boots the Kernel: at deploy time, run it from a `post-install-cmd` with an explicit env, `@php bin/console assets:install public --env=prod`, for the same reasons as [`cache:warmup`](#cache-and-writable-directories). | ||
| 352 | - | ||
| 353 | -## CRON triggers and Command Invocations | ||
| 354 | 50 | ||
| 355 | -### CRON triggers | 51 | +The [documentation index](docs/README.md) lists every guide. The usual path: |
| 356 | 52 | ||
| 357 | -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`). | 53 | +1. [Configuration](docs/configuration.md): the function handler, the Front Controller, environment variables and the host. |
| 358 | -With a Kernel, handle it like any route: | 54 | +2. [Supported Applications](docs/applications.md): what a Front Controller may return, from a Kernel to a raw callable. |
| 359 | - | 55 | +3. [Local development with the Emulator](docs/local-development.md): running the function on your machine. |
| 360 | -```php | 56 | +4. [Packaging](docs/packaging.md) and [Deployment](docs/deployment.md): shipping it to Scaleway, after a [compatibility check](docs/compatibility-check.md). |
| 361 | -#[Route('/', methods: ['POST'])] | 57 | +5. [Logs](docs/logs.md): seeing what the function did. |
| 362 | -public function cron(Request $request): Response | ||
| 363 | -{ | ||
| 364 | - $args = $request->toArray(); // the trigger's arguments | ||
| 365 | - // ... | ||
| 366 | -} | ||
| 367 | -``` | ||
| 368 | - | ||
| 369 | -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. | ||
| 370 | - | ||
| 371 | -### Command Invocations | ||
| 372 | - | ||
| 373 | -A CRON trigger may run a console command instead, through the Console Application of the same Kernel. | ||
| 374 | - | ||
| 375 | -1. Generate a random secret, for instance with `openssl rand -hex 32`. | ||
| 376 | -2. Set it as the `SCALEWAY_CRON_SECRET` secret environment variable of the function. | ||
| 377 | -3. Give the CRON trigger these arguments: | ||
| 378 | - | ||
| 379 | -```json | ||
| 380 | -{"command": "app:sync", "args": {"source": "s3", "--force": true, "--tag": ["a", "b"]}, "secret": "<SCALEWAY_CRON_SECRET>"} | ||
| 381 | -``` | ||
| 382 | - | ||
| 383 | -`args` is optional, and maps argument names, and option names with their dashes, to values, as Symfony's `ArrayInput` does. | ||
| 384 | -The command runs without interaction: questions get their default answer. | ||
| 385 | -Services are reset around each command, so it shares no state with the Invocations before and after it. | ||
| 386 | - | ||
| 387 | -| Outcome | Function Response | | ||
| 388 | -| --- | --- | | ||
| 389 | -| Exit code 0 | 200, the command output as plain text body | | ||
| 390 | -| Any other exit code | 500, the command output as plain text body, also logged to stderr | | ||
| 391 | -| `args` not a JSON object | 500 | | ||
| 392 | -| 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 | | ||
| 393 | - | ||
| 394 | -Nothing shows the Function Response of a CRON Invocation, and a failed one is not retried: the [logs](#logs) are where the outcome of a command shows up, so log what it does ([measured](docs/probe-results.md#cron-invocations)). | ||
| 395 | - | ||
| 396 | -### Security model | ||
| 397 | - | ||
| 398 | -A body only becomes a Command Invocation when both hold: | ||
| 399 | - | ||
| 400 | -- the Event carries neither `X-Real-Ip` nor `X-Envoy-External-Address`, which the platform sets on every HTTP call, overwriting what the client sends, and which CRON Events lack; | ||
| 401 | -- its `secret` matches `SCALEWAY_CRON_SECRET`, compared in constant time. | ||
| 402 | - | ||
| 403 | -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). | ||
| 404 | -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. | ||
| 405 | -The first check relies on undocumented platform behaviour, which is why the secret stays required. | ||
| 406 | - | ||
| 407 | -Keep in mind that: | ||
| 408 | - | ||
| 409 | -- 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; | ||
| 410 | -- rotating it means updating the variable and every CRON trigger together. | ||
| 411 | - | ||
| 412 | -See [ADR 0005](docs/adr/0005-authenticate-command-invocations-with-a-shared-secret.md) for the alternatives considered. | ||
| 413 | - | ||
| 414 | -## Compatibility check | ||
| 415 | - | ||
| 416 | -```sh | ||
| 417 | -vendor/bin/scaleway-doctor --runtime=php84 | ||
| 418 | -``` | ||
| 419 | - | ||
| 420 | -A Platform Requirement (`php` or `ext-*`) the Function Runtime does not meet makes Scaleway's `composer install` fail at deploy time, without failing the deployment: every Invocation then answers a `500` (see [Composer at deploy time](#composer-at-deploy-time)). | ||
| 421 | -`scaleway-doctor` checks, before you deploy, the Platform Requirements that install checks, against the Function Runtime the function declares, named by `--runtime` (`php84` or `php85`). | ||
| 422 | -It never guesses it from your local PHP. | ||
| 423 | -It reads `composer.json` and `composer.lock`, needs neither Scaleway credentials nor network access, and refuses a stale lock as [`scaleway-package`](#packaging) does. | ||
| 424 | - | ||
| 425 | -It checks what `composer install --no-dev` checks on Scaleway: | ||
| 426 | - | ||
| 427 | -- the root requirements the lock records, and those of every locked production package, development ones excluded; | ||
| 428 | -- each one met by the Function Runtime, or by a `provide` or `replace` of the application or of a locked package; | ||
| 429 | -- constraints evaluated by Composer's own engine, against the PHP and extension versions Composer would see on Scaleway. | ||
| 430 | - | ||
| 431 | -Each requirement is: | ||
| 432 | - | ||
| 433 | -- **satisfied**, when the measured version matches; | ||
| 434 | -- **incompatible**, when the extension is not loaded, or the measured version of PHP or of the extension does not match; | ||
| 435 | -- **unknown**, for the platform packages the catalogue does not measure, as `lib-icu` or `php-64bit`. | ||
| 436 | - | ||
| 437 | -Composer's own APIs (`composer`, `composer-plugin-api`, `composer-runtime-api`) are not checked: Scaleway installs with Composer 2. | ||
| 438 | - | ||
| 439 | -The report, on stderr, lists the incompatible and unknown requirements, with what declares them and what the Function Runtime provides: | ||
| 440 | - | ||
| 441 | -```text | ||
| 442 | -INCOMPATIBLE ext-foo * required by acme/bar v2.1.0 php84: not loaded (measured 2026-11-22) | ||
| 443 | - php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions. | ||
| 444 | -UNKNOWN lib-icu >=72 required by symfony/intl v8.0.3 not in the Function Runtime Catalogue | ||
| 445 | - | ||
| 446 | -48 satisfied, 1 unknown, 1 incompatible on php84 (measured 2026-11-22) | ||
| 447 | -This covers declared Platform Requirements only, not whether the application runs. | ||
| 448 | -``` | ||
| 449 | - | ||
| 450 | -It exits with `0` when every requirement is satisfied or only unknowns remain, and with `1` on an incompatible requirement or an invalid input. | ||
| 451 | -For an incompatible requirement, it names the other Function Runtimes that meet it, if any. | ||
| 452 | -Otherwise, custom extensions or versions need [Serverless Containers](https://www.scaleway.com/en/serverless-containers/), which this package does not target. | ||
| 453 | - | ||
| 454 | -What each Function Runtime provides comes from the Function Runtime Catalogue shipped with the package, [resources/function-runtimes.php](resources/function-runtimes.php). | ||
| 455 | -It holds measurements only, made on Scaleway with the [probe](probe), each a complete inventory: an extension it does not list is not loaded. | ||
| 456 | -A measurement describes the Function Runtime on its date, which the report shows, not a guarantee that Scaleway keeps the same versions. | ||
| 457 | -The measured PHP patch version is authoritative: if Scaleway has upgraded PHP since, update the package for a newer catalogue. | ||
| 458 | - | ||
| 459 | -The [Emulator](#local-development-with-the-emulator) runs on your local PHP, which may load extensions or versions the Function Runtime lacks: an application working locally can still fail to install on Scaleway, which is what this check catches. | ||
| 460 | -A successful check covers declared Platform Requirements only: an extension used without being required is not checked, and calling a route after the deployment, as [Composer at deploy time](#composer-at-deploy-time) shows, remains the proof that it works. | ||
| 461 | - | ||
| 462 | -## Packaging | ||
| 463 | - | ||
| 464 | -```sh | ||
| 465 | -vendor/bin/scaleway-package [--runtime=php84] [function.zip] | ||
| 466 | -``` | ||
| 467 | - | ||
| 468 | -With `--runtime`, it first runs the [compatibility check](#compatibility-check) against that Function Runtime, and refuses to build the zip on an incompatible Platform Requirement. | ||
| 469 | - | ||
| 470 | -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](docs/adr/0008-let-scaleway-install-the-dependencies.md)). | ||
| 471 | -Executable bits are kept, and symbolic links are followed: their target is zipped. | ||
| 472 | - | ||
| 473 | -It refuses to build the zip, as Scaleway would install something else or fail without failing the deployment, when: | ||
| 474 | - | ||
| 475 | -- `handler.php` or `composer.lock` is missing; | ||
| 476 | -- `composer.lock` is not up to date with `composer.json`; | ||
| 477 | -- `composer.json` declares a `path` repository, or `composer.lock` installs a package from a local path: Scaleway cannot resolve them. | ||
| 478 | - | ||
| 479 | -| Shipped | Not shipped | | ||
| 480 | -| --- | --- | | ||
| 481 | -| Your code, `composer.json`, `composer.lock`, `handler.php` | `vendor/` and `var/` (installed and built on the platform) | | ||
| 482 | -| `.env`, `.env.prod`... as they are | `tests/`, `phpunit.xml(.dist)`, `.phpunit.cache`, `.phpunit.result.cache`, `.php-cs-fixer.cache` | | ||
| 483 | -| | `.env.local`, `.env.local.php`, `.env.*.local` | | ||
| 484 | -| | `.git`, `.idea`, `.vscode`, `.DS_Store`, `node_modules` anywhere | | ||
| 485 | -| | `.terraform`, `*.tfstate`, `*.tfstate.*` anywhere (Terraform state holds secrets in clear) | | ||
| 486 | - | ||
| 487 | -The full list is `Packager::EXCLUDES` in [src/Packager.php](src/Packager.php). | ||
| 488 | - | ||
| 489 | -Scaleway accepts zips up to 100 MiB, and up to 500 MiB of unzipped code ([limits](https://www.scaleway.com/en/docs/serverless-functions/reference-content/functions-limitations/)). | ||
| 490 | -`scaleway-package` warns when the zip or its content exceeds either, but still writes it. | ||
| 491 | - | ||
| 492 | -## Deployment | ||
| 493 | - | ||
| 494 | -[example/terraform](example/terraform/main.tf) deploys the [example application](example) 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. | ||
| 495 | -Its [README](example/README.md#deploy-it) gives the commands. | ||
| 496 | -That Terraform code was written against the `scaleway/scaleway` provider v2.92 documentation and has never been applied; the [probe](probe/terraform/main.tf)'s, written the same way, has. | ||
| 497 | - | ||
| 498 | -Redeploy by running `scaleway-package` again, then `terraform apply`. | ||
| 499 | -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. | ||
| 500 | - | ||
| 501 | -## Logs | ||
| 502 | - | ||
| 503 | -Scaleway sends what the function writes to stdout and stderr to [Cockpit](https://www.scaleway.com/en/docs/cockpit/), in the project's `Scaleway Logs` data source, about 2 seconds after it is written. | ||
| 504 | -The runtime logs its own failures to stderr, as Monolog does with a `php://stderr` handler. | ||
| 505 | -Without Monolog, Symfony's fallback logger writes to stderr too, but from the `error` level only: lower it as the [example](example/config/services.yaml) does. | ||
| 506 | -Each line is one log entry: a stack trace spans one entry per line, and a line over 16 KiB is split into 16 KiB entries and cut after 64 KiB. | ||
| 507 | -Every entry has the `debug` level, stderr ones included, except the continuations of a split line, whose level is `unknown`: filter on the `stream` field instead. | ||
| 508 | -An entry looks like this, with the `resource_id` label holding the function's UUID: | ||
| 509 | - | ||
| 510 | -```json | ||
| 511 | -{"message":"DEBUG - Invocation failed: RuntimeException: ... in /home/app/function/src/Kernel.php:12 source=user stream=stderr","stream":"stderr","resource_instance":"<namespace>-<function>-00001-deployment-<id>"} | ||
| 512 | -``` | ||
| 513 | - | ||
| 514 | -In the console, open Cockpit's Grafana (`scw cockpit grafana get` prints its URL) and the `Serverless Functions Logs` dashboard, or Explore with the `Scaleway Logs` data source. | ||
| 515 | - | ||
| 516 | -From the command line, query Loki's HTTP API with a token that can only read logs: | ||
| 517 | - | ||
| 518 | -```sh | ||
| 519 | -LOKI_URL=$(scw cockpit data-source list origin=scaleway types.0=logs -o json | jq -r '.[0].url') | ||
| 520 | -FUNCTION_ID=$(scw function function list name=<function name> -o json | jq -r '.[0].id') | ||
| 521 | -# The secret key is only shown at creation: keep it in memory rather than in a file that could get committed. | ||
| 522 | -TOKEN=$(scw cockpit token create name=read-logs token-scopes.0=read_only_logs -o json) | ||
| 523 | -LOKI_TOKEN=$(jq -r .secret_key <<< "$TOKEN") | ||
| 524 | - | ||
| 525 | -curl -sS -G "$LOKI_URL/loki/api/v1/query_range" -H "Authorization: Bearer $LOKI_TOKEN" \ | ||
| 526 | - --data-urlencode "query={resource_id=\"$FUNCTION_ID\"} | json | stream=\"stderr\" | line_format \"{{.message}}\"" \ | ||
| 527 | - --data-urlencode since=1h --data-urlencode limit=1000 \ | ||
| 528 | - | jq -r '[.data.result[].values[]] | sort_by(.[0]) | .[][1]' | ||
| 529 | - | ||
| 530 | -scw cockpit token delete token-id=$(jq -r .id <<< "$TOKEN") | ||
| 531 | -``` | ||
| 532 | - | ||
| 533 | -Token names are unique within a project: if a `read-logs` token was left behind, `token create` fails with `resource already exists`, so delete it first. | ||
| 534 | -Without the `stream="stderr"` filter, the query also returns stdout and the platform's own lines (`Function Triggered: /`, `Function is now ready to serve requests!`). | ||
| 535 | - | ||
| 536 | -## Local development with the Emulator | ||
| 537 | - | ||
| 538 | -```sh | ||
| 539 | -vendor/bin/scaleway-serve [127.0.0.1:8000] | ||
| 540 | -``` | ||
| 541 | - | ||
| 542 | -The Emulator turns each HTTP request into an Event, calls your `handle()` and turns the Function Response back into the HTTP response. | ||
| 543 | -`handle()` runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code. | ||
| 544 | -It sets `APP_ENV=dev` unless started with an `APP_ENV`, as the deployed function defaults to `prod`. | ||
| 545 | -A crashed process is replaced by a fresh one, as Scaleway starts a new instance. | ||
| 546 | - | ||
| 547 | -PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory. | ||
| 548 | - | ||
| 549 | -The Event and the context are built the way the platform builds them ([measured](docs/probe-results.md)): | ||
| 550 | - | ||
| 551 | -- the `httpMethod`, `queryStringParameters` (sorted by key, the last value of a repeated key winning, `[]` without query string) and other keys of the platform; | ||
| 552 | -- header names in `Title-Case`, repeated headers joined with `, `, no `Host`; | ||
| 553 | -- `X-Real-Ip`, `X-Envoy-External-Address`, `X-Request-Id` and `X-Forwarded-Proto: https` set whatever the client sends, the client's `X-Forwarded-For` kept in front of its address, its `X-Forwarded-Host` passed through; | ||
| 554 | -- empty, multipart and non UTF-8 bodies base64-encoded with `isBase64Encoded: true`, text bodies without the flag. | ||
| 555 | - | ||
| 556 | -So the Requests are `https`, and their host is `localhost` unless you set `SCALEWAY_HOST`, as on the platform. | ||
| 557 | - | ||
| 558 | -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: | ||
| 559 | - | ||
| 560 | -```sh | ||
| 561 | -curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"job": "cleanup"}' | ||
| 562 | -``` | ||
| 563 | - | ||
| 564 | -Simulate a Command Invocation by starting the Emulator with `SCALEWAY_CRON_SECRET` set, and sending the [Command Invocation body](#command-invocations) the same way: | ||
| 565 | - | ||
| 566 | -```sh | ||
| 567 | -SCALEWAY_CRON_SECRET=local-secret vendor/bin/scaleway-serve | ||
| 568 | -curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}' | ||
| 569 | -``` | ||
| 570 | - | ||
| 571 | -To run what gets deployed, install the zip the way Scaleway does, without the function's variables, then serve it in `prod`: | ||
| 572 | - | ||
| 573 | -```sh | ||
| 574 | -vendor/bin/scaleway-package | ||
| 575 | -unzip -q function.zip -d /tmp/function | ||
| 576 | -composer install --working-dir=/tmp/function --no-dev | ||
| 577 | -APP_ENV=prod APP_SECRET=local php /tmp/function/vendor/bin/scaleway-serve | ||
| 578 | -``` | ||
| 579 | - | ||
| 580 | -The [example](example/README.md#run-it-locally)'s `e2e/deploy-locally.sh` does the same with the runtime of this repository. | ||
| 581 | - | ||
| 582 | -## Warm Processes | ||
| 583 | - | ||
| 584 | -The Application is built once per Warm Process and reused by the following Invocations, like with FrankenPHP's worker mode or RoadRunner ([ADR 0002](docs/adr/0002-reuse-application-across-invocations.md)). | ||
| 585 | -Scaleway keeps processes warm: consecutive Invocations of an instance run in the same PHP process. | ||
| 586 | - | ||
| 587 | -Between Invocations, for a Kernel: | ||
| 588 | - | ||
| 589 | -- `terminate()` runs after each Invocation, and a failure in it is logged without changing the Function Response; | ||
| 590 | -- the `services_resetter` resets the services tagged `kernel.reset` before the next request, as Symfony's Kernel does; | ||
| 591 | -- uploaded files are deleted, and output buffers the Application left open are closed. | ||
| 592 | - | ||
| 593 | -Everything else survives, so your application must be safe for long-running execution: | ||
| 594 | - | ||
| 595 | -- do not keep per-request state in static properties or in services that do not implement `ResetInterface`; | ||
| 596 | -- in-memory caches and collections grow across Invocations unless reset; | ||
| 597 | -- connections (database, HTTP clients) may have been closed by the server while the process was idle; | ||
| 598 | -- `exit()` or a fatal error ends the process, and the next Invocation pays a cold start. | ||
| 599 | - | ||
| 600 | -## Limitations and platform caveats | ||
| 601 | - | ||
| 602 | -### Requests and responses | ||
| 603 | - | ||
| 604 | -- **Superglobals**: `$_GET`, `$_POST`, `$_COOKIE`, `$_FILES` and the request entries of `$_SERVER` (`REQUEST_URI`, `HTTP_*`...) are not populated per Invocation. | ||
| 605 | - Read the `Request` object instead; `Request::createFromGlobals()` does not describe the Invocation. | ||
| 606 | -- **Output**: only the returned `Response` reaches the client. | ||
| 607 | - `echo` outside the Response, `header()` and `http_response_code()` do not: Scaleway does not put stdout in the response body. | ||
| 608 | -- **Query strings**: the Event carries `queryStringParameters` as a map, so a repeated key such as `a=1&a=2`, or `tags[]=a&tags[]=b`, reaches the Application with its last value only, and the keys arrive sorted, not in the order the client sent them. | ||
| 609 | - Keys are then parsed like PHP does, so `a.b` becomes `a_b` and `a[b]` nests. | ||
| 610 | -- **Form bodies**: `application/x-www-form-urlencoded` bodies are parsed for `POST`, `PUT`, `DELETE`, `PATCH` and `QUERY`, `multipart/form-data` only for `POST`, as PHP does. | ||
| 611 | - Uploaded files are `UploadedFile` objects in test mode: `move()` works, `is_uploaded_file()` does not. | ||
| 612 | -- **Cookies**: request cookie names are taken verbatim: unlike PHP's `$_COOKIE`, dots and spaces are not turned into underscores and `a[b]` does not nest. | ||
| 613 | -- **Streaming**: `StreamedResponse` and `BinaryFileResponse` are buffered into one Function Response; Server-Sent Events and long downloads are not possible. | ||
| 614 | - Bodies that are not valid UTF-8 are sent base64-encoded, and decoded by the platform. | ||
| 615 | -- **PSR-15 responses** go through Symfony's `Response`, which adds `Cache-Control: no-cache, private` and `Date` when they are missing. | ||
| 616 | -- **HEAD requests**: only FrameworkBundle's `ResponseListener` strips the body of a `HEAD` response, but the platform sends none anyway. | ||
| 617 | -- **Request size**: Scaleway rejects request bodies over 6 MiB with a `413`, before they reach the function. | ||
| 618 | -- **CORS**: Scaleway adds `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: Content-Type` to every response, whatever the Application sends. | ||
| 619 | - 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. | ||
| 620 | -- **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 a `500` whose body is `Error while executing function`. | ||
| 621 | - | ||
| 622 | -### Client IP and trusted proxies | ||
| 623 | - | ||
| 624 | -The runtime trusts no proxy, as clients can forge most forwarding headers on Scaleway ([ADR 0007](docs/adr/0007-trust-only-headers-the-platform-overwrites.md)): | ||
| 625 | - | ||
| 626 | -| Request | From | Why | | ||
| 627 | -| --- | --- | --- | | ||
| 628 | -| `getClientIp()` | `X-Real-Ip`, `127.0.0.1` without it (CRON Invocations) | Set by the platform, whatever the client sends | | ||
| 629 | -| `isSecure()`, `getScheme()`, port | `X-Forwarded-Proto`, the scheme's default port | Set by the platform (`https`, `http` for CRON Invocations) | | ||
| 630 | -| `getHost()` | The [`host` option](#host) | No `Host` header reaches the function | | ||
| 631 | - | ||
| 632 | -`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. | ||
| 633 | -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. | ||
| 634 | - | ||
| 635 | -> [!CAUTION] | ||
| 636 | -> Do not configure `framework.trusted_proxies`: the client is already resolved, and trusting `REMOTE_ADDR` or private ranges would make Symfony trust those forgeable headers again. | ||
| 637 | -> Trusted proxies your application configures still apply, as usual. | ||
| 638 | - | ||
| 639 | -### Composer at deploy time | ||
| 640 | - | ||
| 641 | -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/`. | ||
| 642 | -Every locked package must therefore be downloadable from Scaleway, and the function's environment variables are not available to Composer scripts. | ||
| 643 | -The lock must also install on the function's runtime: set `config.platform.php` in `composer.json` to its PHP version (`8.4` for `php84`, `8.5` for `php85`) so that `composer update` resolves for it. | ||
| 644 | -`config.platform` only steers Composer's resolution: run the [compatibility check](#compatibility-check), or package with `--runtime`, to check the lock against what Scaleway provides. | ||
| 645 | -A failing install or script does not fail the deployment, and Scaleway serves the new code anyway, never the previous version ([measured](docs/probe-results.md#failed-scripts-and-installs)): | ||
| 646 | - | ||
| 647 | -- a failing script runs once `vendor/` and its autoloader are complete, so the new code works, without what the script should have done (a warmed cache, generated files...); | ||
| 648 | -- a failing install, from a package Scaleway cannot download or a platform requirement its runtime does not meet, leaves no `vendor/` at all: every Invocation answers a `500`, the first one of each instance logging `Failed to open stream` for `vendor/autoload.php` on stdout, the next ones `Class "JDecool\ScalewayRuntime\Handler" not found` on stderr. | ||
| 649 | - | ||
| 650 | -Neither shows anywhere: the function is `ready`, its `error_message` and `build_message` stay empty, and Composer's output reaches neither Cockpit nor `scw`. | ||
| 651 | -So after each deploy, call a route that should answer a `200`, and check the function's [logs](#logs) if it does not: | ||
| 652 | - | ||
| 653 | -```sh | ||
| 654 | -curl -sS -o /dev/null -w '%{http_code}\n' "https://$(scw function function list name=<function name> -o json | jq -r '.[0].domain_name')/<route>" | ||
| 655 | -``` | ||
| 656 | - | ||
| 657 | -Keep deploy-time scripts to what the application can do without, as a cache warmup the first Invocation redoes, and run whatever it needs at runtime instead. | ||
| 658 | - | ||
| 659 | -### Windows | ||
| 660 | - | ||
| 661 | -`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. | ||
| 662 | -Without the `pcntl` extension, stopping the Emulator with `kill` may leave its PHP processes running. | ||
| 663 | 58 | ||
| 664 | ## Contributing | 59 | ## Contributing |
| 665 | 60 | ||
| 666 | -```sh | 61 | +See [CONTRIBUTING.md](CONTRIBUTING.md). |
| 667 | -composer install | ||
| 668 | -composer check # PHP-CS-Fixer (dry run), PHPStan (max level) and PHPUnit | ||
| 669 | -composer cs-fix # applies the coding style | ||
| 670 | -``` | ||
| 671 | - | ||
| 672 | -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`. | ||
| 673 | -It also runs the [end-to-end scenarios](example/e2e/run.sh) of the [example application](example) through the Emulator, in dev and on its zip installed like Scaleway does ([e2e/deploy-locally.sh](example/e2e/deploy-locally.sh)). | ||
| 674 | -The example installs the runtime of the checkout with `composer link-runtime`, see its [README](example/README.md#run-it-locally). | ||
| 675 | -A weekly workflow measures the Function Runtimes on Scaleway again, and opens a pull request when the catalogue changes, see [docs/probe-results.md](docs/probe-results.md#function-runtime-catalogue). | ||
| 676 | - | ||
| 677 | -The repository holds: | ||
| 678 | - | ||
| 679 | -- `src/`, `bin/`, `resources/`: the package; | ||
| 680 | -- `tests/`: PHPUnit tests, packaging included; | ||
| 681 | -- `example/`: a demo Symfony application requiring the package, with Terraform code to deploy it; | ||
| 682 | -- `probe/`: a dependency-free function measuring the platform facts, its [results](docs/probe-results.md), and the generator of the [Function Runtime Catalogue](docs/probe-results.md#function-runtime-catalogue); | ||
| 683 | -- `docs/`: the [ADRs](docs/adr). | ||
| 684 | 62 | ||
| 685 | ## License | 63 | ## License |
| 686 | 64 | ||
added
docs/README.md +32 -0 | new file mode 100644 | ||
| @@ -0,0 +1,32 @@ | ||
| 1 | +# Documentation | |
| 2 | + | |
| 3 | +What each document in this folder is for. | |
| 4 | +Requirements and installation live in the root [README](../README.md), the vocabulary in [GLOSSARY.md](../GLOSSARY.md), and the contribution workflow in [CONTRIBUTING.md](../CONTRIBUTING.md). | |
| 5 | + | |
| 6 | +## Using the runtime | |
| 7 | + | |
| 8 | +- [Configuration](configuration.md) - the function handler, choosing the Front Controller, the environment variables to set, the host of absolute URLs, the cache and writable directories, and how errors are answered. | |
| 9 | +- [Supported Applications](applications.md) - what a Front Controller may return: an HttpKernel, a Response, a PSR-15 request handler, a Console Application or Command, or a raw callable. | |
| 10 | +- [Static Files](static-files.md) - which files of `public/` the runtime serves itself, their caching headers, compression and size limits. | |
| 11 | +- [CRON triggers and Command Invocations](cron-and-commands.md) - handling a CRON trigger as a route, running a console command from one, and the security model behind it. | |
| 12 | +- [Warm Processes](warm-processes.md) - what survives between Invocations, and what an application must do to be safe for long-running execution. | |
| 13 | +- [Requests and responses](requests-and-responses.md) - the platform caveats on superglobals, output, query strings, bodies and streaming, and how the client IP is resolved without trusting any proxy. | |
| 14 | + | |
| 15 | +## Shipping | |
| 16 | + | |
| 17 | +- [Compatibility check](compatibility-check.md) - checking the Platform Requirements of the lock against a Function Runtime with `scaleway-doctor`, before deploying. | |
| 18 | +- [Packaging](packaging.md) - building the deployment zip with `scaleway-package`, what it ships and what it refuses. | |
| 19 | +- [Deployment](deployment.md) - deploying with Terraform, redeploying, and what Scaleway's `composer install` does at deploy time. | |
| 20 | +- [Logs](logs.md) - where the function's output shows up in Cockpit, and querying it from the command line. | |
| 21 | + | |
| 22 | +## Developing | |
| 23 | + | |
| 24 | +- [Local development with the Emulator](local-development.md) - running the function locally with `scaleway-serve`, simulating CRON and Command Invocations, serving the zip as deployed, and Windows support. | |
| 25 | + | |
| 26 | +## Reference | |
| 27 | + | |
| 28 | +- [Probe results](probe-results.md) - the platform facts measured on Scaleway, and the Function Runtime Catalogue. | |
| 29 | + | |
| 30 | +## Decisions | |
| 31 | + | |
| 32 | +- [Architecture decision records](adr/README.md) - why the runtime is shaped the way it is, one file per decision, indexed by number. | |
| new file mode 100644 | |||
| @@ -0,0 +1,32 @@ | |||
| 1 | +# Documentation | ||
| 2 | + | ||
| 3 | +What each document in this folder is for. | ||
| 4 | +Requirements and installation live in the root [README](../README.md), the vocabulary in [GLOSSARY.md](../GLOSSARY.md), and the contribution workflow in [CONTRIBUTING.md](../CONTRIBUTING.md). | ||
| 5 | + | ||
| 6 | +## Using the runtime | ||
| 7 | + | ||
| 8 | +- [Configuration](configuration.md) - the function handler, choosing the Front Controller, the environment variables to set, the host of absolute URLs, the cache and writable directories, and how errors are answered. | ||
| 9 | +- [Supported Applications](applications.md) - what a Front Controller may return: an HttpKernel, a Response, a PSR-15 request handler, a Console Application or Command, or a raw callable. | ||
| 10 | +- [Static Files](static-files.md) - which files of `public/` the runtime serves itself, their caching headers, compression and size limits. | ||
| 11 | +- [CRON triggers and Command Invocations](cron-and-commands.md) - handling a CRON trigger as a route, running a console command from one, and the security model behind it. | ||
| 12 | +- [Warm Processes](warm-processes.md) - what survives between Invocations, and what an application must do to be safe for long-running execution. | ||
| 13 | +- [Requests and responses](requests-and-responses.md) - the platform caveats on superglobals, output, query strings, bodies and streaming, and how the client IP is resolved without trusting any proxy. | ||
| 14 | + | ||
| 15 | +## Shipping | ||
| 16 | + | ||
| 17 | +- [Compatibility check](compatibility-check.md) - checking the Platform Requirements of the lock against a Function Runtime with `scaleway-doctor`, before deploying. | ||
| 18 | +- [Packaging](packaging.md) - building the deployment zip with `scaleway-package`, what it ships and what it refuses. | ||
| 19 | +- [Deployment](deployment.md) - deploying with Terraform, redeploying, and what Scaleway's `composer install` does at deploy time. | ||
| 20 | +- [Logs](logs.md) - where the function's output shows up in Cockpit, and querying it from the command line. | ||
| 21 | + | ||
| 22 | +## Developing | ||
| 23 | + | ||
| 24 | +- [Local development with the Emulator](local-development.md) - running the function locally with `scaleway-serve`, simulating CRON and Command Invocations, serving the zip as deployed, and Windows support. | ||
| 25 | + | ||
| 26 | +## Reference | ||
| 27 | + | ||
| 28 | +- [Probe results](probe-results.md) - the platform facts measured on Scaleway, and the Function Runtime Catalogue. | ||
| 29 | + | ||
| 30 | +## Decisions | ||
| 31 | + | ||
| 32 | +- [Architecture decision records](adr/README.md) - why the runtime is shaped the way it is, one file per decision, indexed by number. | ||
added
docs/adr/README.md +17 -0 | new file mode 100644 | ||
| @@ -0,0 +1,17 @@ | ||
| 1 | +# Architecture decision records | |
| 2 | + | |
| 3 | +Why the runtime is shaped the way it is, one file per decision. | |
| 4 | +A superseded record stays, as the history of the decision, and names the one that replaces it. | |
| 5 | + | |
| 6 | +| ADR | Decision | | |
| 7 | +| --- | --- | | |
| 8 | +| [0001](0001-handler-drives-runtime-lifecycle.md) | The Handler drives the Runtime lifecycle instead of `autoload_runtime.php` | | |
| 9 | +| [0002](0002-reuse-application-across-invocations.md) | The Application is booted once per Warm Process and reset between Invocations | | |
| 10 | +| [0003](0003-ship-vendor-and-warm-cache-in-zip.md) | The deployment zip ships `vendor/` and a warmed-up cache (superseded by [0008](0008-let-scaleway-install-the-dependencies.md)) | | |
| 11 | +| [0004](0004-call-response-front-controllers-per-invocation.md) | A Front Controller returning a Response is called for every Invocation | | |
| 12 | +| [0005](0005-authenticate-command-invocations-with-a-shared-secret.md) | Command Invocations need both a CRON-shaped Event and a shared secret carried in the CRON arguments | | |
| 13 | +| [0006](0006-default-to-the-prod-env.md) | The Handler defaults `APP_ENV` to `prod`, whatever the `.env` files say | | |
| 14 | +| [0007](0007-trust-only-headers-the-platform-overwrites.md) | The Request trusts only the headers the platform overwrites | | |
| 15 | +| [0008](0008-let-scaleway-install-the-dependencies.md) | Scaleway installs the dependencies, and the cache is built on the platform | | |
| 16 | +| [0009](0009-serve-static-files-from-the-function.md) | The function serves Static Files itself | | |
| 17 | +| [0013](0013-check-platform-requirements-against-an-explicit-function-runtime.md) | Check declared Platform Requirements against an explicit Function Runtime | | |
| new file mode 100644 | |||
| @@ -0,0 +1,17 @@ | |||
| 1 | +# Architecture decision records | ||
| 2 | + | ||
| 3 | +Why the runtime is shaped the way it is, one file per decision. | ||
| 4 | +A superseded record stays, as the history of the decision, and names the one that replaces it. | ||
| 5 | + | ||
| 6 | +| ADR | Decision | | ||
| 7 | +| --- | --- | | ||
| 8 | +| [0001](0001-handler-drives-runtime-lifecycle.md) | The Handler drives the Runtime lifecycle instead of `autoload_runtime.php` | | ||
| 9 | +| [0002](0002-reuse-application-across-invocations.md) | The Application is booted once per Warm Process and reset between Invocations | | ||
| 10 | +| [0003](0003-ship-vendor-and-warm-cache-in-zip.md) | The deployment zip ships `vendor/` and a warmed-up cache (superseded by [0008](0008-let-scaleway-install-the-dependencies.md)) | | ||
| 11 | +| [0004](0004-call-response-front-controllers-per-invocation.md) | A Front Controller returning a Response is called for every Invocation | | ||
| 12 | +| [0005](0005-authenticate-command-invocations-with-a-shared-secret.md) | Command Invocations need both a CRON-shaped Event and a shared secret carried in the CRON arguments | | ||
| 13 | +| [0006](0006-default-to-the-prod-env.md) | The Handler defaults `APP_ENV` to `prod`, whatever the `.env` files say | | ||
| 14 | +| [0007](0007-trust-only-headers-the-platform-overwrites.md) | The Request trusts only the headers the platform overwrites | | ||
| 15 | +| [0008](0008-let-scaleway-install-the-dependencies.md) | Scaleway installs the dependencies, and the cache is built on the platform | | ||
| 16 | +| [0009](0009-serve-static-files-from-the-function.md) | The function serves Static Files itself | | ||
| 17 | +| [0013](0013-check-platform-requirements-against-an-explicit-function-runtime.md) | Check declared Platform Requirements against an explicit Function Runtime | | ||
added
docs/applications.md +118 -0 | new file mode 100644 | ||
| @@ -0,0 +1,118 @@ | ||
| 1 | +# Supported Applications | |
| 2 | + | |
| 3 | +The Front Controller returns a closure, as with any Symfony Runtime. | |
| 4 | +The type of what that closure returns, the Application, decides how Invocations are served. | |
| 5 | + | |
| 6 | +## HttpKernel | |
| 7 | + | |
| 8 | +The usual Symfony Front Controller: | |
| 9 | + | |
| 10 | +```php | |
| 11 | +<?php // public/index.php | |
| 12 | + | |
| 13 | +use App\Kernel; | |
| 14 | + | |
| 15 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 16 | + | |
| 17 | +return function (array $context) { | |
| 18 | + return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); | |
| 19 | +}; | |
| 20 | +``` | |
| 21 | + | |
| 22 | +The Kernel is booted once per Warm Process and serves every Invocation, see [Warm Processes](warm-processes.md). | |
| 23 | +Any `HttpKernelInterface` works; a `KernelInterface` also runs [Command Invocations](cron-and-commands.md#command-invocations). | |
| 24 | + | |
| 25 | +## Response | |
| 26 | + | |
| 27 | +A closure returning a `Response` is called again for every Invocation, without any Kernel. | |
| 28 | +A `Request` argument receives the Invocation's Request: | |
| 29 | + | |
| 30 | +```php | |
| 31 | +<?php // public/hello.php | |
| 32 | + | |
| 33 | +use Symfony\Component\HttpFoundation\JsonResponse; | |
| 34 | +use Symfony\Component\HttpFoundation\Request; | |
| 35 | + | |
| 36 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 37 | + | |
| 38 | +return static function (Request $request): JsonResponse { | |
| 39 | + return new JsonResponse(['message' => sprintf('Hello %s!', $request->query->get('name', 'World'))]); | |
| 40 | +}; | |
| 41 | +``` | |
| 42 | + | |
| 43 | +Keep the closure cheap, as it runs on every Invocation, and make it return a `Response` every time. | |
| 44 | +See [ADR 0004](adr/0004-call-response-front-controllers-per-invocation.md). | |
| 45 | + | |
| 46 | +## PSR-15 request handler | |
| 47 | + | |
| 48 | +A closure returning a `Psr\Http\Server\RequestHandlerInterface` builds it once per Warm Process. | |
| 49 | +It needs two more packages: | |
| 50 | + | |
| 51 | +```sh | |
| 52 | +composer require symfony/psr-http-message-bridge nyholm/psr7 | |
| 53 | +``` | |
| 54 | + | |
| 55 | +```php | |
| 56 | +<?php // public/index.php | |
| 57 | + | |
| 58 | +use App\ApiHandler; | |
| 59 | +use Psr\Http\Server\RequestHandlerInterface; | |
| 60 | + | |
| 61 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 62 | + | |
| 63 | +return static fn (): RequestHandlerInterface => new ApiHandler(); | |
| 64 | +``` | |
| 65 | + | |
| 66 | +The PSR-7 request carries the client address, scheme, host and port the runtime resolved (see [Client IP and trusted proxies](requests-and-responses.md#client-ip-and-trusted-proxies)), in its URI and in the `REMOTE_ADDR`, `HTTPS`, `HTTP_HOST` and `SERVER_PORT` server params. | |
| 67 | +A handler implementing `Symfony\Contracts\Service\ResetInterface` is reset before every Invocation but the first. | |
| 68 | +A malformed host is answered with a 400 before reaching the handler. | |
| 69 | + | |
| 70 | +## Console Application or Command | |
| 71 | + | |
| 72 | +A Front Controller returning a Console `Application` or a `Command` only serves [Command Invocations](cron-and-commands.md#command-invocations), and answers every other Invocation with a 403. | |
| 73 | +Symfony's `bin/console` is such a Front Controller: | |
| 74 | + | |
| 75 | +```sh | |
| 76 | +APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | |
| 77 | +``` | |
| 78 | + | |
| 79 | +A single `Command` runs whatever `command` the Command Invocation names: | |
| 80 | + | |
| 81 | +```php | |
| 82 | +<?php // bin/cleanup.php | |
| 83 | + | |
| 84 | +use Symfony\Component\Console\Command\Command; | |
| 85 | +use Symfony\Component\Console\Input\InputInterface; | |
| 86 | +use Symfony\Component\Console\Output\OutputInterface; | |
| 87 | + | |
| 88 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | |
| 89 | + | |
| 90 | +return static fn (): Command => (new Command('app:cleanup')) | |
| 91 | + ->setCode(static function (InputInterface $input, OutputInterface $output): int { | |
| 92 | + $output->writeln('Cleaned up'); | |
| 93 | + | |
| 94 | + return Command::SUCCESS; | |
| 95 | + }); | |
| 96 | +``` | |
| 97 | + | |
| 98 | +This needs `symfony/console`, and `symfony/framework-bundle` for a `Symfony\Bundle\FrameworkBundle\Console\Application`. | |
| 99 | + | |
| 100 | +## Raw callable | |
| 101 | + | |
| 102 | +A closure returning another `Closure` talks to Scaleway without any translation. | |
| 103 | +The inner closure is built once per Warm Process and receives every Event and context as they are, CRON Invocations included: | |
| 104 | + | |
| 105 | +```php | |
| 106 | +<?php // public/raw.php | |
| 107 | + | |
| 108 | +return static fn (): Closure => static fn (array $event, mixed $context): array => [ | |
| 109 | + 'statusCode' => 200, | |
| 110 | + 'headers' => ['Content-Type' => 'text/plain'], | |
| 111 | + 'body' => 'Hello from '.($event['path'] ?? '/'), | |
| 112 | +]; | |
| 113 | +``` | |
| 114 | + | |
| 115 | +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`. | |
| 116 | +Other keys are dropped, and any other return value fails the Invocation with a 500. | |
| 117 | +Command Invocations are not routed: the raw callable gets their Event like any other. | |
| 118 | +An invokable object is not taken for a raw callable; return `$object(...)` to make it one. | |
| new file mode 100644 | |||
| @@ -0,0 +1,118 @@ | |||
| 1 | +# Supported Applications | ||
| 2 | + | ||
| 3 | +The Front Controller returns a closure, as with any Symfony Runtime. | ||
| 4 | +The type of what that closure returns, the Application, decides how Invocations are served. | ||
| 5 | + | ||
| 6 | +## HttpKernel | ||
| 7 | + | ||
| 8 | +The usual Symfony Front Controller: | ||
| 9 | + | ||
| 10 | +```php | ||
| 11 | +<?php // public/index.php | ||
| 12 | + | ||
| 13 | +use App\Kernel; | ||
| 14 | + | ||
| 15 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 16 | + | ||
| 17 | +return function (array $context) { | ||
| 18 | + return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']); | ||
| 19 | +}; | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +The Kernel is booted once per Warm Process and serves every Invocation, see [Warm Processes](warm-processes.md). | ||
| 23 | +Any `HttpKernelInterface` works; a `KernelInterface` also runs [Command Invocations](cron-and-commands.md#command-invocations). | ||
| 24 | + | ||
| 25 | +## Response | ||
| 26 | + | ||
| 27 | +A closure returning a `Response` is called again for every Invocation, without any Kernel. | ||
| 28 | +A `Request` argument receives the Invocation's Request: | ||
| 29 | + | ||
| 30 | +```php | ||
| 31 | +<?php // public/hello.php | ||
| 32 | + | ||
| 33 | +use Symfony\Component\HttpFoundation\JsonResponse; | ||
| 34 | +use Symfony\Component\HttpFoundation\Request; | ||
| 35 | + | ||
| 36 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 37 | + | ||
| 38 | +return static function (Request $request): JsonResponse { | ||
| 39 | + return new JsonResponse(['message' => sprintf('Hello %s!', $request->query->get('name', 'World'))]); | ||
| 40 | +}; | ||
| 41 | +``` | ||
| 42 | + | ||
| 43 | +Keep the closure cheap, as it runs on every Invocation, and make it return a `Response` every time. | ||
| 44 | +See [ADR 0004](adr/0004-call-response-front-controllers-per-invocation.md). | ||
| 45 | + | ||
| 46 | +## PSR-15 request handler | ||
| 47 | + | ||
| 48 | +A closure returning a `Psr\Http\Server\RequestHandlerInterface` builds it once per Warm Process. | ||
| 49 | +It needs two more packages: | ||
| 50 | + | ||
| 51 | +```sh | ||
| 52 | +composer require symfony/psr-http-message-bridge nyholm/psr7 | ||
| 53 | +``` | ||
| 54 | + | ||
| 55 | +```php | ||
| 56 | +<?php // public/index.php | ||
| 57 | + | ||
| 58 | +use App\ApiHandler; | ||
| 59 | +use Psr\Http\Server\RequestHandlerInterface; | ||
| 60 | + | ||
| 61 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 62 | + | ||
| 63 | +return static fn (): RequestHandlerInterface => new ApiHandler(); | ||
| 64 | +``` | ||
| 65 | + | ||
| 66 | +The PSR-7 request carries the client address, scheme, host and port the runtime resolved (see [Client IP and trusted proxies](requests-and-responses.md#client-ip-and-trusted-proxies)), in its URI and in the `REMOTE_ADDR`, `HTTPS`, `HTTP_HOST` and `SERVER_PORT` server params. | ||
| 67 | +A handler implementing `Symfony\Contracts\Service\ResetInterface` is reset before every Invocation but the first. | ||
| 68 | +A malformed host is answered with a 400 before reaching the handler. | ||
| 69 | + | ||
| 70 | +## Console Application or Command | ||
| 71 | + | ||
| 72 | +A Front Controller returning a Console `Application` or a `Command` only serves [Command Invocations](cron-and-commands.md#command-invocations), and answers every other Invocation with a 403. | ||
| 73 | +Symfony's `bin/console` is such a Front Controller: | ||
| 74 | + | ||
| 75 | +```sh | ||
| 76 | +APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | ||
| 77 | +``` | ||
| 78 | + | ||
| 79 | +A single `Command` runs whatever `command` the Command Invocation names: | ||
| 80 | + | ||
| 81 | +```php | ||
| 82 | +<?php // bin/cleanup.php | ||
| 83 | + | ||
| 84 | +use Symfony\Component\Console\Command\Command; | ||
| 85 | +use Symfony\Component\Console\Input\InputInterface; | ||
| 86 | +use Symfony\Component\Console\Output\OutputInterface; | ||
| 87 | + | ||
| 88 | +require_once dirname(__DIR__).'/vendor/autoload_runtime.php'; | ||
| 89 | + | ||
| 90 | +return static fn (): Command => (new Command('app:cleanup')) | ||
| 91 | + ->setCode(static function (InputInterface $input, OutputInterface $output): int { | ||
| 92 | + $output->writeln('Cleaned up'); | ||
| 93 | + | ||
| 94 | + return Command::SUCCESS; | ||
| 95 | + }); | ||
| 96 | +``` | ||
| 97 | + | ||
| 98 | +This needs `symfony/console`, and `symfony/framework-bundle` for a `Symfony\Bundle\FrameworkBundle\Console\Application`. | ||
| 99 | + | ||
| 100 | +## Raw callable | ||
| 101 | + | ||
| 102 | +A closure returning another `Closure` talks to Scaleway without any translation. | ||
| 103 | +The inner closure is built once per Warm Process and receives every Event and context as they are, CRON Invocations included: | ||
| 104 | + | ||
| 105 | +```php | ||
| 106 | +<?php // public/raw.php | ||
| 107 | + | ||
| 108 | +return static fn (): Closure => static fn (array $event, mixed $context): array => [ | ||
| 109 | + 'statusCode' => 200, | ||
| 110 | + 'headers' => ['Content-Type' => 'text/plain'], | ||
| 111 | + 'body' => 'Hello from '.($event['path'] ?? '/'), | ||
| 112 | +]; | ||
| 113 | +``` | ||
| 114 | + | ||
| 115 | +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`. | ||
| 116 | +Other keys are dropped, and any other return value fails the Invocation with a 500. | ||
| 117 | +Command Invocations are not routed: the raw callable gets their Event like any other. | ||
| 118 | +An invokable object is not taken for a raw callable; return `$object(...)` to make it one. | ||
added
docs/compatibility-check.md +47 -0 | new file mode 100644 | ||
| @@ -0,0 +1,47 @@ | ||
| 1 | +# Compatibility check | |
| 2 | + | |
| 3 | +```sh | |
| 4 | +vendor/bin/scaleway-doctor --runtime=php84 | |
| 5 | +``` | |
| 6 | + | |
| 7 | +A Platform Requirement (`php` or `ext-*`) the Function Runtime does not meet makes Scaleway's `composer install` fail at deploy time, without failing the deployment: every Invocation then answers a `500` (see [Composer at deploy time](deployment.md#composer-at-deploy-time)). | |
| 8 | +`scaleway-doctor` checks, before you deploy, the Platform Requirements that install checks, against the Function Runtime the function declares, named by `--runtime` (`php84` or `php85`). | |
| 9 | +It never guesses it from your local PHP. | |
| 10 | +It reads `composer.json` and `composer.lock`, needs neither Scaleway credentials nor network access, and refuses a stale lock as [`scaleway-package`](packaging.md) does. | |
| 11 | + | |
| 12 | +It checks what `composer install --no-dev` checks on Scaleway: | |
| 13 | + | |
| 14 | +- the root requirements the lock records, and those of every locked production package, development ones excluded; | |
| 15 | +- each one met by the Function Runtime, or by a `provide` or `replace` of the application or of a locked package; | |
| 16 | +- constraints evaluated by Composer's own engine, against the PHP and extension versions Composer would see on Scaleway. | |
| 17 | + | |
| 18 | +Each requirement is: | |
| 19 | + | |
| 20 | +- **satisfied**, when the measured version matches; | |
| 21 | +- **incompatible**, when the extension is not loaded, or the measured version of PHP or of the extension does not match; | |
| 22 | +- **unknown**, for the platform packages the catalogue does not measure, as `lib-icu` or `php-64bit`. | |
| 23 | + | |
| 24 | +Composer's own APIs (`composer`, `composer-plugin-api`, `composer-runtime-api`) are not checked: Scaleway installs with Composer 2. | |
| 25 | + | |
| 26 | +The report, on stderr, lists the incompatible and unknown requirements, with what declares them and what the Function Runtime provides: | |
| 27 | + | |
| 28 | +```text | |
| 29 | +INCOMPATIBLE ext-foo * required by acme/bar v2.1.0 php84: not loaded (measured 2026-11-22) | |
| 30 | + php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions. | |
| 31 | +UNKNOWN lib-icu >=72 required by symfony/intl v8.0.3 not in the Function Runtime Catalogue | |
| 32 | + | |
| 33 | +48 satisfied, 1 unknown, 1 incompatible on php84 (measured 2026-11-22) | |
| 34 | +This covers declared Platform Requirements only, not whether the application runs. | |
| 35 | +``` | |
| 36 | + | |
| 37 | +It exits with `0` when every requirement is satisfied or only unknowns remain, and with `1` on an incompatible requirement or an invalid input. | |
| 38 | +For an incompatible requirement, it names the other Function Runtimes that meet it, if any. | |
| 39 | +Otherwise, custom extensions or versions need [Serverless Containers](https://www.scaleway.com/en/serverless-containers/), which this package does not target. | |
| 40 | + | |
| 41 | +What each Function Runtime provides comes from the Function Runtime Catalogue shipped with the package, [resources/function-runtimes.php](../resources/function-runtimes.php). | |
| 42 | +It holds measurements only, made on Scaleway with the [probe](../probe), each a complete inventory: an extension it does not list is not loaded. | |
| 43 | +A measurement describes the Function Runtime on its date, which the report shows, not a guarantee that Scaleway keeps the same versions. | |
| 44 | +The measured PHP patch version is authoritative: if Scaleway has upgraded PHP since, update the package for a newer catalogue. | |
| 45 | + | |
| 46 | +The [Emulator](local-development.md) runs on your local PHP, which may load extensions or versions the Function Runtime lacks: an application working locally can still fail to install on Scaleway, which is what this check catches. | |
| 47 | +A successful check covers declared Platform Requirements only: an extension used without being required is not checked, and calling a route after the deployment, as [Composer at deploy time](deployment.md#composer-at-deploy-time) shows, remains the proof that it works. | |
| new file mode 100644 | |||
| @@ -0,0 +1,47 @@ | |||
| 1 | +# Compatibility check | ||
| 2 | + | ||
| 3 | +```sh | ||
| 4 | +vendor/bin/scaleway-doctor --runtime=php84 | ||
| 5 | +``` | ||
| 6 | + | ||
| 7 | +A Platform Requirement (`php` or `ext-*`) the Function Runtime does not meet makes Scaleway's `composer install` fail at deploy time, without failing the deployment: every Invocation then answers a `500` (see [Composer at deploy time](deployment.md#composer-at-deploy-time)). | ||
| 8 | +`scaleway-doctor` checks, before you deploy, the Platform Requirements that install checks, against the Function Runtime the function declares, named by `--runtime` (`php84` or `php85`). | ||
| 9 | +It never guesses it from your local PHP. | ||
| 10 | +It reads `composer.json` and `composer.lock`, needs neither Scaleway credentials nor network access, and refuses a stale lock as [`scaleway-package`](packaging.md) does. | ||
| 11 | + | ||
| 12 | +It checks what `composer install --no-dev` checks on Scaleway: | ||
| 13 | + | ||
| 14 | +- the root requirements the lock records, and those of every locked production package, development ones excluded; | ||
| 15 | +- each one met by the Function Runtime, or by a `provide` or `replace` of the application or of a locked package; | ||
| 16 | +- constraints evaluated by Composer's own engine, against the PHP and extension versions Composer would see on Scaleway. | ||
| 17 | + | ||
| 18 | +Each requirement is: | ||
| 19 | + | ||
| 20 | +- **satisfied**, when the measured version matches; | ||
| 21 | +- **incompatible**, when the extension is not loaded, or the measured version of PHP or of the extension does not match; | ||
| 22 | +- **unknown**, for the platform packages the catalogue does not measure, as `lib-icu` or `php-64bit`. | ||
| 23 | + | ||
| 24 | +Composer's own APIs (`composer`, `composer-plugin-api`, `composer-runtime-api`) are not checked: Scaleway installs with Composer 2. | ||
| 25 | + | ||
| 26 | +The report, on stderr, lists the incompatible and unknown requirements, with what declares them and what the Function Runtime provides: | ||
| 27 | + | ||
| 28 | +```text | ||
| 29 | +INCOMPATIBLE ext-foo * required by acme/bar v2.1.0 php84: not loaded (measured 2026-11-22) | ||
| 30 | + php85 meets it: deploy on php85, or use Serverless Containers for custom extensions or versions. | ||
| 31 | +UNKNOWN lib-icu >=72 required by symfony/intl v8.0.3 not in the Function Runtime Catalogue | ||
| 32 | + | ||
| 33 | +48 satisfied, 1 unknown, 1 incompatible on php84 (measured 2026-11-22) | ||
| 34 | +This covers declared Platform Requirements only, not whether the application runs. | ||
| 35 | +``` | ||
| 36 | + | ||
| 37 | +It exits with `0` when every requirement is satisfied or only unknowns remain, and with `1` on an incompatible requirement or an invalid input. | ||
| 38 | +For an incompatible requirement, it names the other Function Runtimes that meet it, if any. | ||
| 39 | +Otherwise, custom extensions or versions need [Serverless Containers](https://www.scaleway.com/en/serverless-containers/), which this package does not target. | ||
| 40 | + | ||
| 41 | +What each Function Runtime provides comes from the Function Runtime Catalogue shipped with the package, [resources/function-runtimes.php](../resources/function-runtimes.php). | ||
| 42 | +It holds measurements only, made on Scaleway with the [probe](../probe), each a complete inventory: an extension it does not list is not loaded. | ||
| 43 | +A measurement describes the Function Runtime on its date, which the report shows, not a guarantee that Scaleway keeps the same versions. | ||
| 44 | +The measured PHP patch version is authoritative: if Scaleway has upgraded PHP since, update the package for a newer catalogue. | ||
| 45 | + | ||
| 46 | +The [Emulator](local-development.md) runs on your local PHP, which may load extensions or versions the Function Runtime lacks: an application working locally can still fail to install on Scaleway, which is what this check catches. | ||
| 47 | +A successful check covers declared Platform Requirements only: an extension used without being required is not checked, and calling a route after the deployment, as [Composer at deploy time](deployment.md#composer-at-deploy-time) shows, remains the proof that it works. | ||
added
docs/configuration.md +102 -0 | new file mode 100644 | ||
| @@ -0,0 +1,102 @@ | ||
| 1 | +# Configuration | |
| 2 | + | |
| 3 | +## Function handler | |
| 4 | + | |
| 5 | +Set the handler of the Scaleway function to `handler.handle`. | |
| 6 | + | |
| 7 | +## Front Controller | |
| 8 | + | |
| 9 | +The Front Controller defaults to `public/index.php`, relative to the project dir. | |
| 10 | +Choose another one with the `front_controller` runtime option, in `composer.json`: | |
| 11 | + | |
| 12 | +```json | |
| 13 | +{ | |
| 14 | + "extra": { | |
| 15 | + "runtime": { | |
| 16 | + "front_controller": "public/api.php" | |
| 17 | + } | |
| 18 | + } | |
| 19 | +} | |
| 20 | +``` | |
| 21 | + | |
| 22 | +Or with the `APP_RUNTIME_OPTIONS` environment variable, a JSON object that wins over `extra.runtime`: | |
| 23 | + | |
| 24 | +```sh | |
| 25 | +APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | |
| 26 | +``` | |
| 27 | + | |
| 28 | +The other `SymfonyRuntime` options (`project_dir`, `env_var_name`, `dotenv_path`...) work as usual. | |
| 29 | +`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`. | |
| 30 | + | |
| 31 | +## Environment variables | |
| 32 | + | |
| 33 | +Set these on the function, in production: | |
| 34 | + | |
| 35 | +| Variable | Kind | Why | | |
| 36 | +| --- | --- | --- | | |
| 37 | +| `APP_SECRET` | Secret | Symfony's `kernel.secret`, used to sign URLs, cookies and CSRF tokens. | | |
| 38 | +| `SCALEWAY_HOST` | Plain | The public host of the function, for absolute URLs, see [Host](#host). | | |
| 39 | +| `SCALEWAY_CRON_SECRET` | Secret | Only to run console commands from CRON triggers, see [Command Invocations](cron-and-commands.md#command-invocations). | | |
| 40 | +| `APP_ENV` | Plain | Only to run another env than `prod`, see below. | | |
| 41 | + | |
| 42 | +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. | |
| 43 | +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](adr/0006-default-to-the-prod-env.md)). | |
| 44 | +Only an `APP_ENV` variable of the function, or the `env` runtime option, picks another env. | |
| 45 | +`APP_DEBUG` follows: off in `prod`, unless set by the function's environment or a `.env` file. | |
| 46 | +The Emulator runs `dev` instead, unless it is started with an `APP_ENV`. | |
| 47 | + | |
| 48 | +For every other variable, real environment variables win over `.env` files, as usual with Symfony's Dotenv. | |
| 49 | +`.env.local`, `.env.local.php` and `.env.*.local` are never shipped. | |
| 50 | + | |
| 51 | +## Host | |
| 52 | + | |
| 53 | +No `Host` header reaches the function, so the runtime cannot know the domain it is called on. | |
| 54 | +Every Request gets the host of the `host` runtime option, which defaults to the `SCALEWAY_HOST` environment variable, then to `localhost`: | |
| 55 | + | |
| 56 | +```sh | |
| 57 | +SCALEWAY_HOST=api.example.com | |
| 58 | +``` | |
| 59 | + | |
| 60 | +The scheme comes from the platform's `X-Forwarded-Proto` (`https` for HTTP calls), the port is the scheme's default. | |
| 61 | +Absolute URLs (`UrlGeneratorInterface::ABSOLUTE_URL`, signed URLs, redirects built from the Request) are only right once the host is set. | |
| 62 | +Set it to the function's domain (its `domain_name` on Scaleway) or to its custom domain. | |
| 63 | +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. | |
| 64 | +An application configuring `framework.trusted_hosts` answers every Request with a 400 until the host is set to one of its trusted hosts. | |
| 65 | +Both were [measured on Scaleway](probe-results.md#absolute-urls), forged `X-Forwarded-Host` and `Forwarded` headers never changing the host. | |
| 66 | + | |
| 67 | +## Cache and writable directories | |
| 68 | + | |
| 69 | +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. | |
| 70 | +To pay it at deploy time instead, warm the cache from a Composer script, which Scaleway runs after installing the dependencies: | |
| 71 | + | |
| 72 | +```json | |
| 73 | +{ | |
| 74 | + "scripts": { | |
| 75 | + "post-install-cmd": ["@php bin/console cache:warmup --env=prod"] | |
| 76 | + } | |
| 77 | +} | |
| 78 | +``` | |
| 79 | + | |
| 80 | +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. | |
| 81 | + | |
| 82 | +> [!WARNING] | |
| 83 | +> Symfony Flex's `auto-scripts` also run at deploy time, with the `APP_ENV` of the shipped `.env`, usually `dev`: `cache:clear` then fails silently, its dev bundles not being installed with `--no-dev`. | |
| 84 | +> Make them env-explicit (`"cache:clear --env=prod": "symfony-cmd"`), or remove `cache:clear` from them and warm the cache as above. | |
| 85 | + | |
| 86 | +When the project's `var/` directory (or the project dir, without `var/`) is not writable, the runtime sets, unless your application already did: | |
| 87 | + | |
| 88 | +- `APP_CACHE_DIR` to `<temp dir>/cache` and `APP_LOG_DIR` to `<temp dir>/log`; | |
| 89 | +- `APP_BUILD_DIR` to `var/cache`, only when `var/cache/<env>` holds a container warmed before, so that it is used as is. | |
| 90 | + | |
| 91 | +Kernels using `MicroKernelTrait` read these variables. | |
| 92 | +Other Kernels must override `getCacheDir()`, `getBuildDir()` and `getLogDir()` themselves. | |
| 93 | +Logs written to files are lost with the instance: send them to `php://stderr` instead, which the runtime also uses for its own errors. | |
| 94 | + | |
| 95 | +## Errors | |
| 96 | + | |
| 97 | +An exception escaping the Application (a Kernel failing to boot, an unsupported Front Controller...) is logged to stderr ([Logs](logs.md)) and answered with a 500. | |
| 98 | +Its body is `Internal Server Error`, or the full exception when `APP_DEBUG` is true. | |
| 99 | +A Kernel that failed to boot is built again from scratch on the next Invocation. | |
| 100 | + | |
| 101 | +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. | |
| 102 | +Outside a web SAPI, FrameworkBundle would pick its CLI error renderer instead, which dumps the exception even in `prod`. | |
| new file mode 100644 | |||
| @@ -0,0 +1,102 @@ | |||
| 1 | +# Configuration | ||
| 2 | + | ||
| 3 | +## Function handler | ||
| 4 | + | ||
| 5 | +Set the handler of the Scaleway function to `handler.handle`. | ||
| 6 | + | ||
| 7 | +## Front Controller | ||
| 8 | + | ||
| 9 | +The Front Controller defaults to `public/index.php`, relative to the project dir. | ||
| 10 | +Choose another one with the `front_controller` runtime option, in `composer.json`: | ||
| 11 | + | ||
| 12 | +```json | ||
| 13 | +{ | ||
| 14 | + "extra": { | ||
| 15 | + "runtime": { | ||
| 16 | + "front_controller": "public/api.php" | ||
| 17 | + } | ||
| 18 | + } | ||
| 19 | +} | ||
| 20 | +``` | ||
| 21 | + | ||
| 22 | +Or with the `APP_RUNTIME_OPTIONS` environment variable, a JSON object that wins over `extra.runtime`: | ||
| 23 | + | ||
| 24 | +```sh | ||
| 25 | +APP_RUNTIME_OPTIONS='{"front_controller":"bin/console"}' | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +The other `SymfonyRuntime` options (`project_dir`, `env_var_name`, `dotenv_path`...) work as usual. | ||
| 29 | +`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`. | ||
| 30 | + | ||
| 31 | +## Environment variables | ||
| 32 | + | ||
| 33 | +Set these on the function, in production: | ||
| 34 | + | ||
| 35 | +| Variable | Kind | Why | | ||
| 36 | +| --- | --- | --- | | ||
| 37 | +| `APP_SECRET` | Secret | Symfony's `kernel.secret`, used to sign URLs, cookies and CSRF tokens. | | ||
| 38 | +| `SCALEWAY_HOST` | Plain | The public host of the function, for absolute URLs, see [Host](#host). | | ||
| 39 | +| `SCALEWAY_CRON_SECRET` | Secret | Only to run console commands from CRON triggers, see [Command Invocations](cron-and-commands.md#command-invocations). | | ||
| 40 | +| `APP_ENV` | Plain | Only to run another env than `prod`, see below. | | ||
| 41 | + | ||
| 42 | +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. | ||
| 43 | +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](adr/0006-default-to-the-prod-env.md)). | ||
| 44 | +Only an `APP_ENV` variable of the function, or the `env` runtime option, picks another env. | ||
| 45 | +`APP_DEBUG` follows: off in `prod`, unless set by the function's environment or a `.env` file. | ||
| 46 | +The Emulator runs `dev` instead, unless it is started with an `APP_ENV`. | ||
| 47 | + | ||
| 48 | +For every other variable, real environment variables win over `.env` files, as usual with Symfony's Dotenv. | ||
| 49 | +`.env.local`, `.env.local.php` and `.env.*.local` are never shipped. | ||
| 50 | + | ||
| 51 | +## Host | ||
| 52 | + | ||
| 53 | +No `Host` header reaches the function, so the runtime cannot know the domain it is called on. | ||
| 54 | +Every Request gets the host of the `host` runtime option, which defaults to the `SCALEWAY_HOST` environment variable, then to `localhost`: | ||
| 55 | + | ||
| 56 | +```sh | ||
| 57 | +SCALEWAY_HOST=api.example.com | ||
| 58 | +``` | ||
| 59 | + | ||
| 60 | +The scheme comes from the platform's `X-Forwarded-Proto` (`https` for HTTP calls), the port is the scheme's default. | ||
| 61 | +Absolute URLs (`UrlGeneratorInterface::ABSOLUTE_URL`, signed URLs, redirects built from the Request) are only right once the host is set. | ||
| 62 | +Set it to the function's domain (its `domain_name` on Scaleway) or to its custom domain. | ||
| 63 | +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. | ||
| 64 | +An application configuring `framework.trusted_hosts` answers every Request with a 400 until the host is set to one of its trusted hosts. | ||
| 65 | +Both were [measured on Scaleway](probe-results.md#absolute-urls), forged `X-Forwarded-Host` and `Forwarded` headers never changing the host. | ||
| 66 | + | ||
| 67 | +## Cache and writable directories | ||
| 68 | + | ||
| 69 | +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. | ||
| 70 | +To pay it at deploy time instead, warm the cache from a Composer script, which Scaleway runs after installing the dependencies: | ||
| 71 | + | ||
| 72 | +```json | ||
| 73 | +{ | ||
| 74 | + "scripts": { | ||
| 75 | + "post-install-cmd": ["@php bin/console cache:warmup --env=prod"] | ||
| 76 | + } | ||
| 77 | +} | ||
| 78 | +``` | ||
| 79 | + | ||
| 80 | +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. | ||
| 81 | + | ||
| 82 | +> [!WARNING] | ||
| 83 | +> Symfony Flex's `auto-scripts` also run at deploy time, with the `APP_ENV` of the shipped `.env`, usually `dev`: `cache:clear` then fails silently, its dev bundles not being installed with `--no-dev`. | ||
| 84 | +> Make them env-explicit (`"cache:clear --env=prod": "symfony-cmd"`), or remove `cache:clear` from them and warm the cache as above. | ||
| 85 | + | ||
| 86 | +When the project's `var/` directory (or the project dir, without `var/`) is not writable, the runtime sets, unless your application already did: | ||
| 87 | + | ||
| 88 | +- `APP_CACHE_DIR` to `<temp dir>/cache` and `APP_LOG_DIR` to `<temp dir>/log`; | ||
| 89 | +- `APP_BUILD_DIR` to `var/cache`, only when `var/cache/<env>` holds a container warmed before, so that it is used as is. | ||
| 90 | + | ||
| 91 | +Kernels using `MicroKernelTrait` read these variables. | ||
| 92 | +Other Kernels must override `getCacheDir()`, `getBuildDir()` and `getLogDir()` themselves. | ||
| 93 | +Logs written to files are lost with the instance: send them to `php://stderr` instead, which the runtime also uses for its own errors. | ||
| 94 | + | ||
| 95 | +## Errors | ||
| 96 | + | ||
| 97 | +An exception escaping the Application (a Kernel failing to boot, an unsupported Front Controller...) is logged to stderr ([Logs](logs.md)) and answered with a 500. | ||
| 98 | +Its body is `Internal Server Error`, or the full exception when `APP_DEBUG` is true. | ||
| 99 | +A Kernel that failed to boot is built again from scratch on the next Invocation. | ||
| 100 | + | ||
| 101 | +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. | ||
| 102 | +Outside a web SAPI, FrameworkBundle would pick its CLI error renderer instead, which dumps the exception even in `prod`. | ||
added
docs/cron-and-commands.md +60 -0 | new file mode 100644 | ||
| @@ -0,0 +1,60 @@ | ||
| 1 | +# CRON triggers and Command Invocations | |
| 2 | + | |
| 3 | +## CRON triggers | |
| 4 | + | |
| 5 | +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`). | |
| 6 | +With a Kernel, handle it like any route: | |
| 7 | + | |
| 8 | +```php | |
| 9 | +#[Route('/', methods: ['POST'])] | |
| 10 | +public function cron(Request $request): Response | |
| 11 | +{ | |
| 12 | + $args = $request->toArray(); // the trigger's arguments | |
| 13 | + // ... | |
| 14 | +} | |
| 15 | +``` | |
| 16 | + | |
| 17 | +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. | |
| 18 | + | |
| 19 | +## Command Invocations | |
| 20 | + | |
| 21 | +A CRON trigger may run a console command instead, through the Console Application of the same Kernel. | |
| 22 | + | |
| 23 | +1. Generate a random secret, for instance with `openssl rand -hex 32`. | |
| 24 | +2. Set it as the `SCALEWAY_CRON_SECRET` secret environment variable of the function. | |
| 25 | +3. Give the CRON trigger these arguments: | |
| 26 | + | |
| 27 | +```json | |
| 28 | +{"command": "app:sync", "args": {"source": "s3", "--force": true, "--tag": ["a", "b"]}, "secret": "<SCALEWAY_CRON_SECRET>"} | |
| 29 | +``` | |
| 30 | + | |
| 31 | +`args` is optional, and maps argument names, and option names with their dashes, to values, as Symfony's `ArrayInput` does. | |
| 32 | +The command runs without interaction: questions get their default answer. | |
| 33 | +Services are reset around each command, so it shares no state with the Invocations before and after it. | |
| 34 | + | |
| 35 | +| Outcome | Function Response | | |
| 36 | +| --- | --- | | |
| 37 | +| Exit code 0 | 200, the command output as plain text body | | |
| 38 | +| Any other exit code | 500, the command output as plain text body, also logged to stderr | | |
| 39 | +| `args` not a JSON object | 500 | | |
| 40 | +| 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 | | |
| 41 | + | |
| 42 | +Nothing shows the Function Response of a CRON Invocation, and a failed one is not retried: the [logs](logs.md) are where the outcome of a command shows up, so log what it does ([measured](probe-results.md#cron-invocations)). | |
| 43 | + | |
| 44 | +## Security model | |
| 45 | + | |
| 46 | +A body only becomes a Command Invocation when both hold: | |
| 47 | + | |
| 48 | +- the Event carries neither `X-Real-Ip` nor `X-Envoy-External-Address`, which the platform sets on every HTTP call, overwriting what the client sends, and which CRON Events lack; | |
| 49 | +- its `secret` matches `SCALEWAY_CRON_SECRET`, compared in constant time. | |
| 50 | + | |
| 51 | +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). | |
| 52 | +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. | |
| 53 | +The first check relies on undocumented platform behaviour, which is why the secret stays required. | |
| 54 | + | |
| 55 | +Keep in mind that: | |
| 56 | + | |
| 57 | +- 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; | |
| 58 | +- rotating it means updating the variable and every CRON trigger together. | |
| 59 | + | |
| 60 | +See [ADR 0005](adr/0005-authenticate-command-invocations-with-a-shared-secret.md) for the alternatives considered. | |
| new file mode 100644 | |||
| @@ -0,0 +1,60 @@ | |||
| 1 | +# CRON triggers and Command Invocations | ||
| 2 | + | ||
| 3 | +## CRON triggers | ||
| 4 | + | ||
| 5 | +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`). | ||
| 6 | +With a Kernel, handle it like any route: | ||
| 7 | + | ||
| 8 | +```php | ||
| 9 | +#[Route('/', methods: ['POST'])] | ||
| 10 | +public function cron(Request $request): Response | ||
| 11 | +{ | ||
| 12 | + $args = $request->toArray(); // the trigger's arguments | ||
| 13 | + // ... | ||
| 14 | +} | ||
| 15 | +``` | ||
| 16 | + | ||
| 17 | +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. | ||
| 18 | + | ||
| 19 | +## Command Invocations | ||
| 20 | + | ||
| 21 | +A CRON trigger may run a console command instead, through the Console Application of the same Kernel. | ||
| 22 | + | ||
| 23 | +1. Generate a random secret, for instance with `openssl rand -hex 32`. | ||
| 24 | +2. Set it as the `SCALEWAY_CRON_SECRET` secret environment variable of the function. | ||
| 25 | +3. Give the CRON trigger these arguments: | ||
| 26 | + | ||
| 27 | +```json | ||
| 28 | +{"command": "app:sync", "args": {"source": "s3", "--force": true, "--tag": ["a", "b"]}, "secret": "<SCALEWAY_CRON_SECRET>"} | ||
| 29 | +``` | ||
| 30 | + | ||
| 31 | +`args` is optional, and maps argument names, and option names with their dashes, to values, as Symfony's `ArrayInput` does. | ||
| 32 | +The command runs without interaction: questions get their default answer. | ||
| 33 | +Services are reset around each command, so it shares no state with the Invocations before and after it. | ||
| 34 | + | ||
| 35 | +| Outcome | Function Response | | ||
| 36 | +| --- | --- | | ||
| 37 | +| Exit code 0 | 200, the command output as plain text body | | ||
| 38 | +| Any other exit code | 500, the command output as plain text body, also logged to stderr | | ||
| 39 | +| `args` not a JSON object | 500 | | ||
| 40 | +| 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 | | ||
| 41 | + | ||
| 42 | +Nothing shows the Function Response of a CRON Invocation, and a failed one is not retried: the [logs](logs.md) are where the outcome of a command shows up, so log what it does ([measured](probe-results.md#cron-invocations)). | ||
| 43 | + | ||
| 44 | +## Security model | ||
| 45 | + | ||
| 46 | +A body only becomes a Command Invocation when both hold: | ||
| 47 | + | ||
| 48 | +- the Event carries neither `X-Real-Ip` nor `X-Envoy-External-Address`, which the platform sets on every HTTP call, overwriting what the client sends, and which CRON Events lack; | ||
| 49 | +- its `secret` matches `SCALEWAY_CRON_SECRET`, compared in constant time. | ||
| 50 | + | ||
| 51 | +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). | ||
| 52 | +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. | ||
| 53 | +The first check relies on undocumented platform behaviour, which is why the secret stays required. | ||
| 54 | + | ||
| 55 | +Keep in mind that: | ||
| 56 | + | ||
| 57 | +- 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; | ||
| 58 | +- rotating it means updating the variable and every CRON trigger together. | ||
| 59 | + | ||
| 60 | +See [ADR 0005](adr/0005-authenticate-command-invocations-with-a-shared-secret.md) for the alternatives considered. | ||
added
docs/deployment.md +28 -0 | new file mode 100644 | ||
| @@ -0,0 +1,28 @@ | ||
| 1 | +# Deployment | |
| 2 | + | |
| 3 | +[example/terraform](../example/terraform/main.tf) deploys the [example application](../example) 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. | |
| 4 | +Its [README](../example/README.md#deploy-it) gives the commands. | |
| 5 | +That Terraform code was written against the `scaleway/scaleway` provider v2.92 documentation and has never been applied; the [probe](../probe/terraform/main.tf)'s, written the same way, has. | |
| 6 | + | |
| 7 | +Redeploy by running `scaleway-package` again, then `terraform apply`. | |
| 8 | +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. | |
| 9 | + | |
| 10 | +## Composer at deploy time | |
| 11 | + | |
| 12 | +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/`. | |
| 13 | +Every locked package must therefore be downloadable from Scaleway, and the function's environment variables are not available to Composer scripts. | |
| 14 | +The lock must also install on the function's runtime: set `config.platform.php` in `composer.json` to its PHP version (`8.4` for `php84`, `8.5` for `php85`) so that `composer update` resolves for it. | |
| 15 | +`config.platform` only steers Composer's resolution: run the [compatibility check](compatibility-check.md), or package with `--runtime`, to check the lock against what Scaleway provides. | |
| 16 | +A failing install or script does not fail the deployment, and Scaleway serves the new code anyway, never the previous version ([measured](probe-results.md#failed-scripts-and-installs)): | |
| 17 | + | |
| 18 | +- a failing script runs once `vendor/` and its autoloader are complete, so the new code works, without what the script should have done (a warmed cache, generated files...); | |
| 19 | +- a failing install, from a package Scaleway cannot download or a platform requirement its runtime does not meet, leaves no `vendor/` at all: every Invocation answers a `500`, the first one of each instance logging `Failed to open stream` for `vendor/autoload.php` on stdout, the next ones `Class "JDecool\ScalewayRuntime\Handler" not found` on stderr. | |
| 20 | + | |
| 21 | +Neither shows anywhere: the function is `ready`, its `error_message` and `build_message` stay empty, and Composer's output reaches neither Cockpit nor `scw`. | |
| 22 | +So after each deploy, call a route that should answer a `200`, and check the function's [logs](logs.md) if it does not: | |
| 23 | + | |
| 24 | +```sh | |
| 25 | +curl -sS -o /dev/null -w '%{http_code}\n' "https://$(scw function function list name=<function name> -o json | jq -r '.[0].domain_name')/<route>" | |
| 26 | +``` | |
| 27 | + | |
| 28 | +Keep deploy-time scripts to what the application can do without, as a cache warmup the first Invocation redoes, and run whatever it needs at runtime instead. | |
| new file mode 100644 | |||
| @@ -0,0 +1,28 @@ | |||
| 1 | +# Deployment | ||
| 2 | + | ||
| 3 | +[example/terraform](../example/terraform/main.tf) deploys the [example application](../example) 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. | ||
| 4 | +Its [README](../example/README.md#deploy-it) gives the commands. | ||
| 5 | +That Terraform code was written against the `scaleway/scaleway` provider v2.92 documentation and has never been applied; the [probe](../probe/terraform/main.tf)'s, written the same way, has. | ||
| 6 | + | ||
| 7 | +Redeploy by running `scaleway-package` again, then `terraform apply`. | ||
| 8 | +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. | ||
| 9 | + | ||
| 10 | +## Composer at deploy time | ||
| 11 | + | ||
| 12 | +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/`. | ||
| 13 | +Every locked package must therefore be downloadable from Scaleway, and the function's environment variables are not available to Composer scripts. | ||
| 14 | +The lock must also install on the function's runtime: set `config.platform.php` in `composer.json` to its PHP version (`8.4` for `php84`, `8.5` for `php85`) so that `composer update` resolves for it. | ||
| 15 | +`config.platform` only steers Composer's resolution: run the [compatibility check](compatibility-check.md), or package with `--runtime`, to check the lock against what Scaleway provides. | ||
| 16 | +A failing install or script does not fail the deployment, and Scaleway serves the new code anyway, never the previous version ([measured](probe-results.md#failed-scripts-and-installs)): | ||
| 17 | + | ||
| 18 | +- a failing script runs once `vendor/` and its autoloader are complete, so the new code works, without what the script should have done (a warmed cache, generated files...); | ||
| 19 | +- a failing install, from a package Scaleway cannot download or a platform requirement its runtime does not meet, leaves no `vendor/` at all: every Invocation answers a `500`, the first one of each instance logging `Failed to open stream` for `vendor/autoload.php` on stdout, the next ones `Class "JDecool\ScalewayRuntime\Handler" not found` on stderr. | ||
| 20 | + | ||
| 21 | +Neither shows anywhere: the function is `ready`, its `error_message` and `build_message` stay empty, and Composer's output reaches neither Cockpit nor `scw`. | ||
| 22 | +So after each deploy, call a route that should answer a `200`, and check the function's [logs](logs.md) if it does not: | ||
| 23 | + | ||
| 24 | +```sh | ||
| 25 | +curl -sS -o /dev/null -w '%{http_code}\n' "https://$(scw function function list name=<function name> -o json | jq -r '.[0].domain_name')/<route>" | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +Keep deploy-time scripts to what the application can do without, as a cache warmup the first Invocation redoes, and run whatever it needs at runtime instead. | ||
added
docs/local-development.md +50 -0 | new file mode 100644 | ||
| @@ -0,0 +1,50 @@ | ||
| 1 | +# Local development with the Emulator | |
| 2 | + | |
| 3 | +```sh | |
| 4 | +vendor/bin/scaleway-serve [127.0.0.1:8000] | |
| 5 | +``` | |
| 6 | + | |
| 7 | +The Emulator turns each HTTP request into an Event, calls your `handle()` and turns the Function Response back into the HTTP response. | |
| 8 | +`handle()` runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code. | |
| 9 | +It sets `APP_ENV=dev` unless started with an `APP_ENV`, as the deployed function defaults to `prod`. | |
| 10 | +A crashed process is replaced by a fresh one, as Scaleway starts a new instance. | |
| 11 | + | |
| 12 | +PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory. | |
| 13 | + | |
| 14 | +The Event and the context are built the way the platform builds them ([measured](probe-results.md)): | |
| 15 | + | |
| 16 | +- the `httpMethod`, `queryStringParameters` (sorted by key, the last value of a repeated key winning, `[]` without query string) and other keys of the platform; | |
| 17 | +- header names in `Title-Case`, repeated headers joined with `, `, no `Host`; | |
| 18 | +- `X-Real-Ip`, `X-Envoy-External-Address`, `X-Request-Id` and `X-Forwarded-Proto: https` set whatever the client sends, the client's `X-Forwarded-For` kept in front of its address, its `X-Forwarded-Host` passed through; | |
| 19 | +- empty, multipart and non UTF-8 bodies base64-encoded with `isBase64Encoded: true`, text bodies without the flag. | |
| 20 | + | |
| 21 | +So the Requests are `https`, and their host is `localhost` unless you set `SCALEWAY_HOST`, as on the platform. | |
| 22 | + | |
| 23 | +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: | |
| 24 | + | |
| 25 | +```sh | |
| 26 | +curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"job": "cleanup"}' | |
| 27 | +``` | |
| 28 | + | |
| 29 | +Simulate a Command Invocation by starting the Emulator with `SCALEWAY_CRON_SECRET` set, and sending the [Command Invocation body](cron-and-commands.md#command-invocations) the same way: | |
| 30 | + | |
| 31 | +```sh | |
| 32 | +SCALEWAY_CRON_SECRET=local-secret vendor/bin/scaleway-serve | |
| 33 | +curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}' | |
| 34 | +``` | |
| 35 | + | |
| 36 | +To run what gets deployed, install the zip the way Scaleway does, without the function's variables, then serve it in `prod`: | |
| 37 | + | |
| 38 | +```sh | |
| 39 | +vendor/bin/scaleway-package | |
| 40 | +unzip -q function.zip -d /tmp/function | |
| 41 | +composer install --working-dir=/tmp/function --no-dev | |
| 42 | +APP_ENV=prod APP_SECRET=local php /tmp/function/vendor/bin/scaleway-serve | |
| 43 | +``` | |
| 44 | + | |
| 45 | +The [example](../example/README.md#run-it-locally)'s `e2e/deploy-locally.sh` does the same with the runtime of this repository. | |
| 46 | + | |
| 47 | +## Windows | |
| 48 | + | |
| 49 | +`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. | |
| 50 | +Without the `pcntl` extension, stopping the Emulator with `kill` may leave its PHP processes running. | |
| new file mode 100644 | |||
| @@ -0,0 +1,50 @@ | |||
| 1 | +# Local development with the Emulator | ||
| 2 | + | ||
| 3 | +```sh | ||
| 4 | +vendor/bin/scaleway-serve [127.0.0.1:8000] | ||
| 5 | +``` | ||
| 6 | + | ||
| 7 | +The Emulator turns each HTTP request into an Event, calls your `handle()` and turns the Function Response back into the HTTP response. | ||
| 8 | +`handle()` runs in one long-lived PHP process, as in a Warm Process: restart the Emulator after changing code. | ||
| 9 | +It sets `APP_ENV=dev` unless started with an `APP_ENV`, as the deployed function defaults to `prod`. | ||
| 10 | +A crashed process is replaced by a fresh one, as Scaleway starts a new instance. | ||
| 11 | + | ||
| 12 | +PHP's built-in server receives the requests, and forwards the Events to that process over a Unix socket in a private temporary directory. | ||
| 13 | + | ||
| 14 | +The Event and the context are built the way the platform builds them ([measured](probe-results.md)): | ||
| 15 | + | ||
| 16 | +- the `httpMethod`, `queryStringParameters` (sorted by key, the last value of a repeated key winning, `[]` without query string) and other keys of the platform; | ||
| 17 | +- header names in `Title-Case`, repeated headers joined with `, `, no `Host`; | ||
| 18 | +- `X-Real-Ip`, `X-Envoy-External-Address`, `X-Request-Id` and `X-Forwarded-Proto: https` set whatever the client sends, the client's `X-Forwarded-For` kept in front of its address, its `X-Forwarded-Host` passed through; | ||
| 19 | +- empty, multipart and non UTF-8 bodies base64-encoded with `isBase64Encoded: true`, text bodies without the flag. | ||
| 20 | + | ||
| 21 | +So the Requests are `https`, and their host is `localhost` unless you set `SCALEWAY_HOST`, as on the platform. | ||
| 22 | + | ||
| 23 | +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: | ||
| 24 | + | ||
| 25 | +```sh | ||
| 26 | +curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"job": "cleanup"}' | ||
| 27 | +``` | ||
| 28 | + | ||
| 29 | +Simulate a Command Invocation by starting the Emulator with `SCALEWAY_CRON_SECRET` set, and sending the [Command Invocation body](cron-and-commands.md#command-invocations) the same way: | ||
| 30 | + | ||
| 31 | +```sh | ||
| 32 | +SCALEWAY_CRON_SECRET=local-secret vendor/bin/scaleway-serve | ||
| 33 | +curl -X POST http://127.0.0.1:8000/_scaleway/cron --data '{"command": "app:greet", "args": {"name": "Scaleway"}, "secret": "local-secret"}' | ||
| 34 | +``` | ||
| 35 | + | ||
| 36 | +To run what gets deployed, install the zip the way Scaleway does, without the function's variables, then serve it in `prod`: | ||
| 37 | + | ||
| 38 | +```sh | ||
| 39 | +vendor/bin/scaleway-package | ||
| 40 | +unzip -q function.zip -d /tmp/function | ||
| 41 | +composer install --working-dir=/tmp/function --no-dev | ||
| 42 | +APP_ENV=prod APP_SECRET=local php /tmp/function/vendor/bin/scaleway-serve | ||
| 43 | +``` | ||
| 44 | + | ||
| 45 | +The [example](../example/README.md#run-it-locally)'s `e2e/deploy-locally.sh` does the same with the runtime of this repository. | ||
| 46 | + | ||
| 47 | +## Windows | ||
| 48 | + | ||
| 49 | +`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. | ||
| 50 | +Without the `pcntl` extension, stopping the Emulator with `kill` may leave its PHP processes running. | ||
added
docs/logs.md +34 -0 | new file mode 100644 | ||
| @@ -0,0 +1,34 @@ | ||
| 1 | +# Logs | |
| 2 | + | |
| 3 | +Scaleway sends what the function writes to stdout and stderr to [Cockpit](https://www.scaleway.com/en/docs/cockpit/), in the project's `Scaleway Logs` data source, about 2 seconds after it is written. | |
| 4 | +The runtime logs its own failures to stderr, as Monolog does with a `php://stderr` handler. | |
| 5 | +Without Monolog, Symfony's fallback logger writes to stderr too, but from the `error` level only: lower it as the [example](../example/config/services.yaml) does. | |
| 6 | +Each line is one log entry: a stack trace spans one entry per line, and a line over 16 KiB is split into 16 KiB entries and cut after 64 KiB. | |
| 7 | +Every entry has the `debug` level, stderr ones included, except the continuations of a split line, whose level is `unknown`: filter on the `stream` field instead. | |
| 8 | +An entry looks like this, with the `resource_id` label holding the function's UUID: | |
| 9 | + | |
| 10 | +```json | |
| 11 | +{"message":"DEBUG - Invocation failed: RuntimeException: ... in /home/app/function/src/Kernel.php:12 source=user stream=stderr","stream":"stderr","resource_instance":"<namespace>-<function>-00001-deployment-<id>"} | |
| 12 | +``` | |
| 13 | + | |
| 14 | +In the console, open Cockpit's Grafana (`scw cockpit grafana get` prints its URL) and the `Serverless Functions Logs` dashboard, or Explore with the `Scaleway Logs` data source. | |
| 15 | + | |
| 16 | +From the command line, query Loki's HTTP API with a token that can only read logs: | |
| 17 | + | |
| 18 | +```sh | |
| 19 | +LOKI_URL=$(scw cockpit data-source list origin=scaleway types.0=logs -o json | jq -r '.[0].url') | |
| 20 | +FUNCTION_ID=$(scw function function list name=<function name> -o json | jq -r '.[0].id') | |
| 21 | +# The secret key is only shown at creation: keep it in memory rather than in a file that could get committed. | |
| 22 | +TOKEN=$(scw cockpit token create name=read-logs token-scopes.0=read_only_logs -o json) | |
| 23 | +LOKI_TOKEN=$(jq -r .secret_key <<< "$TOKEN") | |
| 24 | + | |
| 25 | +curl -sS -G "$LOKI_URL/loki/api/v1/query_range" -H "Authorization: Bearer $LOKI_TOKEN" \ | |
| 26 | + --data-urlencode "query={resource_id=\"$FUNCTION_ID\"} | json | stream=\"stderr\" | line_format \"{{.message}}\"" \ | |
| 27 | + --data-urlencode since=1h --data-urlencode limit=1000 \ | |
| 28 | + | jq -r '[.data.result[].values[]] | sort_by(.[0]) | .[][1]' | |
| 29 | + | |
| 30 | +scw cockpit token delete token-id=$(jq -r .id <<< "$TOKEN") | |
| 31 | +``` | |
| 32 | + | |
| 33 | +Token names are unique within a project: if a `read-logs` token was left behind, `token create` fails with `resource already exists`, so delete it first. | |
| 34 | +Without the `stream="stderr"` filter, the query also returns stdout and the platform's own lines (`Function Triggered: /`, `Function is now ready to serve requests!`). | |
| new file mode 100644 | |||
| @@ -0,0 +1,34 @@ | |||
| 1 | +# Logs | ||
| 2 | + | ||
| 3 | +Scaleway sends what the function writes to stdout and stderr to [Cockpit](https://www.scaleway.com/en/docs/cockpit/), in the project's `Scaleway Logs` data source, about 2 seconds after it is written. | ||
| 4 | +The runtime logs its own failures to stderr, as Monolog does with a `php://stderr` handler. | ||
| 5 | +Without Monolog, Symfony's fallback logger writes to stderr too, but from the `error` level only: lower it as the [example](../example/config/services.yaml) does. | ||
| 6 | +Each line is one log entry: a stack trace spans one entry per line, and a line over 16 KiB is split into 16 KiB entries and cut after 64 KiB. | ||
| 7 | +Every entry has the `debug` level, stderr ones included, except the continuations of a split line, whose level is `unknown`: filter on the `stream` field instead. | ||
| 8 | +An entry looks like this, with the `resource_id` label holding the function's UUID: | ||
| 9 | + | ||
| 10 | +```json | ||
| 11 | +{"message":"DEBUG - Invocation failed: RuntimeException: ... in /home/app/function/src/Kernel.php:12 source=user stream=stderr","stream":"stderr","resource_instance":"<namespace>-<function>-00001-deployment-<id>"} | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +In the console, open Cockpit's Grafana (`scw cockpit grafana get` prints its URL) and the `Serverless Functions Logs` dashboard, or Explore with the `Scaleway Logs` data source. | ||
| 15 | + | ||
| 16 | +From the command line, query Loki's HTTP API with a token that can only read logs: | ||
| 17 | + | ||
| 18 | +```sh | ||
| 19 | +LOKI_URL=$(scw cockpit data-source list origin=scaleway types.0=logs -o json | jq -r '.[0].url') | ||
| 20 | +FUNCTION_ID=$(scw function function list name=<function name> -o json | jq -r '.[0].id') | ||
| 21 | +# The secret key is only shown at creation: keep it in memory rather than in a file that could get committed. | ||
| 22 | +TOKEN=$(scw cockpit token create name=read-logs token-scopes.0=read_only_logs -o json) | ||
| 23 | +LOKI_TOKEN=$(jq -r .secret_key <<< "$TOKEN") | ||
| 24 | + | ||
| 25 | +curl -sS -G "$LOKI_URL/loki/api/v1/query_range" -H "Authorization: Bearer $LOKI_TOKEN" \ | ||
| 26 | + --data-urlencode "query={resource_id=\"$FUNCTION_ID\"} | json | stream=\"stderr\" | line_format \"{{.message}}\"" \ | ||
| 27 | + --data-urlencode since=1h --data-urlencode limit=1000 \ | ||
| 28 | + | jq -r '[.data.result[].values[]] | sort_by(.[0]) | .[][1]' | ||
| 29 | + | ||
| 30 | +scw cockpit token delete token-id=$(jq -r .id <<< "$TOKEN") | ||
| 31 | +``` | ||
| 32 | + | ||
| 33 | +Token names are unique within a project: if a `read-logs` token was left behind, `token create` fails with `resource already exists`, so delete it first. | ||
| 34 | +Without the `stream="stderr"` filter, the query also returns stdout and the platform's own lines (`Function Triggered: /`, `Function is now ready to serve requests!`). | ||
added
docs/packaging.md +29 -0 | new file mode 100644 | ||
| @@ -0,0 +1,29 @@ | ||
| 1 | +# Packaging | |
| 2 | + | |
| 3 | +```sh | |
| 4 | +vendor/bin/scaleway-package [--runtime=php84] [function.zip] | |
| 5 | +``` | |
| 6 | + | |
| 7 | +With `--runtime`, it first runs the [compatibility check](compatibility-check.md) against that Function Runtime, and refuses to build the zip on an incompatible Platform Requirement. | |
| 8 | + | |
| 9 | +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](adr/0008-let-scaleway-install-the-dependencies.md)). | |
| 10 | +Executable bits are kept, and symbolic links are followed: their target is zipped. | |
| 11 | + | |
| 12 | +It refuses to build the zip, as Scaleway would install something else or fail without failing the deployment, when: | |
| 13 | + | |
| 14 | +- `handler.php` or `composer.lock` is missing; | |
| 15 | +- `composer.lock` is not up to date with `composer.json`; | |
| 16 | +- `composer.json` declares a `path` repository, or `composer.lock` installs a package from a local path: Scaleway cannot resolve them. | |
| 17 | + | |
| 18 | +| Shipped | Not shipped | | |
| 19 | +| --- | --- | | |
| 20 | +| Your code, `composer.json`, `composer.lock`, `handler.php` | `vendor/` and `var/` (installed and built on the platform) | | |
| 21 | +| `.env`, `.env.prod`... as they are | `tests/`, `phpunit.xml(.dist)`, `.phpunit.cache`, `.phpunit.result.cache`, `.php-cs-fixer.cache` | | |
| 22 | +| | `.env.local`, `.env.local.php`, `.env.*.local` | | |
| 23 | +| | `.git`, `.idea`, `.vscode`, `.DS_Store`, `node_modules` anywhere | | |
| 24 | +| | `.terraform`, `*.tfstate`, `*.tfstate.*` anywhere (Terraform state holds secrets in clear) | | |
| 25 | + | |
| 26 | +The full list is `Packager::EXCLUDES` in [src/Packager.php](../src/Packager.php). | |
| 27 | + | |
| 28 | +Scaleway accepts zips up to 100 MiB, and up to 500 MiB of unzipped code ([limits](https://www.scaleway.com/en/docs/serverless-functions/reference-content/functions-limitations/)). | |
| 29 | +`scaleway-package` warns when the zip or its content exceeds either, but still writes it. | |
| new file mode 100644 | |||
| @@ -0,0 +1,29 @@ | |||
| 1 | +# Packaging | ||
| 2 | + | ||
| 3 | +```sh | ||
| 4 | +vendor/bin/scaleway-package [--runtime=php84] [function.zip] | ||
| 5 | +``` | ||
| 6 | + | ||
| 7 | +With `--runtime`, it first runs the [compatibility check](compatibility-check.md) against that Function Runtime, and refuses to build the zip on an incompatible Platform Requirement. | ||
| 8 | + | ||
| 9 | +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](adr/0008-let-scaleway-install-the-dependencies.md)). | ||
| 10 | +Executable bits are kept, and symbolic links are followed: their target is zipped. | ||
| 11 | + | ||
| 12 | +It refuses to build the zip, as Scaleway would install something else or fail without failing the deployment, when: | ||
| 13 | + | ||
| 14 | +- `handler.php` or `composer.lock` is missing; | ||
| 15 | +- `composer.lock` is not up to date with `composer.json`; | ||
| 16 | +- `composer.json` declares a `path` repository, or `composer.lock` installs a package from a local path: Scaleway cannot resolve them. | ||
| 17 | + | ||
| 18 | +| Shipped | Not shipped | | ||
| 19 | +| --- | --- | | ||
| 20 | +| Your code, `composer.json`, `composer.lock`, `handler.php` | `vendor/` and `var/` (installed and built on the platform) | | ||
| 21 | +| `.env`, `.env.prod`... as they are | `tests/`, `phpunit.xml(.dist)`, `.phpunit.cache`, `.phpunit.result.cache`, `.php-cs-fixer.cache` | | ||
| 22 | +| | `.env.local`, `.env.local.php`, `.env.*.local` | | ||
| 23 | +| | `.git`, `.idea`, `.vscode`, `.DS_Store`, `node_modules` anywhere | | ||
| 24 | +| | `.terraform`, `*.tfstate`, `*.tfstate.*` anywhere (Terraform state holds secrets in clear) | | ||
| 25 | + | ||
| 26 | +The full list is `Packager::EXCLUDES` in [src/Packager.php](../src/Packager.php). | ||
| 27 | + | ||
| 28 | +Scaleway accepts zips up to 100 MiB, and up to 500 MiB of unzipped code ([limits](https://www.scaleway.com/en/docs/serverless-functions/reference-content/functions-limitations/)). | ||
| 29 | +`scaleway-package` warns when the zip or its content exceeds either, but still writes it. | ||
added
docs/requests-and-responses.md +36 -0 | new file mode 100644 | ||
| @@ -0,0 +1,36 @@ | ||
| 1 | +# Requests and responses | |
| 2 | + | |
| 3 | +- **Superglobals**: `$_GET`, `$_POST`, `$_COOKIE`, `$_FILES` and the request entries of `$_SERVER` (`REQUEST_URI`, `HTTP_*`...) are not populated per Invocation. | |
| 4 | + Read the `Request` object instead; `Request::createFromGlobals()` does not describe the Invocation. | |
| 5 | +- **Output**: only the returned `Response` reaches the client. | |
| 6 | + `echo` outside the Response, `header()` and `http_response_code()` do not: Scaleway does not put stdout in the response body. | |
| 7 | +- **Query strings**: the Event carries `queryStringParameters` as a map, so a repeated key such as `a=1&a=2`, or `tags[]=a&tags[]=b`, reaches the Application with its last value only, and the keys arrive sorted, not in the order the client sent them. | |
| 8 | + Keys are then parsed like PHP does, so `a.b` becomes `a_b` and `a[b]` nests. | |
| 9 | +- **Form bodies**: `application/x-www-form-urlencoded` bodies are parsed for `POST`, `PUT`, `DELETE`, `PATCH` and `QUERY`, `multipart/form-data` only for `POST`, as PHP does. | |
| 10 | + Uploaded files are `UploadedFile` objects in test mode: `move()` works, `is_uploaded_file()` does not. | |
| 11 | +- **Cookies**: request cookie names are taken verbatim: unlike PHP's `$_COOKIE`, dots and spaces are not turned into underscores and `a[b]` does not nest. | |
| 12 | +- **Streaming**: `StreamedResponse` and `BinaryFileResponse` are buffered into one Function Response; Server-Sent Events and long downloads are not possible. | |
| 13 | + Bodies that are not valid UTF-8 are sent base64-encoded, and decoded by the platform. | |
| 14 | +- **PSR-15 responses** go through Symfony's `Response`, which adds `Cache-Control: no-cache, private` and `Date` when they are missing. | |
| 15 | +- **HEAD requests**: only FrameworkBundle's `ResponseListener` strips the body of a `HEAD` response, but the platform sends none anyway. | |
| 16 | +- **Request size**: Scaleway rejects request bodies over 6 MiB with a `413`, before they reach the function. | |
| 17 | +- **CORS**: Scaleway adds `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: Content-Type` to every response, whatever the Application sends. | |
| 18 | + 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. | |
| 19 | +- **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 a `500` whose body is `Error while executing function`. | |
| 20 | + | |
| 21 | +## Client IP and trusted proxies | |
| 22 | + | |
| 23 | +The runtime trusts no proxy, as clients can forge most forwarding headers on Scaleway ([ADR 0007](adr/0007-trust-only-headers-the-platform-overwrites.md)): | |
| 24 | + | |
| 25 | +| Request | From | Why | | |
| 26 | +| --- | --- | --- | | |
| 27 | +| `getClientIp()` | `X-Real-Ip`, `127.0.0.1` without it (CRON Invocations) | Set by the platform, whatever the client sends | | |
| 28 | +| `isSecure()`, `getScheme()`, port | `X-Forwarded-Proto`, the scheme's default port | Set by the platform (`https`, `http` for CRON Invocations) | | |
| 29 | +| `getHost()` | The [`host` option](configuration.md#host) | No `Host` header reaches the function | | |
| 30 | + | |
| 31 | +`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. | |
| 32 | +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. | |
| 33 | + | |
| 34 | +> [!CAUTION] | |
| 35 | +> Do not configure `framework.trusted_proxies`: the client is already resolved, and trusting `REMOTE_ADDR` or private ranges would make Symfony trust those forgeable headers again. | |
| 36 | +> Trusted proxies your application configures still apply, as usual. | |
| new file mode 100644 | |||
| @@ -0,0 +1,36 @@ | |||
| 1 | +# Requests and responses | ||
| 2 | + | ||
| 3 | +- **Superglobals**: `$_GET`, `$_POST`, `$_COOKIE`, `$_FILES` and the request entries of `$_SERVER` (`REQUEST_URI`, `HTTP_*`...) are not populated per Invocation. | ||
| 4 | + Read the `Request` object instead; `Request::createFromGlobals()` does not describe the Invocation. | ||
| 5 | +- **Output**: only the returned `Response` reaches the client. | ||
| 6 | + `echo` outside the Response, `header()` and `http_response_code()` do not: Scaleway does not put stdout in the response body. | ||
| 7 | +- **Query strings**: the Event carries `queryStringParameters` as a map, so a repeated key such as `a=1&a=2`, or `tags[]=a&tags[]=b`, reaches the Application with its last value only, and the keys arrive sorted, not in the order the client sent them. | ||
| 8 | + Keys are then parsed like PHP does, so `a.b` becomes `a_b` and `a[b]` nests. | ||
| 9 | +- **Form bodies**: `application/x-www-form-urlencoded` bodies are parsed for `POST`, `PUT`, `DELETE`, `PATCH` and `QUERY`, `multipart/form-data` only for `POST`, as PHP does. | ||
| 10 | + Uploaded files are `UploadedFile` objects in test mode: `move()` works, `is_uploaded_file()` does not. | ||
| 11 | +- **Cookies**: request cookie names are taken verbatim: unlike PHP's `$_COOKIE`, dots and spaces are not turned into underscores and `a[b]` does not nest. | ||
| 12 | +- **Streaming**: `StreamedResponse` and `BinaryFileResponse` are buffered into one Function Response; Server-Sent Events and long downloads are not possible. | ||
| 13 | + Bodies that are not valid UTF-8 are sent base64-encoded, and decoded by the platform. | ||
| 14 | +- **PSR-15 responses** go through Symfony's `Response`, which adds `Cache-Control: no-cache, private` and `Date` when they are missing. | ||
| 15 | +- **HEAD requests**: only FrameworkBundle's `ResponseListener` strips the body of a `HEAD` response, but the platform sends none anyway. | ||
| 16 | +- **Request size**: Scaleway rejects request bodies over 6 MiB with a `413`, before they reach the function. | ||
| 17 | +- **CORS**: Scaleway adds `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: Content-Type` to every response, whatever the Application sends. | ||
| 18 | + 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. | ||
| 19 | +- **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 a `500` whose body is `Error while executing function`. | ||
| 20 | + | ||
| 21 | +## Client IP and trusted proxies | ||
| 22 | + | ||
| 23 | +The runtime trusts no proxy, as clients can forge most forwarding headers on Scaleway ([ADR 0007](adr/0007-trust-only-headers-the-platform-overwrites.md)): | ||
| 24 | + | ||
| 25 | +| Request | From | Why | | ||
| 26 | +| --- | --- | --- | | ||
| 27 | +| `getClientIp()` | `X-Real-Ip`, `127.0.0.1` without it (CRON Invocations) | Set by the platform, whatever the client sends | | ||
| 28 | +| `isSecure()`, `getScheme()`, port | `X-Forwarded-Proto`, the scheme's default port | Set by the platform (`https`, `http` for CRON Invocations) | | ||
| 29 | +| `getHost()` | The [`host` option](configuration.md#host) | No `Host` header reaches the function | | ||
| 30 | + | ||
| 31 | +`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. | ||
| 32 | +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. | ||
| 33 | + | ||
| 34 | +> [!CAUTION] | ||
| 35 | +> Do not configure `framework.trusted_proxies`: the client is already resolved, and trusting `REMOTE_ADDR` or private ranges would make Symfony trust those forgeable headers again. | ||
| 36 | +> Trusted proxies your application configures still apply, as usual. | ||
added
docs/static-files.md +64 -0 | new file mode 100644 | ||
| @@ -0,0 +1,64 @@ | ||
| 1 | +# Static Files | |
| 2 | + | |
| 3 | +The runtime serves the files of `public/` itself, before building the Application: stylesheets, JavaScript, images, fonts, `favicon.ico`, `robots.txt`, and what AssetMapper or Webpack Encore compile there. | |
| 4 | +Such an Invocation pays no Kernel boot, and is answered even when the Application fails to build ([ADR 0009](adr/0009-serve-static-files-from-the-function.md)). | |
| 5 | + | |
| 6 | +A file is served when: | |
| 7 | + | |
| 8 | +- the request is a `GET` or a `HEAD`; | |
| 9 | +- the path names a regular file under `<project_dir>/public`, a symbolic link leading out of it excluded; | |
| 10 | +- no segment of the path starts with a dot (`..`, `.env`, `.htaccess`), but for a leading `/.well-known/`; | |
| 11 | +- its extension is not `.php`. | |
| 12 | + | |
| 13 | +Every other request goes to the Application, directories included: there is no index file nor directory listing. | |
| 14 | + | |
| 15 | +> [!IMPORTANT] | |
| 16 | +> A file wins over a route of the same path. | |
| 17 | +> An application answering `/robots.txt` from a controller while shipping `public/robots.txt` gets the file: delete the file to keep the route. | |
| 18 | + | |
| 19 | +## Responses | |
| 20 | + | |
| 21 | +- The `Content-Type` comes from the extension, `application/octet-stream` for an unknown one, without charset. | |
| 22 | +- Each response carries `X-Content-Type-Options: nosniff`, and an `ETag` of the bytes it sends: a matching `If-None-Match` gets a `304` without body. | |
| 23 | +- `Cache-Control` is `public, max-age=0, must-revalidate`: browsers keep the file but check it on each use. | |
| 24 | +- It is `public, max-age=31536000, immutable` for a file whose name changes with its content: one that a `manifest.json` in its directory, or in one above, maps from another name. | |
| 25 | + AssetMapper's `public/assets/manifest.json` and Webpack Encore's `public/build/manifest.json` (with versioning) are such manifests. | |
| 26 | + Names alone are not trusted, as `font-awesome.css` would look as digested as `app-mH7q4W_.css`. | |
| 27 | +- `Range` requests get the whole file with a `200`. | |
| 28 | + | |
| 29 | +No CDN stands in front of a function: every request for a Static File is an Invocation, billed and possibly paying a cold start. | |
| 30 | +Long-lived caching of digested files is what spares most of them. | |
| 31 | + | |
| 32 | +## Compression | |
| 33 | + | |
| 34 | +A file is sent compressed when the client accepts it, in this order: | |
| 35 | + | |
| 36 | +1. a precompressed variant shipped next to it, `app.css.br`, then `app.css.zst`, then `app.css.gz`, written by any build step; | |
| 37 | +2. otherwise, when the `static_compression` runtime option is set, the file compressed by the runtime. | |
| 38 | + | |
| 39 | +```json | |
| 40 | +{ | |
| 41 | + "extra": { | |
| 42 | + "runtime": { | |
| 43 | + "static_compression": "gzip" | |
| 44 | + } | |
| 45 | + } | |
| 46 | +} | |
| 47 | +``` | |
| 48 | + | |
| 49 | +`static_compression` is `false` by default, `"gzip"`, `"zstd"` or `"br"`, each needing its extension (`zlib`, `zstd`, `brotli`): any other value, or one whose extension is not loaded, answers every Invocation with a 500 until fixed. | |
| 50 | +The Scaleway `php85` runtime loads `zlib` and `zstd` but not `brotli`: use `"zstd"` or `"gzip"` there, and ship `.br` variants built beforehand for brotli. | |
| 51 | +The runtime only compresses textual files (`text/*`, JavaScript, JSON, XML, SVG, WebAssembly) of at least 1 KiB, and keeps the results in memory for the Warm Process, up to 32 MiB. | |
| 52 | + | |
| 53 | +The order of preference is the runtime's: only a `q=0` in `Accept-Encoding` refuses an encoding. | |
| 54 | +Compressed responses carry `Content-Encoding`, an `ETag` of their own and `Vary: Accept-Encoding`. | |
| 55 | +A request for `app.css.gz` itself gets that file, as any other. | |
| 56 | + | |
| 57 | +## Limits | |
| 58 | + | |
| 59 | +- A Static File must fit in one Function Response, base64-encoded when it is binary, which takes a third more. | |
| 60 | + Scaleway enforces no limit, but responses of 10 MiB and more intermittently fail with a `504` after 60 seconds ([measured](probe-results.md#size-and-encodings)). | |
| 61 | + The runtime therefore refuses Static Files over 6 MiB in a Function Response: it answers a 500 and logs the file, and `scaleway-package` warns about such files. | |
| 62 | +- A file written at runtime under `public/`, such as an upload, is only served by the instance that wrote it, each instance having its own disk. | |
| 63 | +- Store uploads, large files and busy sites' assets on Object Storage, behind Edge Services or not, and point `framework.assets.base_urls` to it. | |
| 64 | +- `assets:install` boots the Kernel: at deploy time, run it from a `post-install-cmd` with an explicit env, `@php bin/console assets:install public --env=prod`, for the same reasons as [`cache:warmup`](configuration.md#cache-and-writable-directories). | |
| new file mode 100644 | |||
| @@ -0,0 +1,64 @@ | |||
| 1 | +# Static Files | ||
| 2 | + | ||
| 3 | +The runtime serves the files of `public/` itself, before building the Application: stylesheets, JavaScript, images, fonts, `favicon.ico`, `robots.txt`, and what AssetMapper or Webpack Encore compile there. | ||
| 4 | +Such an Invocation pays no Kernel boot, and is answered even when the Application fails to build ([ADR 0009](adr/0009-serve-static-files-from-the-function.md)). | ||
| 5 | + | ||
| 6 | +A file is served when: | ||
| 7 | + | ||
| 8 | +- the request is a `GET` or a `HEAD`; | ||
| 9 | +- the path names a regular file under `<project_dir>/public`, a symbolic link leading out of it excluded; | ||
| 10 | +- no segment of the path starts with a dot (`..`, `.env`, `.htaccess`), but for a leading `/.well-known/`; | ||
| 11 | +- its extension is not `.php`. | ||
| 12 | + | ||
| 13 | +Every other request goes to the Application, directories included: there is no index file nor directory listing. | ||
| 14 | + | ||
| 15 | +> [!IMPORTANT] | ||
| 16 | +> A file wins over a route of the same path. | ||
| 17 | +> An application answering `/robots.txt` from a controller while shipping `public/robots.txt` gets the file: delete the file to keep the route. | ||
| 18 | + | ||
| 19 | +## Responses | ||
| 20 | + | ||
| 21 | +- The `Content-Type` comes from the extension, `application/octet-stream` for an unknown one, without charset. | ||
| 22 | +- Each response carries `X-Content-Type-Options: nosniff`, and an `ETag` of the bytes it sends: a matching `If-None-Match` gets a `304` without body. | ||
| 23 | +- `Cache-Control` is `public, max-age=0, must-revalidate`: browsers keep the file but check it on each use. | ||
| 24 | +- It is `public, max-age=31536000, immutable` for a file whose name changes with its content: one that a `manifest.json` in its directory, or in one above, maps from another name. | ||
| 25 | + AssetMapper's `public/assets/manifest.json` and Webpack Encore's `public/build/manifest.json` (with versioning) are such manifests. | ||
| 26 | + Names alone are not trusted, as `font-awesome.css` would look as digested as `app-mH7q4W_.css`. | ||
| 27 | +- `Range` requests get the whole file with a `200`. | ||
| 28 | + | ||
| 29 | +No CDN stands in front of a function: every request for a Static File is an Invocation, billed and possibly paying a cold start. | ||
| 30 | +Long-lived caching of digested files is what spares most of them. | ||
| 31 | + | ||
| 32 | +## Compression | ||
| 33 | + | ||
| 34 | +A file is sent compressed when the client accepts it, in this order: | ||
| 35 | + | ||
| 36 | +1. a precompressed variant shipped next to it, `app.css.br`, then `app.css.zst`, then `app.css.gz`, written by any build step; | ||
| 37 | +2. otherwise, when the `static_compression` runtime option is set, the file compressed by the runtime. | ||
| 38 | + | ||
| 39 | +```json | ||
| 40 | +{ | ||
| 41 | + "extra": { | ||
| 42 | + "runtime": { | ||
| 43 | + "static_compression": "gzip" | ||
| 44 | + } | ||
| 45 | + } | ||
| 46 | +} | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +`static_compression` is `false` by default, `"gzip"`, `"zstd"` or `"br"`, each needing its extension (`zlib`, `zstd`, `brotli`): any other value, or one whose extension is not loaded, answers every Invocation with a 500 until fixed. | ||
| 50 | +The Scaleway `php85` runtime loads `zlib` and `zstd` but not `brotli`: use `"zstd"` or `"gzip"` there, and ship `.br` variants built beforehand for brotli. | ||
| 51 | +The runtime only compresses textual files (`text/*`, JavaScript, JSON, XML, SVG, WebAssembly) of at least 1 KiB, and keeps the results in memory for the Warm Process, up to 32 MiB. | ||
| 52 | + | ||
| 53 | +The order of preference is the runtime's: only a `q=0` in `Accept-Encoding` refuses an encoding. | ||
| 54 | +Compressed responses carry `Content-Encoding`, an `ETag` of their own and `Vary: Accept-Encoding`. | ||
| 55 | +A request for `app.css.gz` itself gets that file, as any other. | ||
| 56 | + | ||
| 57 | +## Limits | ||
| 58 | + | ||
| 59 | +- A Static File must fit in one Function Response, base64-encoded when it is binary, which takes a third more. | ||
| 60 | + Scaleway enforces no limit, but responses of 10 MiB and more intermittently fail with a `504` after 60 seconds ([measured](probe-results.md#size-and-encodings)). | ||
| 61 | + The runtime therefore refuses Static Files over 6 MiB in a Function Response: it answers a 500 and logs the file, and `scaleway-package` warns about such files. | ||
| 62 | +- A file written at runtime under `public/`, such as an upload, is only served by the instance that wrote it, each instance having its own disk. | ||
| 63 | +- Store uploads, large files and busy sites' assets on Object Storage, behind Edge Services or not, and point `framework.assets.base_urls` to it. | ||
| 64 | +- `assets:install` boots the Kernel: at deploy time, run it from a `post-install-cmd` with an explicit env, `@php bin/console assets:install public --env=prod`, for the same reasons as [`cache:warmup`](configuration.md#cache-and-writable-directories). | ||
added
docs/warm-processes.md +17 -0 | new file mode 100644 | ||
| @@ -0,0 +1,17 @@ | ||
| 1 | +# Warm Processes | |
| 2 | + | |
| 3 | +The Application is built once per Warm Process and reused by the following Invocations, like with FrankenPHP's worker mode or RoadRunner ([ADR 0002](adr/0002-reuse-application-across-invocations.md)). | |
| 4 | +Scaleway keeps processes warm: consecutive Invocations of an instance run in the same PHP process. | |
| 5 | + | |
| 6 | +Between Invocations, for a Kernel: | |
| 7 | + | |
| 8 | +- `terminate()` runs after each Invocation, and a failure in it is logged without changing the Function Response; | |
| 9 | +- the `services_resetter` resets the services tagged `kernel.reset` before the next request, as Symfony's Kernel does; | |
| 10 | +- uploaded files are deleted, and output buffers the Application left open are closed. | |
| 11 | + | |
| 12 | +Everything else survives, so your application must be safe for long-running execution: | |
| 13 | + | |
| 14 | +- do not keep per-request state in static properties or in services that do not implement `ResetInterface`; | |
| 15 | +- in-memory caches and collections grow across Invocations unless reset; | |
| 16 | +- connections (database, HTTP clients) may have been closed by the server while the process was idle; | |
| 17 | +- `exit()` or a fatal error ends the process, and the next Invocation pays a cold start. | |
| new file mode 100644 | |||
| @@ -0,0 +1,17 @@ | |||
| 1 | +# Warm Processes | ||
| 2 | + | ||
| 3 | +The Application is built once per Warm Process and reused by the following Invocations, like with FrankenPHP's worker mode or RoadRunner ([ADR 0002](adr/0002-reuse-application-across-invocations.md)). | ||
| 4 | +Scaleway keeps processes warm: consecutive Invocations of an instance run in the same PHP process. | ||
| 5 | + | ||
| 6 | +Between Invocations, for a Kernel: | ||
| 7 | + | ||
| 8 | +- `terminate()` runs after each Invocation, and a failure in it is logged without changing the Function Response; | ||
| 9 | +- the `services_resetter` resets the services tagged `kernel.reset` before the next request, as Symfony's Kernel does; | ||
| 10 | +- uploaded files are deleted, and output buffers the Application left open are closed. | ||
| 11 | + | ||
| 12 | +Everything else survives, so your application must be safe for long-running execution: | ||
| 13 | + | ||
| 14 | +- do not keep per-request state in static properties or in services that do not implement `ResetInterface`; | ||
| 15 | +- in-memory caches and collections grow across Invocations unless reset; | ||
| 16 | +- connections (database, HTTP clients) may have been closed by the server while the process was idle; | ||
| 17 | +- `exit()` or a fatal error ends the process, and the next Invocation pays a cold start. | ||
modified
example/README.md +2 -2 | @@ -14,7 +14,7 @@ A minimal Symfony application running on Scaleway Serverless Functions through ` | ||
| 14 | 14 | | `GET /redirect` | A redirect to an absolute route URL | |
| 15 | 15 | | `POST /` | Where CRON Invocations land, with the trigger's arguments as JSON body | |
| 16 | 16 | |
| 17 | -The files of `public/` are [Static Files](../README.md#static-files), served by the runtime without building the Application: | |
| 17 | +The files of `public/` are [Static Files](../docs/static-files.md), served by the runtime without building the Application: | |
| 18 | 18 | |
| 19 | 19 | | File | What it shows | |
| 20 | 20 | | --- | --- | |
| @@ -97,7 +97,7 @@ terraform -chdir=terraform destroy | ||
| 97 | 97 | Rerun `scaleway-package` and `terraform apply` (with the same `host`) to deploy a new version. |
| 98 | 98 | `e2e/run.sh` checks that absolute URLs carry `SCALEWAY_HOST`, `localhost` when it is unset, as for a deployment without `host`. |
| 99 | 99 | Against a deployment, `e2e/run.sh` skips the CRON scenarios, as only the platform triggers CRON Invocations. |
| 100 | -Check them in the [logs](../README.md#logs) instead, after the triggers ran (at minutes 0 and 30): each one leaves its line, the second showing that `app:greet` ran as a Command Invocation. | |
| 100 | +Check them in the [logs](../docs/logs.md) instead, after the triggers ran (at minutes 0 and 30): each one leaves its line, the second showing that `app:greet` ran as a Command Invocation. | |
| 101 | 101 | |
| 102 | 102 | ``` |
| 103 | 103 | DEBUG - [info] CRON Invocation received with the arguments ["job"] source=user stream=stderr |
| @@ -14,7 +14,7 @@ A minimal Symfony application running on Scaleway Serverless Functions through ` | |||
| 14 | | `GET /redirect` | A redirect to an absolute route URL | | 14 | | `GET /redirect` | A redirect to an absolute route URL | |
| 15 | | `POST /` | Where CRON Invocations land, with the trigger's arguments as JSON body | | 15 | | `POST /` | Where CRON Invocations land, with the trigger's arguments as JSON body | |
| 16 | 16 | ||
| 17 | -The files of `public/` are [Static Files](../README.md#static-files), served by the runtime without building the Application: | 17 | +The files of `public/` are [Static Files](../docs/static-files.md), served by the runtime without building the Application: |
| 18 | 18 | ||
| 19 | | File | What it shows | | 19 | | File | What it shows | |
| 20 | | --- | --- | | 20 | | --- | --- | |
| @@ -97,7 +97,7 @@ terraform -chdir=terraform destroy | |||
| 97 | Rerun `scaleway-package` and `terraform apply` (with the same `host`) to deploy a new version. | 97 | Rerun `scaleway-package` and `terraform apply` (with the same `host`) to deploy a new version. |
| 98 | `e2e/run.sh` checks that absolute URLs carry `SCALEWAY_HOST`, `localhost` when it is unset, as for a deployment without `host`. | 98 | `e2e/run.sh` checks that absolute URLs carry `SCALEWAY_HOST`, `localhost` when it is unset, as for a deployment without `host`. |
| 99 | Against a deployment, `e2e/run.sh` skips the CRON scenarios, as only the platform triggers CRON Invocations. | 99 | Against a deployment, `e2e/run.sh` skips the CRON scenarios, as only the platform triggers CRON Invocations. |
| 100 | -Check them in the [logs](../README.md#logs) instead, after the triggers ran (at minutes 0 and 30): each one leaves its line, the second showing that `app:greet` ran as a Command Invocation. | 100 | +Check them in the [logs](../docs/logs.md) instead, after the triggers ran (at minutes 0 and 30): each one leaves its line, the second showing that `app:greet` ran as a Command Invocation. |
| 101 | 101 | ||
| 102 | ``` | 102 | ``` |
| 103 | DEBUG - [info] CRON Invocation received with the arguments ["job"] source=user stream=stderr | 103 | DEBUG - [info] CRON Invocation received with the arguments ["job"] source=user stream=stderr |
modified
probe/README.md +1 -1 | @@ -78,7 +78,7 @@ To update the [Function Runtime Catalogue](../docs/probe-results.md#function-run | ||
| 78 | 78 | curl -sS "$PROBE_URL/?mode=runtime" > ../tests/Fixtures/FunctionRuntimes/php85.json |
| 79 | 79 | ``` |
| 80 | 80 | |
| 81 | -10. Export the function's logs of the last hour, CRON lines included, from Cockpit's Grafana or with the Loki query of the [README](../README.md#logs). | |
| 81 | +10. Export the function's logs of the last hour, CRON lines included, from Cockpit's Grafana or with the Loki query of the [README](../docs/logs.md). | |
| 82 | 82 | |
| 83 | 83 | 11. Compare a CRON Event (step 9 or 10) with the HTTP one of `01-facts.json`, `event` and `context` alike, and list what only the CRON one has or lacks: headers (a trigger name or id, a token, `User-Agent`, `X-Forwarded-For`), method, path, context fields. |
| 84 | 84 | Then send each such header from a plain HTTP call, and check whether it reaches the Event as sent, is overwritten, or is removed: only a marker the platform sets itself can tell CRON Invocations from HTTP ones. |
| @@ -78,7 +78,7 @@ To update the [Function Runtime Catalogue](../docs/probe-results.md#function-run | |||
| 78 | curl -sS "$PROBE_URL/?mode=runtime" > ../tests/Fixtures/FunctionRuntimes/php85.json | 78 | curl -sS "$PROBE_URL/?mode=runtime" > ../tests/Fixtures/FunctionRuntimes/php85.json |
| 79 | ``` | 79 | ``` |
| 80 | 80 | ||
| 81 | -10. Export the function's logs of the last hour, CRON lines included, from Cockpit's Grafana or with the Loki query of the [README](../README.md#logs). | 81 | +10. Export the function's logs of the last hour, CRON lines included, from Cockpit's Grafana or with the Loki query of the [README](../docs/logs.md). |
| 82 | 82 | ||
| 83 | 11. Compare a CRON Event (step 9 or 10) with the HTTP one of `01-facts.json`, `event` and `context` alike, and list what only the CRON one has or lacks: headers (a trigger name or id, a token, `User-Agent`, `X-Forwarded-For`), method, path, context fields. | 83 | 11. Compare a CRON Event (step 9 or 10) with the HTTP one of `01-facts.json`, `event` and `context` alike, and list what only the CRON one has or lacks: headers (a trigger name or id, a token, `User-Agent`, `X-Forwarded-For`), method, path, context fields. |
| 84 | Then send each such header from a plain HTTP call, and check whether it reaches the Event as sent, is overwritten, or is removed: only a marker the platform sets itself can tell CRON Invocations from HTTP ones. | 84 | Then send each such header from a plain HTTP call, and check whether it reaches the Event as sent, is overwritten, or is removed: only a marker the platform sets itself can tell CRON Invocations from HTTP ones. |