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

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

Download ZIP

Merge pull request #1 from jdecool/feat/static-filesUnverified

feat: serve Static Files from the function
Jérémy DECOOL committed 2026-11-22T11:53:23+01:00 Browse files
1358470 parents: fcb9afc 98a3c8f
modified .github/workflows/ci.yml +3 -1
@@ -27,6 +27,8 @@ jobs:
2727 with:
2828 php-version: ${{ matrix.php }}
2929 coverage: none
30+ # Covers the zstd and brotli compression of Static Files, skipped without them.
31+ extensions: zstd, brotli
3032 tools: flex
3133
3234 - name: Validate composer.json
@@ -55,7 +57,7 @@ jobs:
5557 with:
5658 php-version: '8.5'
5759 coverage: none
58- extensions: zip
60+ extensions: zip, zstd
5961
6062 - name: Install with the runtime of this checkout
6163 working-directory: example
@@ -27,6 +27,8 @@ jobs:
27 with:27 with:
28 php-version: ${{ matrix.php }}28 php-version: ${{ matrix.php }}
29 coverage: none29 coverage: none
30+ # Covers the zstd and brotli compression of Static Files, skipped without them.
31+ extensions: zstd, brotli
30 tools: flex32 tools: flex
31 33
32 - name: Validate composer.json34 - name: Validate composer.json
@@ -55,7 +57,7 @@ jobs:
55 with:57 with:
56 php-version: '8.5'58 php-version: '8.5'
57 coverage: none59 coverage: none
58- extensions: zip60+ extensions: zip, zstd
59 61
60 - name: Install with the runtime of this checkout62 - name: Install with the runtime of this checkout
61 working-directory: example63 working-directory: example
modified GLOSSARY.md +4 -0
@@ -49,3 +49,7 @@ _Avoid_: Token, API key
4949 **Emulator**:
5050 The local server that turns real HTTP requests into Events and calls the Handler, to run an application without deploying it.
5151 _Avoid_: Local runtime, dev server
52+
53+**Static File**:
54+A file present under the application's web root when an HTTP Invocation asks for it, answered as it is, without building the Application.
55+_Avoid_: Asset (the Symfony component), public file
@@ -49,3 +49,7 @@ _Avoid_: Token, API key
49 **Emulator**:49 **Emulator**:
50 The local server that turns real HTTP requests into Events and calls the Handler, to run an application without deploying it.50 The local server that turns real HTTP requests into Events and calls the Handler, to run an application without deploying it.
51 _Avoid_: Local runtime, dev server51 _Avoid_: Local runtime, dev server
52+
53+**Static File**:
54+A file present under the application's web root when an HTTP Invocation asks for it, answered as it is, without building the Application.
55+_Avoid_: Asset (the Symfony component), public file
modified README.md +66 -0
@@ -18,6 +18,7 @@ Vocabulary (Invocation, Event, Warm Process...) is defined in [GLOSSARY.md](GLOS
1818 - [Installation](#installation)
1919 - [Configuration](#configuration)
2020 - [Supported Applications](#supported-applications)
21+- [Static Files](#static-files)
2122 - [CRON triggers and Command Invocations](#cron-triggers-and-command-invocations)
2223 - [Packaging](#packaging)
2324 - [Deployment](#deployment)
@@ -283,6 +284,71 @@ Other keys are dropped, and any other return value fails the Invocation with a 5
283284 Command Invocations are not routed: the raw callable gets their Event like any other.
284285 An invokable object is not taken for a raw callable; return `$object(...)` to make it one.
285286
287+## Static Files
288+
289+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.
290+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)).
291+
292+A file is served when:
293+
294+- the request is a `GET` or a `HEAD`;
295+- the path names a regular file under `<project_dir>/public`, a symbolic link leading out of it excluded;
296+- no segment of the path starts with a dot (`..`, `.env`, `.htaccess`), but for a leading `/.well-known/`;
297+- its extension is not `.php`.
298+
299+Every other request goes to the Application, directories included: there is no index file nor directory listing.
300+
301+> [!IMPORTANT]
302+> A file wins over a route of the same path.
303+> An application answering `/robots.txt` from a controller while shipping `public/robots.txt` gets the file: delete the file to keep the route.
304+
305+### Responses
306+
307+- The `Content-Type` comes from the extension, `application/octet-stream` for an unknown one, without charset.
308+- 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.
309+- `Cache-Control` is `public, max-age=0, must-revalidate`: browsers keep the file but check it on each use.
310+- 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.
311+ AssetMapper's `public/assets/manifest.json` and Webpack Encore's `public/build/manifest.json` (with versioning) are such manifests.
312+ Names alone are not trusted, as `font-awesome.css` would look as digested as `app-mH7q4W_.css`.
313+- `Range` requests get the whole file with a `200`.
314+
315+No CDN stands in front of a function: every request for a Static File is an Invocation, billed and possibly paying a cold start.
316+Long-lived caching of digested files is what spares most of them.
317+
318+### Compression
319+
320+A file is sent compressed when the client accepts it, in this order:
321+
322+1. a precompressed variant shipped next to it, `app.css.br`, then `app.css.zst`, then `app.css.gz`, written by any build step;
323+2. otherwise, when the `static_compression` runtime option is set, the file compressed by the runtime.
324+
325+```json
326+{
327+ "extra": {
328+ "runtime": {
329+ "static_compression": "gzip"
330+ }
331+ }
332+}
333+```
334+
335+`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.
336+The Scaleway `php85` runtime loads `zlib` and `zstd` but not `brotli`: use `"zstd"` or `"gzip"` there, and ship `.br` variants built beforehand for brotli.
337+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.
338+
339+The order of preference is the runtime's: only a `q=0` in `Accept-Encoding` refuses an encoding.
340+Compressed responses carry `Content-Encoding`, an `ETag` of their own and `Vary: Accept-Encoding`.
341+A request for `app.css.gz` itself gets that file, as any other.
342+
343+### Limits
344+
345+- A Static File must fit in one Function Response, base64-encoded when it is binary, which takes a third more.
346+ 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)).
347+ 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.
348+- 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.
349+- Store uploads, large files and busy sites' assets on Object Storage, behind Edge Services or not, and point `framework.assets.base_urls` to it.
350+- `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).
351+
286352 ## CRON triggers and Command Invocations
287353
288354 ### CRON triggers
@@ -18,6 +18,7 @@ Vocabulary (Invocation, Event, Warm Process...) is defined in [GLOSSARY.md](GLOS
18 - [Installation](#installation)18 - [Installation](#installation)
19 - [Configuration](#configuration)19 - [Configuration](#configuration)
20 - [Supported Applications](#supported-applications)20 - [Supported Applications](#supported-applications)
21+- [Static Files](#static-files)
21 - [CRON triggers and Command Invocations](#cron-triggers-and-command-invocations)22 - [CRON triggers and Command Invocations](#cron-triggers-and-command-invocations)
22 - [Packaging](#packaging)23 - [Packaging](#packaging)
23 - [Deployment](#deployment)24 - [Deployment](#deployment)
@@ -283,6 +284,71 @@ Other keys are dropped, and any other return value fails the Invocation with a 5
283 Command Invocations are not routed: the raw callable gets their Event like any other.284 Command Invocations are not routed: the raw callable gets their Event like any other.
284 An invokable object is not taken for a raw callable; return `$object(...)` to make it one.285 An invokable object is not taken for a raw callable; return `$object(...)` to make it one.
285 286
287+## Static Files
288+
289+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.
290+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)).
291+
292+A file is served when:
293+
294+- the request is a `GET` or a `HEAD`;
295+- the path names a regular file under `<project_dir>/public`, a symbolic link leading out of it excluded;
296+- no segment of the path starts with a dot (`..`, `.env`, `.htaccess`), but for a leading `/.well-known/`;
297+- its extension is not `.php`.
298+
299+Every other request goes to the Application, directories included: there is no index file nor directory listing.
300+
301+> [!IMPORTANT]
302+> A file wins over a route of the same path.
303+> An application answering `/robots.txt` from a controller while shipping `public/robots.txt` gets the file: delete the file to keep the route.
304+
305+### Responses
306+
307+- The `Content-Type` comes from the extension, `application/octet-stream` for an unknown one, without charset.
308+- 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.
309+- `Cache-Control` is `public, max-age=0, must-revalidate`: browsers keep the file but check it on each use.
310+- 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.
311+ AssetMapper's `public/assets/manifest.json` and Webpack Encore's `public/build/manifest.json` (with versioning) are such manifests.
312+ Names alone are not trusted, as `font-awesome.css` would look as digested as `app-mH7q4W_.css`.
313+- `Range` requests get the whole file with a `200`.
314+
315+No CDN stands in front of a function: every request for a Static File is an Invocation, billed and possibly paying a cold start.
316+Long-lived caching of digested files is what spares most of them.
317+
318+### Compression
319+
320+A file is sent compressed when the client accepts it, in this order:
321+
322+1. a precompressed variant shipped next to it, `app.css.br`, then `app.css.zst`, then `app.css.gz`, written by any build step;
323+2. otherwise, when the `static_compression` runtime option is set, the file compressed by the runtime.
324+
325+```json
326+{
327+ "extra": {
328+ "runtime": {
329+ "static_compression": "gzip"
330+ }
331+ }
332+}
333+```
334+
335+`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.
336+The Scaleway `php85` runtime loads `zlib` and `zstd` but not `brotli`: use `"zstd"` or `"gzip"` there, and ship `.br` variants built beforehand for brotli.
337+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.
338+
339+The order of preference is the runtime's: only a `q=0` in `Accept-Encoding` refuses an encoding.
340+Compressed responses carry `Content-Encoding`, an `ETag` of their own and `Vary: Accept-Encoding`.
341+A request for `app.css.gz` itself gets that file, as any other.
342+
343+### Limits
344+
345+- A Static File must fit in one Function Response, base64-encoded when it is binary, which takes a third more.
346+ 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)).
347+ 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.
348+- 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.
349+- Store uploads, large files and busy sites' assets on Object Storage, behind Edge Services or not, and point `framework.assets.base_urls` to it.
350+- `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).
351+
286 ## CRON triggers and Command Invocations352 ## CRON triggers and Command Invocations
287 353
288 ### CRON triggers354 ### CRON triggers
modified bin/scaleway-serve +1 -1
@@ -70,7 +70,7 @@ $startWarmProcess = static function () use ($handlerFile, $socket) {
7070
7171 $warmProcess = $startWarmProcess();
7272 $server = start(
73- [\PHP_BINARY, '-d', 'enable_post_data_reading=0', '-d', 'expose_php=0', '-d', 'default_mimetype=', '-S', $address, __DIR__.'/../resources/emulator/router.php'],
73+ [\PHP_BINARY, '-d', 'enable_post_data_reading=0', '-d', 'expose_php=0', '-d', 'default_mimetype=', '-d', 'default_charset=', '-S', $address, __DIR__.'/../resources/emulator/router.php'],
7474 ['SCALEWAY_EMULATOR_AUTOLOAD' => $autoload, 'SCALEWAY_EMULATOR_SOCKET' => $socket] + getenv(),
7575 );
7676 // Children outlive a killed parent, so a SIGTERM would leave the port busy and the Warm Process running.
@@ -70,7 +70,7 @@ $startWarmProcess = static function () use ($handlerFile, $socket) {
70 70
71 $warmProcess = $startWarmProcess();71 $warmProcess = $startWarmProcess();
72 $server = start(72 $server = start(
73- [\PHP_BINARY, '-d', 'enable_post_data_reading=0', '-d', 'expose_php=0', '-d', 'default_mimetype=', '-S', $address, __DIR__.'/../resources/emulator/router.php'],73+ [\PHP_BINARY, '-d', 'enable_post_data_reading=0', '-d', 'expose_php=0', '-d', 'default_mimetype=', '-d', 'default_charset=', '-S', $address, __DIR__.'/../resources/emulator/router.php'],
74 ['SCALEWAY_EMULATOR_AUTOLOAD' => $autoload, 'SCALEWAY_EMULATOR_SOCKET' => $socket] + getenv(),74 ['SCALEWAY_EMULATOR_AUTOLOAD' => $autoload, 'SCALEWAY_EMULATOR_SOCKET' => $socket] + getenv(),
75 );75 );
76 // Children outlive a killed parent, so a SIGTERM would leave the port busy and the Warm Process running.76 // Children outlive a killed parent, so a SIGTERM would leave the port busy and the Warm Process running.
modified composer.json +1 -0
@@ -14,6 +14,7 @@
1414 "riverline/multipart-parser": "^2.3",
1515 "symfony/http-foundation": "^7.4 || ^8.0",
1616 "symfony/http-kernel": "^7.4 || ^8.0",
17+ "symfony/mime": "^7.4 || ^8.0",
1718 "symfony/runtime": "^7.4 || ^8.0"
1819 },
1920 "suggest": {
@@ -14,6 +14,7 @@
14 "riverline/multipart-parser": "^2.3",14 "riverline/multipart-parser": "^2.3",
15 "symfony/http-foundation": "^7.4 || ^8.0",15 "symfony/http-foundation": "^7.4 || ^8.0",
16 "symfony/http-kernel": "^7.4 || ^8.0",16 "symfony/http-kernel": "^7.4 || ^8.0",
17+ "symfony/mime": "^7.4 || ^8.0",
17 "symfony/runtime": "^7.4 || ^8.0"18 "symfony/runtime": "^7.4 || ^8.0"
18 },19 },
19 "suggest": {20 "suggest": {
added docs/adr/0009-serve-static-files-from-the-function.md +16 -0
new file mode 100644
@@ -0,0 +1,16 @@
1+# The function serves Static Files itself
2+
3+A Symfony application ships its CSS, JavaScript, images and fonts under its web root, and nothing in front of a Scaleway function serves them: every request reaches the Handler.
4+We therefore let the runtime serve the files under the web root itself, before building the Application, so that a standard application works on Scaleway without extra infrastructure, and keep moving them to Object Storage as a later, optional step.
5+
6+## Considered Options
7+
8+- Uploading them to Object Storage, behind Edge Services or not, and pointing `asset()` to it: kept for later, as it needs a bucket, CORS settings and a deployment step before an application works at all.
9+- Serving nothing and documenting Object Storage only: rejected, an unchanged application would answer its own stylesheets with 404s.
10+
11+## Consequences
12+
13+- Each Static File costs an Invocation, can hit a cold start, and its binary body grows by about a third once base64-encoded.
14+- Its size is bounded by the largest Function Response the platform accepts.
15+- Files written at runtime, such as user uploads, are only served by the instance that wrote them, each instance having its own ephemeral disk: they belong in Object Storage.
16+- Only a file that a `manifest.json` above it maps from another name, as AssetMapper and Webpack Encore write them, is cached for good: a digest guessed from the name alone would also match plain names such as `font-awesome.css`, which would then stay stale in browsers for a year.
new file mode 100644
@@ -0,0 +1,16 @@
1+# The function serves Static Files itself
2+
3+A Symfony application ships its CSS, JavaScript, images and fonts under its web root, and nothing in front of a Scaleway function serves them: every request reaches the Handler.
4+We therefore let the runtime serve the files under the web root itself, before building the Application, so that a standard application works on Scaleway without extra infrastructure, and keep moving them to Object Storage as a later, optional step.
5+
6+## Considered Options
7+
8+- Uploading them to Object Storage, behind Edge Services or not, and pointing `asset()` to it: kept for later, as it needs a bucket, CORS settings and a deployment step before an application works at all.
9+- Serving nothing and documenting Object Storage only: rejected, an unchanged application would answer its own stylesheets with 404s.
10+
11+## Consequences
12+
13+- Each Static File costs an Invocation, can hit a cold start, and its binary body grows by about a third once base64-encoded.
14+- Its size is bounded by the largest Function Response the platform accepts.
15+- Files written at runtime, such as user uploads, are only served by the instance that wrote them, each instance having its own ephemeral disk: they belong in Object Storage.
16+- Only a file that a `manifest.json` above it maps from another name, as AssetMapper and Webpack Encore write them, is cached for good: a digest guessed from the name alone would also match plain names such as `font-awesome.css`, which would then stay stale in browsers for a year.
modified docs/probe-results.md +11 -0
@@ -149,6 +149,17 @@ An `array`: `{"memoryLimitInMb": 256, "functionName": "probe-php85", "functionVe
149149 - `HEAD` responses carry `Content-Length` and no body.
150150 - The platform adds `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: Content-Type` to every response.
151151
152+### Size and encodings
153+
154+Measured on 2026-11-22 on `php85` (256 MB) with the probe's `size` and `encoded` modes (step 12), sizes being the decoded body.
155+
156+- No size limit showed up: text bodies of up to 28 MiB and base64 ones of up to 12 MiB reached the client whole.
157+- From 10 MiB on, responses failed intermittently with a `504` after exactly 60 seconds, text and base64 alike (10 MiB: 4 of 8 failed; 16 to 28 MiB base64: all failed); a successful 28 MiB text response took 44 seconds.
158+- Up to 5 MiB, all 15 base64 responses of 1, 3 and 5 MiB succeeded; 6 to 8 MiB succeeded in a single run each.
159+- The platform does not compress responses: a 100 KiB text body with `Accept-Encoding: gzip, br` came back without `Content-Encoding`.
160+- A `Content-Encoding` set by the function, `gzip` or `zstd`, reaches the client with `Vary`, and the base64 body decoded by the platform is the compressed stream as sent.
161+- The `php85` runtime loads 120 extensions: `zlib` and `zstd`, but not `brotli`.
162+
152163 ## Logs
153164
154165 Measured with the Loki HTTP API of the project's `Scaleway Logs` data source (`scw cockpit data-source list origin=scaleway types.0=logs`), with a `read_only_logs` Cockpit token sent as `Authorization: Bearer`; requests without it get `401`.
@@ -149,6 +149,17 @@ An `array`: `{"memoryLimitInMb": 256, "functionName": "probe-php85", "functionVe
149 - `HEAD` responses carry `Content-Length` and no body.149 - `HEAD` responses carry `Content-Length` and no body.
150 - The platform adds `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: Content-Type` to every response.150 - The platform adds `Access-Control-Allow-Origin: *` and `Access-Control-Allow-Headers: Content-Type` to every response.
151 151
152+### Size and encodings
153+
154+Measured on 2026-11-22 on `php85` (256 MB) with the probe's `size` and `encoded` modes (step 12), sizes being the decoded body.
155+
156+- No size limit showed up: text bodies of up to 28 MiB and base64 ones of up to 12 MiB reached the client whole.
157+- From 10 MiB on, responses failed intermittently with a `504` after exactly 60 seconds, text and base64 alike (10 MiB: 4 of 8 failed; 16 to 28 MiB base64: all failed); a successful 28 MiB text response took 44 seconds.
158+- Up to 5 MiB, all 15 base64 responses of 1, 3 and 5 MiB succeeded; 6 to 8 MiB succeeded in a single run each.
159+- The platform does not compress responses: a 100 KiB text body with `Accept-Encoding: gzip, br` came back without `Content-Encoding`.
160+- A `Content-Encoding` set by the function, `gzip` or `zstd`, reaches the client with `Vary`, and the base64 body decoded by the platform is the compressed stream as sent.
161+- The `php85` runtime loads 120 extensions: `zlib` and `zstd`, but not `brotli`.
162+
152 ## Logs163 ## Logs
153 164
154 Measured with the Loki HTTP API of the project's `Scaleway Logs` data source (`scw cockpit data-source list origin=scaleway types.0=logs`), with a `read_only_logs` Cockpit token sent as `Authorization: Bearer`; requests without it get `401`.165 Measured with the Loki HTTP API of the project's `Scaleway Logs` data source (`scw cockpit data-source list origin=scaleway types.0=logs`), with a `read_only_logs` Cockpit token sent as `Authorization: Bearer`; requests without it get `401`.
modified example/.gitignore +4 -0
@@ -4,3 +4,7 @@
44 /var/
55 /vendor/
66 /function.zip
7+# Precompressed Static File variants are shipped on purpose, whatever a global gitignore says.
8+!/public/**/*.gz
9+!/public/**/*.br
10+!/public/**/*.zst
@@ -4,3 +4,7 @@
4 /var/4 /var/
5 /vendor/5 /vendor/
6 /function.zip6 /function.zip
7+# Precompressed Static File variants are shipped on purpose, whatever a global gitignore says.
8+!/public/**/*.gz
9+!/public/**/*.br
10+!/public/**/*.zst
modified example/README.md +9 -0
@@ -14,6 +14,15 @@ A minimal Symfony application running on Scaleway Serverless Functions through `
1414 | `GET /redirect` | A redirect to an absolute route URL |
1515 | `POST /` | Where CRON Invocations land, with the trigger's arguments as JSON body |
1616
17+The files of `public/` are [Static Files](../README.md#static-files), served by the runtime without building the Application:
18+
19+| File | What it shows |
20+| --- | --- |
21+| `/css/app.css` | A stylesheet, revalidated with its `ETag`; with `Accept-Encoding: zstd` or `gzip`, its precompressed `app.css.zst` or `app.css.gz` |
22+| `/js/greeting.js` | A JavaScript module, as `text/javascript` |
23+| `/images/logo.png` | A binary file, base64-encoded in the Function Response |
24+| `/assets/app-Ex4mPl3.css` | A digested file as AssetMapper writes one, listed in `assets/manifest.json`, so cached for good |
25+
1726 Its `post-install-cmd` warms the prod cache when Scaleway installs the dependencies at deploy time, as the warmup needs no secret; without it, the first Invocation of each Warm Process builds the cache.
1827
1928 It logs from the `info` level to stderr, which reaches Cockpit, through Symfony's fallback logger lowered in `config/services.yaml`, without Monolog.
@@ -14,6 +14,15 @@ 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:
18+
19+| File | What it shows |
20+| --- | --- |
21+| `/css/app.css` | A stylesheet, revalidated with its `ETag`; with `Accept-Encoding: zstd` or `gzip`, its precompressed `app.css.zst` or `app.css.gz` |
22+| `/js/greeting.js` | A JavaScript module, as `text/javascript` |
23+| `/images/logo.png` | A binary file, base64-encoded in the Function Response |
24+| `/assets/app-Ex4mPl3.css` | A digested file as AssetMapper writes one, listed in `assets/manifest.json`, so cached for good |
25+
17 Its `post-install-cmd` warms the prod cache when Scaleway installs the dependencies at deploy time, as the warmup needs no secret; without it, the first Invocation of each Warm Process builds the cache.26 Its `post-install-cmd` warms the prod cache when Scaleway installs the dependencies at deploy time, as the warmup needs no secret; without it, the first Invocation of each Warm Process builds the cache.
18 27
19 It logs from the `info` level to stderr, which reaches Cockpit, through Symfony's fallback logger lowered in `config/services.yaml`, without Monolog.28 It logs from the `info` level to stderr, which reaches Cockpit, through Symfony's fallback logger lowered in `config/services.yaml`, without Monolog.
modified example/e2e/run.sh +41 -0
@@ -130,6 +130,47 @@ fi
130130 status=$(request missing "$base_url/missing")
131131 expect "unknown route" "$status" 404
132132
133+# Static Files, served by the runtime from public/ before the Application is built.
134+status=$(request css "$base_url/css/app.css")
135+expect "GET Static File status" "$status" 200
136+expect "Static File content type" "$(header css content-type)" text/css
137+expect "Static File body" "$(sha256 "$tmp/css.body")" "$(sha256 "$(dirname "$0")/../public/css/app.css")"
138+expect "Static File nosniff" "$(header css x-content-type-options)" nosniff
139+expect "Static File revalidated" "$(header css cache-control)" "public, max-age=0, must-revalidate"
140+etag=$(header css etag)
141+status=$(request css304 -H "If-None-Match: $etag" "$base_url/css/app.css")
142+expect "Static File with a matching If-None-Match" "$status" 304
143+status=$(request csshead -I "$base_url/css/app.css")
144+expect "HEAD Static File" "$status $(header csshead content-type)" "200 text/css"
145+
146+status=$(request gzip -H 'Accept-Encoding: gzip' "$base_url/css/app.css")
147+expect "precompressed variant encoding" "$(header gzip content-encoding)" gzip
148+expect "precompressed variant varies" "$(header gzip vary)" Accept-Encoding
149+expect "precompressed variant body" "$(php -r 'echo hash("sha256", (string) gzdecode(file_get_contents($argv[1])));' "$tmp/gzip.body")" "$(sha256 "$(dirname "$0")/../public/css/app.css")"
150+
151+# zstd is preferred to gzip, and Scaleway's php85 can compress with it too.
152+status=$(request zstd -H 'Accept-Encoding: gzip, zstd' "$base_url/css/app.css")
153+expect "zstd variant preferred to gzip" "$(header zstd content-encoding)" zstd
154+if php -r 'exit(function_exists("zstd_uncompress") ? 0 : 1);'; then
155+ expect "zstd variant body" "$(php -r 'echo hash("sha256", (string) zstd_uncompress(file_get_contents($argv[1])));' "$tmp/zstd.body")" "$(sha256 "$(dirname "$0")/../public/css/app.css")"
156+else
157+ echo "skip zstd variant body: the local php lacks the zstd extension"
158+fi
159+
160+status=$(request js "$base_url/js/greeting.js")
161+expect "JavaScript module content type" "$status $(header js content-type)" "200 text/javascript"
162+status=$(request png "$base_url/images/logo.png")
163+expect "image content type" "$status $(header png content-type)" "200 image/png"
164+expect "image body, base64 decoded by the platform" "$(sha256 "$tmp/png.body")" "$(sha256 "$(dirname "$0")/../public/images/logo.png")"
165+status=$(request digested "$base_url/assets/app-Ex4mPl3.css")
166+expect "digested Static File cached for good" "$(header digested cache-control)" "public, max-age=31536000, immutable"
167+
168+# Both reach the Application, which has no such route.
169+status=$(request frontcontroller "$base_url/index.php")
170+expect "the Front Controller is never served as a file" "$status" 404
171+status=$(request dotenv --path-as-is "$base_url/../.env")
172+expect "files outside public/ are not served" "$status" 404
173+
133174 status=$(request postroot -X POST -H 'Content-Type: application/json' --data '{"job":"cleanup"}' "$base_url/")
134175 expect "POST / JSON body" "$(field postroot args.job)" cleanup
135176
@@ -130,6 +130,47 @@ fi
130 status=$(request missing "$base_url/missing")130 status=$(request missing "$base_url/missing")
131 expect "unknown route" "$status" 404131 expect "unknown route" "$status" 404
132 132
133+# Static Files, served by the runtime from public/ before the Application is built.
134+status=$(request css "$base_url/css/app.css")
135+expect "GET Static File status" "$status" 200
136+expect "Static File content type" "$(header css content-type)" text/css
137+expect "Static File body" "$(sha256 "$tmp/css.body")" "$(sha256 "$(dirname "$0")/../public/css/app.css")"
138+expect "Static File nosniff" "$(header css x-content-type-options)" nosniff
139+expect "Static File revalidated" "$(header css cache-control)" "public, max-age=0, must-revalidate"
140+etag=$(header css etag)
141+status=$(request css304 -H "If-None-Match: $etag" "$base_url/css/app.css")
142+expect "Static File with a matching If-None-Match" "$status" 304
143+status=$(request csshead -I "$base_url/css/app.css")
144+expect "HEAD Static File" "$status $(header csshead content-type)" "200 text/css"
145+
146+status=$(request gzip -H 'Accept-Encoding: gzip' "$base_url/css/app.css")
147+expect "precompressed variant encoding" "$(header gzip content-encoding)" gzip
148+expect "precompressed variant varies" "$(header gzip vary)" Accept-Encoding
149+expect "precompressed variant body" "$(php -r 'echo hash("sha256", (string) gzdecode(file_get_contents($argv[1])));' "$tmp/gzip.body")" "$(sha256 "$(dirname "$0")/../public/css/app.css")"
150+
151+# zstd is preferred to gzip, and Scaleway's php85 can compress with it too.
152+status=$(request zstd -H 'Accept-Encoding: gzip, zstd' "$base_url/css/app.css")
153+expect "zstd variant preferred to gzip" "$(header zstd content-encoding)" zstd
154+if php -r 'exit(function_exists("zstd_uncompress") ? 0 : 1);'; then
155+ expect "zstd variant body" "$(php -r 'echo hash("sha256", (string) zstd_uncompress(file_get_contents($argv[1])));' "$tmp/zstd.body")" "$(sha256 "$(dirname "$0")/../public/css/app.css")"
156+else
157+ echo "skip zstd variant body: the local php lacks the zstd extension"
158+fi
159+
160+status=$(request js "$base_url/js/greeting.js")
161+expect "JavaScript module content type" "$status $(header js content-type)" "200 text/javascript"
162+status=$(request png "$base_url/images/logo.png")
163+expect "image content type" "$status $(header png content-type)" "200 image/png"
164+expect "image body, base64 decoded by the platform" "$(sha256 "$tmp/png.body")" "$(sha256 "$(dirname "$0")/../public/images/logo.png")"
165+status=$(request digested "$base_url/assets/app-Ex4mPl3.css")
166+expect "digested Static File cached for good" "$(header digested cache-control)" "public, max-age=31536000, immutable"
167+
168+# Both reach the Application, which has no such route.
169+status=$(request frontcontroller "$base_url/index.php")
170+expect "the Front Controller is never served as a file" "$status" 404
171+status=$(request dotenv --path-as-is "$base_url/../.env")
172+expect "files outside public/ are not served" "$status" 404
173+
133 status=$(request postroot -X POST -H 'Content-Type: application/json' --data '{"job":"cleanup"}' "$base_url/")174 status=$(request postroot -X POST -H 'Content-Type: application/json' --data '{"job":"cleanup"}' "$base_url/")
134 expect "POST / JSON body" "$(field postroot args.job)" cleanup175 expect "POST / JSON body" "$(field postroot args.job)" cleanup
135 176
added example/public/assets/app-Ex4mPl3.css +2 -0
new file mode 100644
@@ -0,0 +1,2 @@
1+/* The digested copy AssetMapper would write, listed in manifest.json: cached for good. */
2+body { background: Canvas; }
new file mode 100644
@@ -0,0 +1,2 @@
1+/* The digested copy AssetMapper would write, listed in manifest.json: cached for good. */
2+body { background: Canvas; }
added example/public/assets/manifest.json +3 -0
new file mode 100644
@@ -0,0 +1,3 @@
1+{
2+ "app.css": "/assets/app-Ex4mPl3.css"
3+}
new file mode 100644
@@ -0,0 +1,3 @@
1+{
2+ "app.css": "/assets/app-Ex4mPl3.css"
3+}
added example/public/css/app.css +15 -0
new file mode 100644
@@ -0,0 +1,15 @@
1+/* Served by the function as a Static File, without building the Application. */
2+:root {
3+ color-scheme: light dark;
4+ font-family: system-ui, sans-serif;
5+}
6+
7+body {
8+ margin: 2rem auto;
9+ max-width: 40rem;
10+ line-height: 1.5;
11+}
12+
13+code {
14+ font-family: ui-monospace, monospace;
15+}
new file mode 100644
@@ -0,0 +1,15 @@
1+/* Served by the function as a Static File, without building the Application. */
2+:root {
3+ color-scheme: light dark;
4+ font-family: system-ui, sans-serif;
5+}
6+
7+body {
8+ margin: 2rem auto;
9+ max-width: 40rem;
10+ line-height: 1.5;
11+}
12+
13+code {
14+ font-family: ui-monospace, monospace;
15+}
added example/public/css/app.css.gz +0 -0
new file mode 100644
Binary files /dev/null and b/example/public/css/app.css.gz differ
new file mode 100644
Binary files /dev/null and b/example/public/css/app.css.gz differBinary files /dev/null and b/example/public/css/app.css.gz differ
added example/public/css/app.css.zst +0 -0
new file mode 100644
Binary files /dev/null and b/example/public/css/app.css.zst differ
new file mode 100644
Binary files /dev/null and b/example/public/css/app.css.zst differBinary files /dev/null and b/example/public/css/app.css.zst differ
added example/public/images/logo.png +0 -0
new file mode 100644
Binary files /dev/null and b/example/public/images/logo.png differ
new file mode 100644
Binary files /dev/null and b/example/public/images/logo.png differBinary files /dev/null and b/example/public/images/logo.png differ
added example/public/js/greeting.js +1 -0
new file mode 100644
@@ -0,0 +1 @@
1+export const greeting = "Hello from a Static File";
new file mode 100644
@@ -0,0 +1 @@
1+export const greeting = "Hello from a Static File";
modified probe/README.md +20 -0
@@ -82,6 +82,25 @@ sleep 330; curl -sS "$PROBE_URL/?mode=history" > 09-history.ndjson
8282 curl -sS "$PROBE_URL/" -H 'X-Example-Cron-Header: forged' > 11-forged-cron-marker.json
8383 ```
8484
85+12. Static Files: the largest Function Response, and what the platform does with response encodings.
86+
87+```sh
88+# Text and base64 bodies of 5 to 12 MiB (decoded size): which sizes reach the client whole?
89+for size in 5 6 7 8 10 12; do
90+ for encoding in text base64; do
91+ curl -sS -o /dev/null -w "${size} MiB ${encoding}: HTTP %{http_code}, %{size_download} bytes\n" \
92+ "$PROBE_URL/?mode=size&encoding=${encoding}&bytes=$((size * 1024 * 1024))"
93+ done
94+done > 12-response-sizes.txt
95+# Does the platform compress responses itself? Look for Content-Encoding in the headers.
96+curl -sS -o /dev/null -D 12-platform-compression.txt -H 'Accept-Encoding: gzip, br' "$PROBE_URL/?mode=size&bytes=102400"
97+# Does a Content-Encoding set by the function reach the client, with a body that decodes to X-Probe-Sha256?
98+for encoding in gzip zstd br; do
99+ curl -sS -D 12-encoded-$encoding.headers -o 12-encoded-$encoding.body -H "Accept-Encoding: $encoding" "$PROBE_URL/?mode=encoded&encoding=$encoding"
100+done
101+php -r 'echo hash("sha256", gzdecode(file_get_contents("12-encoded-gzip.body"))), PHP_EOL;' > 12-encoded-gzip.sha256
102+```
103+
85104 ## Report back
86105
87106 - All files of `probe-results/` (except `random.bin` and `body-*.txt`) and the exported logs.
@@ -104,6 +123,7 @@ The answers the files settle:
104123 | Read-only code dir, writable `/tmp`, free space | `01-facts.json` `filesystem` |
105124 | Shipped `vendor/` kept, Composer run at deploy (scripts, `--no-dev`) | `01-facts.json` `vendorMarkerKept`, `composerLockPresent`, `composerRun`, `vendorListing` |
106125 | stdout, uncaught exceptions | `07-*.txt`, logs |
126+| Largest Function Response, platform compression, `Content-Encoding` pass-through, `brotli` extension | `12-*`, `01-facts.json` `extensions` |
107127
108128 ## Clean up
109129
@@ -82,6 +82,25 @@ sleep 330; curl -sS "$PROBE_URL/?mode=history" > 09-history.ndjson
82 curl -sS "$PROBE_URL/" -H 'X-Example-Cron-Header: forged' > 11-forged-cron-marker.json82 curl -sS "$PROBE_URL/" -H 'X-Example-Cron-Header: forged' > 11-forged-cron-marker.json
83 ```83 ```
84 84
85+12. Static Files: the largest Function Response, and what the platform does with response encodings.
86+
87+```sh
88+# Text and base64 bodies of 5 to 12 MiB (decoded size): which sizes reach the client whole?
89+for size in 5 6 7 8 10 12; do
90+ for encoding in text base64; do
91+ curl -sS -o /dev/null -w "${size} MiB ${encoding}: HTTP %{http_code}, %{size_download} bytes\n" \
92+ "$PROBE_URL/?mode=size&encoding=${encoding}&bytes=$((size * 1024 * 1024))"
93+ done
94+done > 12-response-sizes.txt
95+# Does the platform compress responses itself? Look for Content-Encoding in the headers.
96+curl -sS -o /dev/null -D 12-platform-compression.txt -H 'Accept-Encoding: gzip, br' "$PROBE_URL/?mode=size&bytes=102400"
97+# Does a Content-Encoding set by the function reach the client, with a body that decodes to X-Probe-Sha256?
98+for encoding in gzip zstd br; do
99+ curl -sS -D 12-encoded-$encoding.headers -o 12-encoded-$encoding.body -H "Accept-Encoding: $encoding" "$PROBE_URL/?mode=encoded&encoding=$encoding"
100+done
101+php -r 'echo hash("sha256", gzdecode(file_get_contents("12-encoded-gzip.body"))), PHP_EOL;' > 12-encoded-gzip.sha256
102+```
103+
85 ## Report back104 ## Report back
86 105
87 - All files of `probe-results/` (except `random.bin` and `body-*.txt`) and the exported logs.106 - All files of `probe-results/` (except `random.bin` and `body-*.txt`) and the exported logs.
@@ -104,6 +123,7 @@ The answers the files settle:
104 | Read-only code dir, writable `/tmp`, free space | `01-facts.json` `filesystem` |123 | Read-only code dir, writable `/tmp`, free space | `01-facts.json` `filesystem` |
105 | Shipped `vendor/` kept, Composer run at deploy (scripts, `--no-dev`) | `01-facts.json` `vendorMarkerKept`, `composerLockPresent`, `composerRun`, `vendorListing` |124 | Shipped `vendor/` kept, Composer run at deploy (scripts, `--no-dev`) | `01-facts.json` `vendorMarkerKept`, `composerLockPresent`, `composerRun`, `vendorListing` |
106 | stdout, uncaught exceptions | `07-*.txt`, logs |125 | stdout, uncaught exceptions | `07-*.txt`, logs |
126+| Largest Function Response, platform compression, `Content-Encoding` pass-through, `brotli` extension | `12-*`, `01-facts.json` `extensions` |
107 127
108 ## Clean up128 ## Clean up
109 129
modified probe/function/handler.php +31 -0
@@ -46,6 +46,37 @@ function handle($event, $context)
4646 'isBase64Encoded' => true,
4747 ];
4848
49+ case 'size':
50+ // The largest Function Response the platform accepts bounds the Static Files the runtime can serve.
51+ // Capped so the public probe cannot exhaust its memory.
52+ $bytes = min(max((int) ($query['bytes'] ?? 0), 0), 32 << 20);
53+ if ('base64' === ($query['encoding'] ?? 'text')) {
54+ return [
55+ 'statusCode' => 200,
56+ 'headers' => ['Content-Type' => 'application/octet-stream'],
57+ 'body' => base64_encode(str_repeat("\xFF", $bytes)),
58+ 'isBase64Encoded' => true,
59+ ];
60+ }
61+
62+ return ['statusCode' => 200, 'headers' => ['Content-Type' => 'text/plain'], 'body' => str_repeat('a', $bytes)];
63+
64+ case 'encoded':
65+ // Does a Content-Encoding set by the function reach the client with the body untouched?
66+ $text = str_repeat("Static File compressed by the function.\n", 1000);
67+ $encoders = ['gzip' => 'gzencode', 'br' => 'brotli_compress', 'zstd' => 'zstd_compress'];
68+ $encoding = isset($encoders[$query['encoding'] ?? '']) ? $query['encoding'] : 'gzip';
69+ if (!function_exists($encoders[$encoding])) {
70+ return ['statusCode' => 501, 'headers' => ['Content-Type' => 'text/plain'], 'body' => "No extension compresses with {$encoding}.\n"];
71+ }
72+
73+ return [
74+ 'statusCode' => 200,
75+ 'headers' => ['Content-Type' => 'text/plain', 'Content-Encoding' => $encoding, 'Vary' => 'Accept-Encoding', 'X-Probe-Sha256' => hash('sha256', $text)],
76+ 'body' => base64_encode($encoders[$encoding]($text)),
77+ 'isBase64Encoded' => true,
78+ ];
79+
4980 case 'status':
5081 return ['statusCode' => (int) ($query['code'] ?? 418), 'headers' => ['Content-Type' => 'text/plain'], 'body' => "status\n"];
5182
@@ -46,6 +46,37 @@ function handle($event, $context)
46 'isBase64Encoded' => true,46 'isBase64Encoded' => true,
47 ];47 ];
48 48
49+ case 'size':
50+ // The largest Function Response the platform accepts bounds the Static Files the runtime can serve.
51+ // Capped so the public probe cannot exhaust its memory.
52+ $bytes = min(max((int) ($query['bytes'] ?? 0), 0), 32 << 20);
53+ if ('base64' === ($query['encoding'] ?? 'text')) {
54+ return [
55+ 'statusCode' => 200,
56+ 'headers' => ['Content-Type' => 'application/octet-stream'],
57+ 'body' => base64_encode(str_repeat("\xFF", $bytes)),
58+ 'isBase64Encoded' => true,
59+ ];
60+ }
61+
62+ return ['statusCode' => 200, 'headers' => ['Content-Type' => 'text/plain'], 'body' => str_repeat('a', $bytes)];
63+
64+ case 'encoded':
65+ // Does a Content-Encoding set by the function reach the client with the body untouched?
66+ $text = str_repeat("Static File compressed by the function.\n", 1000);
67+ $encoders = ['gzip' => 'gzencode', 'br' => 'brotli_compress', 'zstd' => 'zstd_compress'];
68+ $encoding = isset($encoders[$query['encoding'] ?? '']) ? $query['encoding'] : 'gzip';
69+ if (!function_exists($encoders[$encoding])) {
70+ return ['statusCode' => 501, 'headers' => ['Content-Type' => 'text/plain'], 'body' => "No extension compresses with {$encoding}.\n"];
71+ }
72+
73+ return [
74+ 'statusCode' => 200,
75+ 'headers' => ['Content-Type' => 'text/plain', 'Content-Encoding' => $encoding, 'Vary' => 'Accept-Encoding', 'X-Probe-Sha256' => hash('sha256', $text)],
76+ 'body' => base64_encode($encoders[$encoding]($text)),
77+ 'isBase64Encoded' => true,
78+ ];
79+
49 case 'status':80 case 'status':
50 return ['statusCode' => (int) ($query['code'] ?? 418), 'headers' => ['Content-Type' => 'text/plain'], 'body' => "status\n"];81 return ['statusCode' => (int) ($query['code'] ?? 418), 'headers' => ['Content-Type' => 'text/plain'], 'body' => "status\n"];
51 82
modified src/Handler.php +6 -0
@@ -20,6 +20,7 @@ final class Handler
2020 private static ?self $instance = null;
2121
2222 private ?ScalewayRuntime $runtime = null;
23+ private ?StaticFiles $staticFiles = null;
2324 private ?InvocationRunner $runner = null;
2425
2526 /**
@@ -57,6 +58,11 @@ final class Handler
5758 {
5859 try {
5960 $this->runtime ??= new ScalewayRuntime($this->runtimeOptions());
61+ // Before the Application is built, so Static Files cost no boot and are served even when it cannot be built.
62+ $this->staticFiles ??= $this->runtime->createStaticFiles($this->errorLog);
63+ if (null !== $response = $this->staticFiles->serve($event)) {
64+ return $response;
65+ }
6066 $this->runner ??= $this->runtime->createInvocationRunner($this->errorLog);
6167
6268 return $this->runner->invoke($event, $context);
@@ -20,6 +20,7 @@ final class Handler
20 private static ?self $instance = null;20 private static ?self $instance = null;
21 21
22 private ?ScalewayRuntime $runtime = null;22 private ?ScalewayRuntime $runtime = null;
23+ private ?StaticFiles $staticFiles = null;
23 private ?InvocationRunner $runner = null;24 private ?InvocationRunner $runner = null;
24 25
25 /**26 /**
@@ -57,6 +58,11 @@ final class Handler
57 {58 {
58 try {59 try {
59 $this->runtime ??= new ScalewayRuntime($this->runtimeOptions());60 $this->runtime ??= new ScalewayRuntime($this->runtimeOptions());
61+ // Before the Application is built, so Static Files cost no boot and are served even when it cannot be built.
62+ $this->staticFiles ??= $this->runtime->createStaticFiles($this->errorLog);
63+ if (null !== $response = $this->staticFiles->serve($event)) {
64+ return $response;
65+ }
60 $this->runner ??= $this->runtime->createInvocationRunner($this->errorLog);66 $this->runner ??= $this->runtime->createInvocationRunner($this->errorLog);
61 67
62 return $this->runner->invoke($event, $context);68 return $this->runner->invoke($event, $context);
modified src/Packager.php +3 -0
@@ -148,6 +148,9 @@ final readonly class Packager
148148 // Keeps the executable bits, as for bin/console.
149149 $zip->setExternalAttributesName($name, \ZipArchive::OPSYS_UNIX, ($file->getPerms() & 0o777 | 0o100000) << 16);
150150 $codeSize += $file->getSize();
151+ if (str_starts_with($name, 'public/') && ($size = StaticFiles::responseSize($file->getPathname())) > StaticFiles::MAX_RESPONSE_SIZE) {
152+ $this->log(\sprintf('WARNING: %s takes %.1f MiB in a Function Response, over the %.0f MiB Scaleway accepts: the function will answer it with a 500, serve it from Object Storage', $name, $size / 1024 ** 2, StaticFiles::MAX_RESPONSE_SIZE / 1024 ** 2));
153+ }
151154 }
152155
153156 if (!$zip->close()) {
@@ -148,6 +148,9 @@ final readonly class Packager
148 // Keeps the executable bits, as for bin/console.148 // Keeps the executable bits, as for bin/console.
149 $zip->setExternalAttributesName($name, \ZipArchive::OPSYS_UNIX, ($file->getPerms() & 0o777 | 0o100000) << 16);149 $zip->setExternalAttributesName($name, \ZipArchive::OPSYS_UNIX, ($file->getPerms() & 0o777 | 0o100000) << 16);
150 $codeSize += $file->getSize();150 $codeSize += $file->getSize();
151+ if (str_starts_with($name, 'public/') && ($size = StaticFiles::responseSize($file->getPathname())) > StaticFiles::MAX_RESPONSE_SIZE) {
152+ $this->log(\sprintf('WARNING: %s takes %.1f MiB in a Function Response, over the %.0f MiB Scaleway accepts: the function will answer it with a 500, serve it from Object Storage', $name, $size / 1024 ** 2, StaticFiles::MAX_RESPONSE_SIZE / 1024 ** 2));
153+ }
151 }154 }
152 155
153 if (!$zip->close()) {156 if (!$zip->close()) {
modified src/ScalewayRuntime.php +19 -2
@@ -26,7 +26,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
2626 * On top of the options managed by SymfonyRuntime, it accepts:
2727 * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php";
2828 * - "host": the public host of the function, as no Host header reaches it; defaults to the SCALEWAY_HOST
29- * environment variable, then to "localhost".
29+ * environment variable, then to "localhost";
30+ * - "static_compression": false (the default), "gzip", "br" or "zstd", the encoding Static Files of a textual type are
31+ * compressed with on the fly when they have no precompressed variant.
3032 *
3133 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
3234 *
@@ -52,7 +54,7 @@ class ScalewayRuntime extends SymfonyRuntime
5254 private ?Request $request = null;
5355
5456 /**
55- * @param array<mixed> $options see SymfonyRuntime, plus "front_controller" and "host"
57+ * @param array<mixed> $options see SymfonyRuntime, plus "front_controller", "host" and "static_compression"
5658 */
5759 public function __construct(array $options = [])
5860 {
@@ -83,6 +85,21 @@ class ScalewayRuntime extends SymfonyRuntime
8385 }
8486 }
8587
88+ /**
89+ * Serves the Static Files of the project's public/ directory, the web root of Symfony applications.
90+ *
91+ * @param resource $errorLog
92+ */
93+ public function createStaticFiles(mixed $errorLog): StaticFiles
94+ {
95+ $projectDir = $this->options['project_dir'] ?? null;
96+ if (!\is_string($projectDir)) {
97+ throw new \LogicException('The "project_dir" runtime option must be a string.');
98+ }
99+
100+ return StaticFiles::create($projectDir.'/public', $this->options['static_compression'] ?? false, $errorLog);
101+ }
102+
86103 /**
87104 * Builds the Application from the Front Controller and picks the runner matching its type.
88105 *
@@ -26,7 +26,9 @@ use Symfony\Component\Runtime\SymfonyRuntime;
26 * On top of the options managed by SymfonyRuntime, it accepts:26 * On top of the options managed by SymfonyRuntime, it accepts:
27 * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php";27 * - "front_controller": the Front Controller path, relative to "project_dir"; defaults to "public/index.php";
28 * - "host": the public host of the function, as no Host header reaches it; defaults to the SCALEWAY_HOST28 * - "host": the public host of the function, as no Host header reaches it; defaults to the SCALEWAY_HOST
29- * environment variable, then to "localhost".29+ * environment variable, then to "localhost";
30+ * - "static_compression": false (the default), "gzip", "br" or "zstd", the encoding Static Files of a textual type are
31+ * compressed with on the fly when they have no precompressed variant.
30 *32 *
31 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.33 * Unlike SymfonyRuntime, it defaults the env to prod when the process environment sets none, whatever .env files say.
32 *34 *
@@ -52,7 +54,7 @@ class ScalewayRuntime extends SymfonyRuntime
52 private ?Request $request = null;54 private ?Request $request = null;
53 55
54 /**56 /**
55- * @param array<mixed> $options see SymfonyRuntime, plus "front_controller" and "host"57+ * @param array<mixed> $options see SymfonyRuntime, plus "front_controller", "host" and "static_compression"
56 */58 */
57 public function __construct(array $options = [])59 public function __construct(array $options = [])
58 {60 {
@@ -83,6 +85,21 @@ class ScalewayRuntime extends SymfonyRuntime
83 }85 }
84 }86 }
85 87
88+ /**
89+ * Serves the Static Files of the project's public/ directory, the web root of Symfony applications.
90+ *
91+ * @param resource $errorLog
92+ */
93+ public function createStaticFiles(mixed $errorLog): StaticFiles
94+ {
95+ $projectDir = $this->options['project_dir'] ?? null;
96+ if (!\is_string($projectDir)) {
97+ throw new \LogicException('The "project_dir" runtime option must be a string.');
98+ }
99+
100+ return StaticFiles::create($projectDir.'/public', $this->options['static_compression'] ?? false, $errorLog);
101+ }
102+
86 /**103 /**
87 * Builds the Application from the Front Controller and picks the runner matching its type.104 * Builds the Application from the Front Controller and picks the runner matching its type.
88 *105 *
added src/StaticFiles.php +348 -0
new file mode 100644
@@ -0,0 +1,348 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime;
6+
7+use Symfony\Component\Mime\MimeTypes;
8+
9+/**
10+ * Answers HTTP Invocations asking for a Static File, before the Application is built
11+ * (see docs/adr/0009-serve-static-files-from-the-function.md).
12+ *
13+ * Only GET and HEAD requests for a regular file under the web root are served, never a .php file nor a path with a
14+ * segment starting with a dot; everything else goes to the Application, as with nginx's try_files.
15+ *
16+ * @phpstan-import-type FunctionResponse from HttpConverter
17+ */
18+final class StaticFiles
19+{
20+ /** Encodings of the precompressed variants, in order of preference, with their file extension. */
21+ public const array PRECOMPRESSED = ['br' => '.br', 'zstd' => '.zst', 'gzip' => '.gz'];
22+
23+ /** The values of the "static_compression" runtime option, but false, with the extension and function each needs. */
24+ public const array COMPRESSIONS = ['gzip' => ['zlib', 'gzencode'], 'br' => ['brotli', 'brotli_compress'], 'zstd' => ['zstd', 'zstd_compress']];
25+
26+ // The platform enforces no limit, but larger responses intermittently time out (docs/probe-results.md#size-and-encodings).
27+ public const int MAX_RESPONSE_SIZE = 6 * 1024 * 1024;
28+
29+ /** Smaller files gain less from compression than the headers it adds cost. */
30+ public const int COMPRESSION_MIN_SIZE = 1024;
31+
32+ /** Bounds the memory the compressed bodies kept across Invocations may take in a Warm Process. */
33+ public const int COMPRESSION_CACHE_SIZE = 32 * 1024 * 1024;
34+
35+ /** Types already compressed by their format are left out: compressing them again costs CPU for nothing. */
36+ private const array COMPRESSIBLE_TYPES = ['application/javascript', 'application/json', 'application/xml', 'application/wasm', 'image/svg+xml'];
37+
38+ private ?string $root = null;
39+
40+ /** @var array<string, string> */
41+ private array $etags = [];
42+
43+ /** @var array<string, string> */
44+ private array $compressed = [];
45+
46+ private int $compressedSize = 0;
47+
48+ /** @var array<string, array<string, true>> the digested public paths of each manifest.json, by manifest file */
49+ private array $manifests = [];
50+
51+ /**
52+ * @param string $webRoot the directory holding the Static Files
53+ * @param 'gzip'|'br'|'zstd'|null $compression the encoding to compress textual files with on the fly, if any
54+ * @param resource $errorLog
55+ */
56+ public function __construct(
57+ private readonly string $webRoot,
58+ private readonly ?string $compression,
59+ private readonly mixed $errorLog,
60+ ) {
61+ }
62+
63+ /**
64+ * @param mixed $compression the "static_compression" runtime option
65+ * @param resource $errorLog
66+ */
67+ public static function create(string $webRoot, mixed $compression, mixed $errorLog): self
68+ {
69+ if (false === $compression || null === $compression) {
70+ return new self($webRoot, null, $errorLog);
71+ }
72+ if (!\is_string($compression) || !isset(self::COMPRESSIONS[$compression])) {
73+ throw new \InvalidArgumentException(\sprintf('The "static_compression" runtime option must be false, "gzip", "br" or "zstd", "%s" given.', get_debug_type($compression)));
74+ }
75+ // Falling back to another encoding would hide that the function serves something else than what was asked.
76+ [$extension, $function] = self::COMPRESSIONS[$compression];
77+ if (!\function_exists($function)) {
78+ throw new \LogicException(\sprintf('The "static_compression" runtime option is "%s", but the %s extension is not loaded.', $compression, $extension));
79+ }
80+
81+ return new self($webRoot, $compression, $errorLog);
82+ }
83+
84+ /**
85+ * @param array<mixed> $event
86+ *
87+ * @return FunctionResponse|null null when the Invocation is not for a Static File
88+ */
89+ public function serve(array $event): ?array
90+ {
91+ $method = strtoupper(\is_string($event['httpMethod'] ?? null) ? $event['httpMethod'] : (\is_string($event['method'] ?? null) ? $event['method'] : 'GET'));
92+ $path = \is_string($event['path'] ?? null) ? rawurldecode($event['path']) : '';
93+ if (!\in_array($method, ['GET', 'HEAD'], true) || null === $file = $this->resolve($path)) {
94+ return null;
95+ }
96+
97+ $headers = array_change_key_case(\is_array($event['headers'] ?? null) ? $event['headers'] : []);
98+ $type = MimeTypes::getDefault()->getMimeTypes(pathinfo($file, \PATHINFO_EXTENSION))[0] ?? 'application/octet-stream';
99+ $compressible = null !== $this->compression && $this->isCompressible($type);
100+ [$encoding, $bodyFile] = $this->negotiate($file, \is_string($headers['accept-encoding'] ?? null) ? $headers['accept-encoding'] : '', $compressible);
101+
102+ $etag = $this->etag($bodyFile ?? $file, $encoding);
103+ $responseHeaders = [
104+ 'Content-Type' => $type,
105+ 'Cache-Control' => $this->isDigested($path, $file) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
106+ 'ETag' => $etag,
107+ 'X-Content-Type-Options' => 'nosniff',
108+ ];
109+ if ($compressible || $this->hasVariant($file)) {
110+ $responseHeaders['Vary'] = 'Accept-Encoding';
111+ }
112+ if (null !== $encoding) {
113+ $responseHeaders['Content-Encoding'] = $encoding;
114+ }
115+
116+ if (self::matches(\is_string($headers['if-none-match'] ?? null) ? $headers['if-none-match'] : '', $etag)) {
117+ unset($responseHeaders['Content-Type']);
118+
119+ return ['statusCode' => 304, 'headers' => $responseHeaders, 'body' => ''];
120+ }
121+ if ('HEAD' === $method) {
122+ return ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => ''];
123+ }
124+
125+ $compressing = null === $bodyFile && null !== $encoding;
126+ // Checked before reading, so a large file cannot exhaust the memory of the Warm Process; a file compressed
127+ // on the fly may shrink below the limit, so it gets more room.
128+ $size = (int) filesize($bodyFile ?? $file);
129+ if ($size > ($compressing ? 4 : 1) * self::MAX_RESPONSE_SIZE) {
130+ return $this->tooLarge($path, $size);
131+ }
132+
133+ $body = $compressing ? $this->compress($file, $encoding) : (string) file_get_contents($bodyFile ?? $file);
134+ $base64 = null !== $encoding || 1 !== preg_match('//u', $body);
135+ $size = $base64 ? 4 * (int) ceil(\strlen($body) / 3) : \strlen($body);
136+ if ($size > self::MAX_RESPONSE_SIZE) {
137+ return $this->tooLarge($path, $size);
138+ }
139+
140+ return $base64
141+ ? ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => base64_encode($body), 'isBase64Encoded' => true]
142+ : ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => $body];
143+ }
144+
145+ /**
146+ * @return FunctionResponse
147+ */
148+ private function tooLarge(string $path, int $size): array
149+ {
150+ // The platform would answer an opaque error: the log says which file and why.
151+ fwrite($this->errorLog, \sprintf('Static File "%s" is %d bytes once encoded, over the %d bytes a Function Response may carry.', $path, $size, self::MAX_RESPONSE_SIZE).\PHP_EOL);
152+
153+ return ['statusCode' => 500, 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'], 'body' => 'Internal Server Error'];
154+ }
155+
156+ /**
157+ * The size a file takes in a Function Response, base64 included, for scaleway-package to warn about.
158+ */
159+ public static function responseSize(string $file): int
160+ {
161+ $size = (int) filesize($file);
162+ if ($size > self::MAX_RESPONSE_SIZE) {
163+ return $size;
164+ }
165+
166+ return 1 === preg_match('//u', (string) file_get_contents($file)) ? $size : 4 * (int) ceil($size / 3);
167+ }
168+
169+ private function resolve(string $path): ?string
170+ {
171+ if (str_contains($path, "\0") || str_ends_with(strtolower($path), '.php')) {
172+ return null;
173+ }
174+ // Dot segments cover "..", and hidden files such as .htaccess or .env that a web server would not serve either;
175+ // /.well-known/ is the one public prefix starting with a dot (RFC 8615).
176+ foreach (explode('/', ltrim($path, '/')) as $i => $segment) {
177+ if (str_starts_with($segment, '.') && (0 !== $i || '.well-known' !== $segment)) {
178+ return null;
179+ }
180+ }
181+
182+ $this->root ??= realpath($this->webRoot) ?: '';
183+ if ('' === $this->root) {
184+ return null;
185+ }
186+ // A symbolic link leading out of the web root is not served either.
187+ $file = realpath($this->root.'/'.ltrim($path, '/'));
188+
189+ return false !== $file && str_starts_with($file, $this->root.\DIRECTORY_SEPARATOR) && is_file($file) ? $file : null;
190+ }
191+
192+ /**
193+ * Picks the encoding the client accepts, a precompressed variant first.
194+ *
195+ * @return array{?string, ?string} the encoding, and the precompressed file holding the body if any
196+ */
197+ private function negotiate(string $file, string $acceptEncoding, bool $compressible): array
198+ {
199+ $accepted = self::acceptedEncodings($acceptEncoding);
200+ foreach (self::PRECOMPRESSED as $encoding => $extension) {
201+ if ($accepted($encoding) && is_file($file.$extension)) {
202+ return [$encoding, $file.$extension];
203+ }
204+ }
205+ if ($compressible && \is_string($this->compression) && $accepted($this->compression) && filesize($file) >= self::COMPRESSION_MIN_SIZE) {
206+ return [$this->compression, null];
207+ }
208+
209+ return [null, null];
210+ }
211+
212+ /**
213+ * Only q=0 refuses an encoding: the order of preference is the runtime's, not the client's weights.
214+ *
215+ * @return \Closure(string): bool
216+ */
217+ private static function acceptedEncodings(string $header): \Closure
218+ {
219+ $weights = [];
220+ foreach (explode(',', $header) as $item) {
221+ $parts = explode(';', $item);
222+ $name = strtolower(trim($parts[0]));
223+ if ('' === $name) {
224+ continue;
225+ }
226+ $weights[$name] = 1.0;
227+ foreach (\array_slice($parts, 1) as $parameter) {
228+ if (1 === preg_match('/^\s*q\s*=\s*([0-9.]+)\s*$/i', $parameter, $match)) {
229+ $weights[$name] = (float) $match[1];
230+ }
231+ }
232+ }
233+
234+ return static fn (string $encoding): bool => ($weights[$encoding] ?? $weights['*'] ?? 0.0) > 0.0;
235+ }
236+
237+ private function hasVariant(string $file): bool
238+ {
239+ return array_any(self::PRECOMPRESSED, static fn (string $extension): bool => is_file($file.$extension));
240+ }
241+
242+ private function isCompressible(string $type): bool
243+ {
244+ return str_starts_with($type, 'text/') || \in_array($type, self::COMPRESSIBLE_TYPES, true)
245+ || str_ends_with($type, '+json') || str_ends_with($type, '+xml');
246+ }
247+
248+ private function compress(string $file, string $encoding): string
249+ {
250+ $key = $this->key($file).':'.$encoding;
251+ if (isset($this->compressed[$key])) {
252+ return $this->compressed[$key];
253+ }
254+
255+ $content = (string) file_get_contents($file);
256+ $body = (string) (self::COMPRESSIONS[$encoding][1])($content);
257+ // Past the cap, files are compressed again for each Invocation rather than growing the Warm Process.
258+ if ($this->compressedSize + \strlen($body) <= self::COMPRESSION_CACHE_SIZE) {
259+ $this->compressed[$key] = $body;
260+ $this->compressedSize += \strlen($body);
261+ }
262+
263+ return $body;
264+ }
265+
266+ /**
267+ * A strong ETag of the bytes sent, each encoding having its own as its bytes differ.
268+ */
269+ private function etag(string $file, ?string $encoding): string
270+ {
271+ $key = $this->key($file);
272+ $this->etags[$key] ??= hash_file('xxh128', $file) ?: '';
273+
274+ return '"'.$this->etags[$key].(null === $encoding ? '' : '-'.$encoding).'"';
275+ }
276+
277+ /**
278+ * Files written at runtime, such as uploads, may change within a Warm Process: their key changes with them.
279+ */
280+ private function key(string $file): string
281+ {
282+ clearstatcache(true, $file);
283+
284+ return $file.':'.filemtime($file).':'.filesize($file);
285+ }
286+
287+ /**
288+ * Weak comparison, as RFC 9110 asks for If-None-Match.
289+ */
290+ private static function matches(string $ifNoneMatch, string $etag): bool
291+ {
292+ if ('*' === trim($ifNoneMatch)) {
293+ return true;
294+ }
295+ foreach (explode(',', $ifNoneMatch) as $candidate) {
296+ $candidate = trim($candidate);
297+ if ((str_starts_with($candidate, 'W/') ? substr($candidate, 2) : $candidate) === $etag) {
298+ return true;
299+ }
300+ }
301+
302+ return false;
303+ }
304+
305+ /**
306+ * A file is cached for good only when a manifest.json above it, as written by AssetMapper or Webpack Encore, maps a
307+ * logical path to it under another name: its name then changes with its content. Guessing a digest from the name
308+ * alone would also match plain names such as "font-awesome.css".
309+ */
310+ private function isDigested(string $path, string $file): bool
311+ {
312+ $public = '/'.ltrim($path, '/');
313+ for ($dir = \dirname($file); str_starts_with($dir.\DIRECTORY_SEPARATOR, (string) $this->root.\DIRECTORY_SEPARATOR); $dir = \dirname($dir)) {
314+ if (isset($this->manifest($dir.'/manifest.json')[$public])) {
315+ return true;
316+ }
317+ if ($dir === $this->root) {
318+ break;
319+ }
320+ }
321+
322+ return false;
323+ }
324+
325+ /**
326+ * @return array<string, true>
327+ */
328+ private function manifest(string $file): array
329+ {
330+ if (!isset($this->manifests[$file])) {
331+ $digested = [];
332+ $entries = is_file($file) ? json_decode((string) file_get_contents($file), true) : null;
333+ foreach (\is_array($entries) ? $entries : [] as $logical => $public) {
334+ if (!\is_string($public)) {
335+ continue;
336+ }
337+ // Assets served from a CDN or with a base path are listed as URLs: only their path is ours.
338+ $publicPath = parse_url($public, \PHP_URL_PATH);
339+ if (\is_string($publicPath) && basename($publicPath) !== basename((string) $logical)) {
340+ $digested['/'.ltrim($publicPath, '/')] = true;
341+ }
342+ }
343+ $this->manifests[$file] = $digested;
344+ }
345+
346+ return $this->manifests[$file];
347+ }
348+}
new file mode 100644
@@ -0,0 +1,348 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime;
6+
7+use Symfony\Component\Mime\MimeTypes;
8+
9+/**
10+ * Answers HTTP Invocations asking for a Static File, before the Application is built
11+ * (see docs/adr/0009-serve-static-files-from-the-function.md).
12+ *
13+ * Only GET and HEAD requests for a regular file under the web root are served, never a .php file nor a path with a
14+ * segment starting with a dot; everything else goes to the Application, as with nginx's try_files.
15+ *
16+ * @phpstan-import-type FunctionResponse from HttpConverter
17+ */
18+final class StaticFiles
19+{
20+ /** Encodings of the precompressed variants, in order of preference, with their file extension. */
21+ public const array PRECOMPRESSED = ['br' => '.br', 'zstd' => '.zst', 'gzip' => '.gz'];
22+
23+ /** The values of the "static_compression" runtime option, but false, with the extension and function each needs. */
24+ public const array COMPRESSIONS = ['gzip' => ['zlib', 'gzencode'], 'br' => ['brotli', 'brotli_compress'], 'zstd' => ['zstd', 'zstd_compress']];
25+
26+ // The platform enforces no limit, but larger responses intermittently time out (docs/probe-results.md#size-and-encodings).
27+ public const int MAX_RESPONSE_SIZE = 6 * 1024 * 1024;
28+
29+ /** Smaller files gain less from compression than the headers it adds cost. */
30+ public const int COMPRESSION_MIN_SIZE = 1024;
31+
32+ /** Bounds the memory the compressed bodies kept across Invocations may take in a Warm Process. */
33+ public const int COMPRESSION_CACHE_SIZE = 32 * 1024 * 1024;
34+
35+ /** Types already compressed by their format are left out: compressing them again costs CPU for nothing. */
36+ private const array COMPRESSIBLE_TYPES = ['application/javascript', 'application/json', 'application/xml', 'application/wasm', 'image/svg+xml'];
37+
38+ private ?string $root = null;
39+
40+ /** @var array<string, string> */
41+ private array $etags = [];
42+
43+ /** @var array<string, string> */
44+ private array $compressed = [];
45+
46+ private int $compressedSize = 0;
47+
48+ /** @var array<string, array<string, true>> the digested public paths of each manifest.json, by manifest file */
49+ private array $manifests = [];
50+
51+ /**
52+ * @param string $webRoot the directory holding the Static Files
53+ * @param 'gzip'|'br'|'zstd'|null $compression the encoding to compress textual files with on the fly, if any
54+ * @param resource $errorLog
55+ */
56+ public function __construct(
57+ private readonly string $webRoot,
58+ private readonly ?string $compression,
59+ private readonly mixed $errorLog,
60+ ) {
61+ }
62+
63+ /**
64+ * @param mixed $compression the "static_compression" runtime option
65+ * @param resource $errorLog
66+ */
67+ public static function create(string $webRoot, mixed $compression, mixed $errorLog): self
68+ {
69+ if (false === $compression || null === $compression) {
70+ return new self($webRoot, null, $errorLog);
71+ }
72+ if (!\is_string($compression) || !isset(self::COMPRESSIONS[$compression])) {
73+ throw new \InvalidArgumentException(\sprintf('The "static_compression" runtime option must be false, "gzip", "br" or "zstd", "%s" given.', get_debug_type($compression)));
74+ }
75+ // Falling back to another encoding would hide that the function serves something else than what was asked.
76+ [$extension, $function] = self::COMPRESSIONS[$compression];
77+ if (!\function_exists($function)) {
78+ throw new \LogicException(\sprintf('The "static_compression" runtime option is "%s", but the %s extension is not loaded.', $compression, $extension));
79+ }
80+
81+ return new self($webRoot, $compression, $errorLog);
82+ }
83+
84+ /**
85+ * @param array<mixed> $event
86+ *
87+ * @return FunctionResponse|null null when the Invocation is not for a Static File
88+ */
89+ public function serve(array $event): ?array
90+ {
91+ $method = strtoupper(\is_string($event['httpMethod'] ?? null) ? $event['httpMethod'] : (\is_string($event['method'] ?? null) ? $event['method'] : 'GET'));
92+ $path = \is_string($event['path'] ?? null) ? rawurldecode($event['path']) : '';
93+ if (!\in_array($method, ['GET', 'HEAD'], true) || null === $file = $this->resolve($path)) {
94+ return null;
95+ }
96+
97+ $headers = array_change_key_case(\is_array($event['headers'] ?? null) ? $event['headers'] : []);
98+ $type = MimeTypes::getDefault()->getMimeTypes(pathinfo($file, \PATHINFO_EXTENSION))[0] ?? 'application/octet-stream';
99+ $compressible = null !== $this->compression && $this->isCompressible($type);
100+ [$encoding, $bodyFile] = $this->negotiate($file, \is_string($headers['accept-encoding'] ?? null) ? $headers['accept-encoding'] : '', $compressible);
101+
102+ $etag = $this->etag($bodyFile ?? $file, $encoding);
103+ $responseHeaders = [
104+ 'Content-Type' => $type,
105+ 'Cache-Control' => $this->isDigested($path, $file) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
106+ 'ETag' => $etag,
107+ 'X-Content-Type-Options' => 'nosniff',
108+ ];
109+ if ($compressible || $this->hasVariant($file)) {
110+ $responseHeaders['Vary'] = 'Accept-Encoding';
111+ }
112+ if (null !== $encoding) {
113+ $responseHeaders['Content-Encoding'] = $encoding;
114+ }
115+
116+ if (self::matches(\is_string($headers['if-none-match'] ?? null) ? $headers['if-none-match'] : '', $etag)) {
117+ unset($responseHeaders['Content-Type']);
118+
119+ return ['statusCode' => 304, 'headers' => $responseHeaders, 'body' => ''];
120+ }
121+ if ('HEAD' === $method) {
122+ return ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => ''];
123+ }
124+
125+ $compressing = null === $bodyFile && null !== $encoding;
126+ // Checked before reading, so a large file cannot exhaust the memory of the Warm Process; a file compressed
127+ // on the fly may shrink below the limit, so it gets more room.
128+ $size = (int) filesize($bodyFile ?? $file);
129+ if ($size > ($compressing ? 4 : 1) * self::MAX_RESPONSE_SIZE) {
130+ return $this->tooLarge($path, $size);
131+ }
132+
133+ $body = $compressing ? $this->compress($file, $encoding) : (string) file_get_contents($bodyFile ?? $file);
134+ $base64 = null !== $encoding || 1 !== preg_match('//u', $body);
135+ $size = $base64 ? 4 * (int) ceil(\strlen($body) / 3) : \strlen($body);
136+ if ($size > self::MAX_RESPONSE_SIZE) {
137+ return $this->tooLarge($path, $size);
138+ }
139+
140+ return $base64
141+ ? ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => base64_encode($body), 'isBase64Encoded' => true]
142+ : ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => $body];
143+ }
144+
145+ /**
146+ * @return FunctionResponse
147+ */
148+ private function tooLarge(string $path, int $size): array
149+ {
150+ // The platform would answer an opaque error: the log says which file and why.
151+ fwrite($this->errorLog, \sprintf('Static File "%s" is %d bytes once encoded, over the %d bytes a Function Response may carry.', $path, $size, self::MAX_RESPONSE_SIZE).\PHP_EOL);
152+
153+ return ['statusCode' => 500, 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'], 'body' => 'Internal Server Error'];
154+ }
155+
156+ /**
157+ * The size a file takes in a Function Response, base64 included, for scaleway-package to warn about.
158+ */
159+ public static function responseSize(string $file): int
160+ {
161+ $size = (int) filesize($file);
162+ if ($size > self::MAX_RESPONSE_SIZE) {
163+ return $size;
164+ }
165+
166+ return 1 === preg_match('//u', (string) file_get_contents($file)) ? $size : 4 * (int) ceil($size / 3);
167+ }
168+
169+ private function resolve(string $path): ?string
170+ {
171+ if (str_contains($path, "\0") || str_ends_with(strtolower($path), '.php')) {
172+ return null;
173+ }
174+ // Dot segments cover "..", and hidden files such as .htaccess or .env that a web server would not serve either;
175+ // /.well-known/ is the one public prefix starting with a dot (RFC 8615).
176+ foreach (explode('/', ltrim($path, '/')) as $i => $segment) {
177+ if (str_starts_with($segment, '.') && (0 !== $i || '.well-known' !== $segment)) {
178+ return null;
179+ }
180+ }
181+
182+ $this->root ??= realpath($this->webRoot) ?: '';
183+ if ('' === $this->root) {
184+ return null;
185+ }
186+ // A symbolic link leading out of the web root is not served either.
187+ $file = realpath($this->root.'/'.ltrim($path, '/'));
188+
189+ return false !== $file && str_starts_with($file, $this->root.\DIRECTORY_SEPARATOR) && is_file($file) ? $file : null;
190+ }
191+
192+ /**
193+ * Picks the encoding the client accepts, a precompressed variant first.
194+ *
195+ * @return array{?string, ?string} the encoding, and the precompressed file holding the body if any
196+ */
197+ private function negotiate(string $file, string $acceptEncoding, bool $compressible): array
198+ {
199+ $accepted = self::acceptedEncodings($acceptEncoding);
200+ foreach (self::PRECOMPRESSED as $encoding => $extension) {
201+ if ($accepted($encoding) && is_file($file.$extension)) {
202+ return [$encoding, $file.$extension];
203+ }
204+ }
205+ if ($compressible && \is_string($this->compression) && $accepted($this->compression) && filesize($file) >= self::COMPRESSION_MIN_SIZE) {
206+ return [$this->compression, null];
207+ }
208+
209+ return [null, null];
210+ }
211+
212+ /**
213+ * Only q=0 refuses an encoding: the order of preference is the runtime's, not the client's weights.
214+ *
215+ * @return \Closure(string): bool
216+ */
217+ private static function acceptedEncodings(string $header): \Closure
218+ {
219+ $weights = [];
220+ foreach (explode(',', $header) as $item) {
221+ $parts = explode(';', $item);
222+ $name = strtolower(trim($parts[0]));
223+ if ('' === $name) {
224+ continue;
225+ }
226+ $weights[$name] = 1.0;
227+ foreach (\array_slice($parts, 1) as $parameter) {
228+ if (1 === preg_match('/^\s*q\s*=\s*([0-9.]+)\s*$/i', $parameter, $match)) {
229+ $weights[$name] = (float) $match[1];
230+ }
231+ }
232+ }
233+
234+ return static fn (string $encoding): bool => ($weights[$encoding] ?? $weights['*'] ?? 0.0) > 0.0;
235+ }
236+
237+ private function hasVariant(string $file): bool
238+ {
239+ return array_any(self::PRECOMPRESSED, static fn (string $extension): bool => is_file($file.$extension));
240+ }
241+
242+ private function isCompressible(string $type): bool
243+ {
244+ return str_starts_with($type, 'text/') || \in_array($type, self::COMPRESSIBLE_TYPES, true)
245+ || str_ends_with($type, '+json') || str_ends_with($type, '+xml');
246+ }
247+
248+ private function compress(string $file, string $encoding): string
249+ {
250+ $key = $this->key($file).':'.$encoding;
251+ if (isset($this->compressed[$key])) {
252+ return $this->compressed[$key];
253+ }
254+
255+ $content = (string) file_get_contents($file);
256+ $body = (string) (self::COMPRESSIONS[$encoding][1])($content);
257+ // Past the cap, files are compressed again for each Invocation rather than growing the Warm Process.
258+ if ($this->compressedSize + \strlen($body) <= self::COMPRESSION_CACHE_SIZE) {
259+ $this->compressed[$key] = $body;
260+ $this->compressedSize += \strlen($body);
261+ }
262+
263+ return $body;
264+ }
265+
266+ /**
267+ * A strong ETag of the bytes sent, each encoding having its own as its bytes differ.
268+ */
269+ private function etag(string $file, ?string $encoding): string
270+ {
271+ $key = $this->key($file);
272+ $this->etags[$key] ??= hash_file('xxh128', $file) ?: '';
273+
274+ return '"'.$this->etags[$key].(null === $encoding ? '' : '-'.$encoding).'"';
275+ }
276+
277+ /**
278+ * Files written at runtime, such as uploads, may change within a Warm Process: their key changes with them.
279+ */
280+ private function key(string $file): string
281+ {
282+ clearstatcache(true, $file);
283+
284+ return $file.':'.filemtime($file).':'.filesize($file);
285+ }
286+
287+ /**
288+ * Weak comparison, as RFC 9110 asks for If-None-Match.
289+ */
290+ private static function matches(string $ifNoneMatch, string $etag): bool
291+ {
292+ if ('*' === trim($ifNoneMatch)) {
293+ return true;
294+ }
295+ foreach (explode(',', $ifNoneMatch) as $candidate) {
296+ $candidate = trim($candidate);
297+ if ((str_starts_with($candidate, 'W/') ? substr($candidate, 2) : $candidate) === $etag) {
298+ return true;
299+ }
300+ }
301+
302+ return false;
303+ }
304+
305+ /**
306+ * A file is cached for good only when a manifest.json above it, as written by AssetMapper or Webpack Encore, maps a
307+ * logical path to it under another name: its name then changes with its content. Guessing a digest from the name
308+ * alone would also match plain names such as "font-awesome.css".
309+ */
310+ private function isDigested(string $path, string $file): bool
311+ {
312+ $public = '/'.ltrim($path, '/');
313+ for ($dir = \dirname($file); str_starts_with($dir.\DIRECTORY_SEPARATOR, (string) $this->root.\DIRECTORY_SEPARATOR); $dir = \dirname($dir)) {
314+ if (isset($this->manifest($dir.'/manifest.json')[$public])) {
315+ return true;
316+ }
317+ if ($dir === $this->root) {
318+ break;
319+ }
320+ }
321+
322+ return false;
323+ }
324+
325+ /**
326+ * @return array<string, true>
327+ */
328+ private function manifest(string $file): array
329+ {
330+ if (!isset($this->manifests[$file])) {
331+ $digested = [];
332+ $entries = is_file($file) ? json_decode((string) file_get_contents($file), true) : null;
333+ foreach (\is_array($entries) ? $entries : [] as $logical => $public) {
334+ if (!\is_string($public)) {
335+ continue;
336+ }
337+ // Assets served from a CDN or with a base path are listed as URLs: only their path is ours.
338+ $publicPath = parse_url($public, \PHP_URL_PATH);
339+ if (\is_string($publicPath) && basename($publicPath) !== basename((string) $logical)) {
340+ $digested['/'.ltrim($publicPath, '/')] = true;
341+ }
342+ }
343+ $this->manifests[$file] = $digested;
344+ }
345+
346+ return $this->manifests[$file];
347+ }
348+}
added tests/Fixtures/public/static.txt +1 -0
new file mode 100644
@@ -0,0 +1 @@
1+Served without the Application.
new file mode 100644
@@ -0,0 +1 @@
1+Served without the Application.
modified tests/HandlerTest.php +25 -0
@@ -99,6 +99,31 @@ final class HandlerTest extends TestCase
9999 self::assertSame(1, RecordingKernel::$builds);
100100 }
101101
102+ public function testStaticFilesAreServedWithoutBuildingTheApplication(): void
103+ {
104+ RecordingKernel::$failingBuilds = 1;
105+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'debug' => false]);
106+
107+ $response = $handler->invoke(['path' => '/static.txt', 'httpMethod' => 'GET'], []);
108+
109+ self::assertSame(200, $response['statusCode']);
110+ self::assertSame("Served without the Application.\n", $response['body']);
111+ self::assertSame(0, RecordingKernel::$builds);
112+ // Only another method reaches the Application, whose build fails once on purpose.
113+ self::assertSame(500, $handler->invoke(['path' => '/static.txt', 'httpMethod' => 'POST'], [])['statusCode']);
114+ self::assertSame(1, RecordingKernel::$builds);
115+ }
116+
117+ public function testInvalidStaticCompressionFailsEveryInvocation(): void
118+ {
119+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'debug' => false, 'static_compression' => 'deflate']);
120+
121+ self::assertSame(500, $handler->invoke(['path' => '/static.txt'], [])['statusCode']);
122+ self::assertSame(500, $handler->invoke(['path' => '/'], [])['statusCode']);
123+ self::assertStringContainsString('The "static_compression" runtime option must be false, "gzip", "br" or "zstd"', $this->errorLog());
124+ self::assertSame(0, RecordingKernel::$builds);
125+ }
126+
102127 public function testUnsupportedApplicationTypeIsReported(): void
103128 {
104129 $this->handler(['front_controller' => 'front-controllers/unsupported.php', 'debug' => false])->invoke([], []);
@@ -99,6 +99,31 @@ final class HandlerTest extends TestCase
99 self::assertSame(1, RecordingKernel::$builds);99 self::assertSame(1, RecordingKernel::$builds);
100 }100 }
101 101
102+ public function testStaticFilesAreServedWithoutBuildingTheApplication(): void
103+ {
104+ RecordingKernel::$failingBuilds = 1;
105+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'debug' => false]);
106+
107+ $response = $handler->invoke(['path' => '/static.txt', 'httpMethod' => 'GET'], []);
108+
109+ self::assertSame(200, $response['statusCode']);
110+ self::assertSame("Served without the Application.\n", $response['body']);
111+ self::assertSame(0, RecordingKernel::$builds);
112+ // Only another method reaches the Application, whose build fails once on purpose.
113+ self::assertSame(500, $handler->invoke(['path' => '/static.txt', 'httpMethod' => 'POST'], [])['statusCode']);
114+ self::assertSame(1, RecordingKernel::$builds);
115+ }
116+
117+ public function testInvalidStaticCompressionFailsEveryInvocation(): void
118+ {
119+ $handler = $this->handler(['front_controller' => 'front-controllers/recording.php', 'debug' => false, 'static_compression' => 'deflate']);
120+
121+ self::assertSame(500, $handler->invoke(['path' => '/static.txt'], [])['statusCode']);
122+ self::assertSame(500, $handler->invoke(['path' => '/'], [])['statusCode']);
123+ self::assertStringContainsString('The "static_compression" runtime option must be false, "gzip", "br" or "zstd"', $this->errorLog());
124+ self::assertSame(0, RecordingKernel::$builds);
125+ }
126+
102 public function testUnsupportedApplicationTypeIsReported(): void127 public function testUnsupportedApplicationTypeIsReported(): void
103 {128 {
104 $this->handler(['front_controller' => 'front-controllers/unsupported.php', 'debug' => false])->invoke([], []);129 $this->handler(['front_controller' => 'front-controllers/unsupported.php', 'debug' => false])->invoke([], []);
modified tests/PackagerTest.php +17 -0
@@ -90,6 +90,23 @@ final class PackagerTest extends TestCase
9090 $zip->close();
9191 }
9292
93+ public function testWarnsAboutStaticFilesTooLargeForAFunctionResponse(): void
94+ {
95+ // Small enough as it is, but not once base64-encoded.
96+ $this->filesystem->dumpFile($this->appDir.'/public/video.bin', str_repeat("\xff", 5 * 1024 * 1024));
97+ $this->filesystem->dumpFile($this->appDir.'/public/app.css', 'body {}');
98+ $this->filesystem->dumpFile($this->appDir.'/src/large.bin', str_repeat("\xff", 5 * 1024 * 1024));
99+
100+ $this->package();
101+
102+ rewind($this->log);
103+ $log = (string) stream_get_contents($this->log);
104+ self::assertStringContainsString('WARNING: public/video.bin takes 6.7 MiB in a Function Response, over the 6 MiB Scaleway accepts', $log);
105+ self::assertStringNotContainsString('app.css', $log);
106+ self::assertStringNotContainsString('src/large.bin', $log);
107+ self::assertFileExists($this->dir.'/function.zip');
108+ }
109+
93110 public function testContentHashIsComposers(): void
94111 {
95112 $composer = json_decode((string) file_get_contents(__DIR__.'/Fixtures/PackagedApp/composer.json'), true);
@@ -90,6 +90,23 @@ final class PackagerTest extends TestCase
90 $zip->close();90 $zip->close();
91 }91 }
92 92
93+ public function testWarnsAboutStaticFilesTooLargeForAFunctionResponse(): void
94+ {
95+ // Small enough as it is, but not once base64-encoded.
96+ $this->filesystem->dumpFile($this->appDir.'/public/video.bin', str_repeat("\xff", 5 * 1024 * 1024));
97+ $this->filesystem->dumpFile($this->appDir.'/public/app.css', 'body {}');
98+ $this->filesystem->dumpFile($this->appDir.'/src/large.bin', str_repeat("\xff", 5 * 1024 * 1024));
99+
100+ $this->package();
101+
102+ rewind($this->log);
103+ $log = (string) stream_get_contents($this->log);
104+ self::assertStringContainsString('WARNING: public/video.bin takes 6.7 MiB in a Function Response, over the 6 MiB Scaleway accepts', $log);
105+ self::assertStringNotContainsString('app.css', $log);
106+ self::assertStringNotContainsString('src/large.bin', $log);
107+ self::assertFileExists($this->dir.'/function.zip');
108+ }
109+
93 public function testContentHashIsComposers(): void110 public function testContentHashIsComposers(): void
94 {111 {
95 $composer = json_decode((string) file_get_contents(__DIR__.'/Fixtures/PackagedApp/composer.json'), true);112 $composer = json_decode((string) file_get_contents(__DIR__.'/Fixtures/PackagedApp/composer.json'), true);
added tests/StaticFilesTest.php +402 -0
new file mode 100644
@@ -0,0 +1,402 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests;
6+
7+use JDecool\ScalewayRuntime\StaticFiles;
8+use PHPUnit\Framework\Attributes\DataProvider;
9+use PHPUnit\Framework\Attributes\RequiresPhpExtension;
10+use PHPUnit\Framework\TestCase;
11+use Symfony\Component\Filesystem\Filesystem;
12+
13+final class StaticFilesTest extends TestCase
14+{
15+ private string $root;
16+ /** @var resource */
17+ private $errorLog;
18+
19+ protected function setUp(): void
20+ {
21+ $this->root = sys_get_temp_dir().'/static-files-'.bin2hex(random_bytes(4));
22+ $errorLog = fopen('php://memory', 'w+');
23+ self::assertNotFalse($errorLog);
24+ $this->errorLog = $errorLog;
25+ $this->write('app.css', 'body { color: red; }');
26+ $this->write('build/app.js', 'console.log("app");');
27+ $this->write('.env', 'APP_SECRET=leaked');
28+ $this->write('index.php', '<?php echo "source";');
29+ $this->write('.well-known/security.txt', 'Contact: mailto:security@example.com');
30+ }
31+
32+ protected function tearDown(): void
33+ {
34+ new Filesystem()->remove($this->root);
35+ }
36+
37+ public function testServesAFileWithItsTypeAndCacheHeaders(): void
38+ {
39+ $response = $this->serve('/app.css');
40+
41+ self::assertSame(200, $response['statusCode']);
42+ self::assertSame('body { color: red; }', $response['body']);
43+ self::assertArrayNotHasKey('isBase64Encoded', $response);
44+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
45+ self::assertSame('nosniff', $response['headers']['X-Content-Type-Options'] ?? null);
46+ self::assertSame('public, max-age=0, must-revalidate', $response['headers']['Cache-Control'] ?? null);
47+ self::assertMatchesRegularExpression('/^"[0-9a-f]{32}"$/', $response['headers']['ETag'] ?? '');
48+ self::assertArrayNotHasKey('Vary', $response['headers']);
49+ }
50+
51+ public function testServesBinaryFilesBase64Encoded(): void
52+ {
53+ $png = "\x89PNG\r\n\x1a\n\x00\xff";
54+ $this->write('logo.png', $png);
55+
56+ $response = $this->serve('/logo.png');
57+
58+ self::assertSame('image/png', $response['headers']['Content-Type'] ?? null);
59+ self::assertTrue($response['isBase64Encoded'] ?? false);
60+ self::assertSame($png, base64_decode($response['body'], true));
61+ }
62+
63+ public function testUnknownExtensionsAreOctetStreams(): void
64+ {
65+ $this->write('data.unknown-ext', 'x');
66+
67+ self::assertSame('application/octet-stream', $this->serve('/data.unknown-ext')['headers']['Content-Type'] ?? null);
68+ }
69+
70+ public function testDecodesThePath(): void
71+ {
72+ $this->write('with space.txt', 'spaced');
73+
74+ self::assertSame('spaced', $this->serve('/with%20space.txt')['body']);
75+ }
76+
77+ public function testHeadHasTheHeadersButNoBody(): void
78+ {
79+ $response = $this->serve('/app.css', 'HEAD');
80+
81+ self::assertSame(200, $response['statusCode']);
82+ self::assertSame('', $response['body']);
83+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
84+ }
85+
86+ /**
87+ * @return iterable<string, array{string, string}>
88+ */
89+ public static function invocationsForTheApplication(): iterable
90+ {
91+ yield 'POST' => ['/app.css', 'POST'];
92+ yield 'root' => ['/', 'GET'];
93+ yield 'directory' => ['/build', 'GET'];
94+ yield 'missing file' => ['/missing.css', 'GET'];
95+ yield 'PHP file' => ['/index.php', 'GET'];
96+ yield 'PHP file in upper case' => ['/INDEX.PHP', 'GET'];
97+ yield 'hidden file' => ['/.env', 'GET'];
98+ yield 'parent directory' => ['/build/../app.css', 'GET'];
99+ yield 'encoded parent directory' => ['/build/%2e%2e/app.css', 'GET'];
100+ yield 'escaping the web root' => ['/../composer.json', 'GET'];
101+ yield 'null byte' => ['/app.css%00.png', 'GET'];
102+ yield 'nested .well-known' => ['/build/.well-known/security.txt', 'GET'];
103+ }
104+
105+ #[DataProvider('invocationsForTheApplication')]
106+ public function testLeavesOtherInvocationsToTheApplication(string $path, string $method): void
107+ {
108+ new Filesystem()->dumpFile($this->root.'/composer.json', '{}');
109+
110+ self::assertNull($this->staticFiles()->serve(['path' => $path, 'httpMethod' => $method]));
111+ }
112+
113+ public function testServesWellKnownFiles(): void
114+ {
115+ self::assertSame('Contact: mailto:security@example.com', $this->serve('/.well-known/security.txt')['body']);
116+ }
117+
118+ public function testSymbolicLinksLeavingTheWebRootAreNotServed(): void
119+ {
120+ $outside = $this->root.'-outside';
121+ new Filesystem()->dumpFile($outside.'/secret.txt', 'secret');
122+ symlink($outside, $this->root.'/public/link');
123+
124+ try {
125+ self::assertNull($this->staticFiles()->serve(['path' => '/link/secret.txt']));
126+ } finally {
127+ new Filesystem()->remove($outside);
128+ }
129+ }
130+
131+ public function testMissingWebRootServesNothing(): void
132+ {
133+ self::assertNull(new StaticFiles($this->root.'/missing', null, $this->errorLog)->serve(['path' => '/app.css']));
134+ }
135+
136+ public function testMatchingIfNoneMatchIsA304WithoutBody(): void
137+ {
138+ $etag = $this->serve('/app.css')['headers']['ETag'] ?? '';
139+
140+ foreach ([$etag, 'W/'.$etag, '"other", '.$etag, '*'] as $ifNoneMatch) {
141+ $response = $this->serve('/app.css', headers: ['If-None-Match' => $ifNoneMatch]);
142+ self::assertSame(304, $response['statusCode'], $ifNoneMatch);
143+ self::assertSame('', $response['body']);
144+ self::assertSame($etag, $response['headers']['ETag'] ?? null);
145+ }
146+ self::assertSame(200, $this->serve('/app.css', headers: ['If-None-Match' => '"other"'])['statusCode']);
147+ }
148+
149+ public function testETagFollowsAFileChangingWithinTheWarmProcess(): void
150+ {
151+ $staticFiles = $this->staticFiles();
152+ $before = $staticFiles->serve(['path' => '/app.css'])['headers']['ETag'] ?? null;
153+ $this->write('app.css', 'body { color: blue; }');
154+ touch($this->root.'/public/app.css', time() + 10);
155+
156+ self::assertNotSame($before, $staticFiles->serve(['path' => '/app.css'])['headers']['ETag'] ?? null);
157+ }
158+
159+ public function testFilesADigestingManifestMapsAreImmutable(): void
160+ {
161+ // As AssetMapper writes it, then as Webpack Encore does, with versioning off for one entry.
162+ $this->write('assets/manifest.json', json_encode(['app.css' => '/assets/app-mH7q4W_.css', 'styles/x.css' => 'https://cdn.example.com/assets/styles/x-Ab1Cd2E.css']) ?: '');
163+ $this->write('assets/app-mH7q4W_.css', 'a');
164+ $this->write('assets/styles/x-Ab1Cd2E.css', 'x');
165+ $this->write('build/manifest.json', json_encode(['build/app.js' => '/build/app.js', 'build/vendor.js' => '/build/vendor.3f2a1b9c.js']) ?: '');
166+ $this->write('build/vendor.3f2a1b9c.js', 'v');
167+ $this->write('font-awesome.css', 'f');
168+
169+ $immutable = 'public, max-age=31536000, immutable';
170+ self::assertSame($immutable, $this->serve('/assets/app-mH7q4W_.css')['headers']['Cache-Control'] ?? null);
171+ self::assertSame($immutable, $this->serve('/assets/styles/x-Ab1Cd2E.css')['headers']['Cache-Control'] ?? null);
172+ self::assertSame($immutable, $this->serve('/build/vendor.3f2a1b9c.js')['headers']['Cache-Control'] ?? null);
173+ self::assertNotSame($immutable, $this->serve('/build/app.js')['headers']['Cache-Control'] ?? null);
174+ self::assertNotSame($immutable, $this->serve('/font-awesome.css')['headers']['Cache-Control'] ?? null);
175+ self::assertNotSame($immutable, $this->serve('/assets/manifest.json')['headers']['Cache-Control'] ?? null);
176+ }
177+
178+ /**
179+ * @return iterable<string, array{string, ?string}>
180+ */
181+ public static function acceptEncodings(): iterable
182+ {
183+ yield 'none' => ['', null];
184+ yield 'gzip only' => ['gzip', 'gzip'];
185+ yield 'both, brotli preferred whatever the weights' => ['gzip;q=1.0, br;q=0.1', 'br'];
186+ yield 'brotli refused' => ['gzip, br;q=0', 'gzip'];
187+ yield 'zstd preferred to gzip' => ['gzip, zstd', 'zstd'];
188+ yield 'brotli preferred to zstd' => ['zstd, br', 'br'];
189+ yield 'wildcard' => ['*', 'br'];
190+ yield 'wildcard but brotli' => ['*, br;q=0', 'zstd'];
191+ yield 'everything refused' => ['br;q=0, zstd;q=0, gzip;q=0', null];
192+ yield 'case insensitive' => ['GZIP', 'gzip'];
193+ }
194+
195+ #[DataProvider('acceptEncodings')]
196+ public function testServesThePreferredPrecompressedVariant(string $acceptEncoding, ?string $expected): void
197+ {
198+ $this->write('app.css.br', 'brotli bytes');
199+ $this->write('app.css.zst', "\x28\xb5\x2f\xfd zstd bytes");
200+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
201+
202+ $response = $this->serve('/app.css', headers: ['Accept-Encoding' => $acceptEncoding]);
203+
204+ self::assertSame($expected, $response['headers']['Content-Encoding'] ?? null);
205+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
206+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
207+ $body = true === ($response['isBase64Encoded'] ?? false) ? base64_decode($response['body'], true) : $response['body'];
208+ self::assertSame(match ($expected) {
209+ 'br' => 'brotli bytes',
210+ 'zstd' => "\x28\xb5\x2f\xfd zstd bytes",
211+ 'gzip' => "\x1f\x8b gzip bytes",
212+ default => 'body { color: red; }',
213+ }, $body);
214+ }
215+
216+ public function testEachEncodingHasItsOwnETag(): void
217+ {
218+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
219+
220+ $plain = $this->serve('/app.css')['headers']['ETag'] ?? null;
221+ $gzip = $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'])['headers']['ETag'] ?? null;
222+
223+ self::assertNotSame($plain, $gzip);
224+ self::assertSame(304, $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip', 'If-None-Match' => (string) $gzip])['statusCode']);
225+ self::assertSame(200, $this->serve('/app.css', headers: ['If-None-Match' => (string) $gzip])['statusCode']);
226+ }
227+
228+ public function testAPrecompressedVariantIsAlsoAFileOfItsOwn(): void
229+ {
230+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
231+
232+ $response = $this->serve('/app.css.gz');
233+
234+ self::assertSame("\x1f\x8b gzip bytes", base64_decode($response['body'], true));
235+ self::assertArrayNotHasKey('Content-Encoding', $response['headers']);
236+ }
237+
238+ public function testCompressesTextualFilesOnTheFly(): void
239+ {
240+ $css = str_repeat('body { color: red; }', 100);
241+ $this->write('large.css', $css);
242+
243+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
244+
245+ self::assertSame('gzip', $response['headers']['Content-Encoding'] ?? null);
246+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
247+ self::assertTrue($response['isBase64Encoded'] ?? false);
248+ self::assertSame($css, gzdecode((string) base64_decode($response['body'], true)));
249+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/large.css', compression: 'gzip')['headers']);
250+ }
251+
252+ public function testLeavesSmallAndAlreadyCompressedFilesUncompressed(): void
253+ {
254+ $this->write('large.png', str_repeat("\x89", 2048));
255+
256+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip')['headers']);
257+ $png = $this->serve('/large.png', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
258+ self::assertArrayNotHasKey('Content-Encoding', $png['headers']);
259+ self::assertArrayNotHasKey('Vary', $png['headers']);
260+ }
261+
262+ public function testPrefersAPrecompressedVariantToCompressingOnTheFly(): void
263+ {
264+ $this->write('large.css', str_repeat('a', 2048));
265+ $this->write('large.css.br', 'brotli bytes');
266+
267+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip, br'], compression: 'gzip');
268+
269+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
270+ }
271+
272+ public function testCompressedBodiesAreKeptWithinTheirCap(): void
273+ {
274+ $staticFiles = $this->staticFiles('gzip');
275+ $cache = new \ReflectionProperty(StaticFiles::class, 'compressed');
276+ // Hex digits of random bytes compress to about half their size: twelve such files fill the cache past its cap.
277+ $hex = bin2hex(random_bytes(3 * 1024 * 1024));
278+ $files = range(1, 12);
279+ foreach ($files as $name) {
280+ $this->write("$name.txt", $hex);
281+ $response = $staticFiles->serve(['path' => "/$name.txt", 'headers' => ['Accept-Encoding' => 'gzip']]);
282+ self::assertSame(200, $response['statusCode'] ?? null);
283+ }
284+
285+ $cached = $cache->getValue($staticFiles);
286+ self::assertIsArray($cached);
287+ self::assertLessThan(\count($files), \count($cached));
288+ self::assertLessThanOrEqual(StaticFiles::COMPRESSION_CACHE_SIZE, array_sum(array_map(strlen(...), array_filter($cached, \is_string(...)))));
289+ $last = $staticFiles->serve(['path' => '/12.txt', 'headers' => ['Accept-Encoding' => 'gzip']]);
290+ self::assertSame($hex, gzdecode((string) base64_decode($last['body'] ?? '', true)));
291+ }
292+
293+ public function testFilesTooLargeForAFunctionResponseAreA500AndLogged(): void
294+ {
295+ $this->write('large.bin', str_repeat("\xff", 5 * 1024 * 1024));
296+ $this->write('huge.txt', str_repeat('a', StaticFiles::MAX_RESPONSE_SIZE + 1));
297+
298+ foreach (['/large.bin', '/huge.txt'] as $path) {
299+ $response = $this->serve($path);
300+ self::assertSame(500, $response['statusCode']);
301+ self::assertSame('Internal Server Error', $response['body']);
302+ }
303+ rewind($this->errorLog);
304+ $log = (string) stream_get_contents($this->errorLog);
305+ self::assertStringContainsString('Static File "/large.bin" is 6990508 bytes once encoded', $log);
306+ self::assertStringContainsString('Static File "/huge.txt"', $log);
307+ }
308+
309+ public function testResponseSizeCountsTheBase64OfBinaryFiles(): void
310+ {
311+ $this->write('binary.bin', "\xff\xff\xff");
312+
313+ self::assertSame(20, StaticFiles::responseSize($this->root.'/public/app.css'));
314+ self::assertSame(4, StaticFiles::responseSize($this->root.'/public/binary.bin'));
315+ }
316+
317+ /**
318+ * @return iterable<string, array{mixed}>
319+ */
320+ public static function invalidCompressions(): iterable
321+ {
322+ yield 'unknown encoding' => ['deflate'];
323+ yield 'true' => [true];
324+ }
325+
326+ #[DataProvider('invalidCompressions')]
327+ public function testInvalidCompressionIsAnError(mixed $compression): void
328+ {
329+ $this->expectException(\InvalidArgumentException::class);
330+
331+ StaticFiles::create($this->root, $compression, $this->errorLog);
332+ }
333+
334+ public function testBrotliCompressionNeedsTheBrotliExtension(): void
335+ {
336+ if (\function_exists('brotli_compress')) {
337+ self::markTestSkipped('The brotli extension is loaded.');
338+ }
339+
340+ $this->expectExceptionMessage('the brotli extension is not loaded');
341+
342+ StaticFiles::create($this->root, 'br', $this->errorLog);
343+ }
344+
345+ public function testZstdCompressionNeedsTheZstdExtension(): void
346+ {
347+ if (\function_exists('zstd_compress')) {
348+ self::markTestSkipped('The zstd extension is loaded.');
349+ }
350+
351+ $this->expectExceptionMessage('the zstd extension is not loaded');
352+
353+ StaticFiles::create($this->root, 'zstd', $this->errorLog);
354+ }
355+
356+ #[RequiresPhpExtension('zstd')]
357+ public function testCompressesWithZstd(): void
358+ {
359+ $css = str_repeat('body { color: red; }', 100);
360+ $this->write('large.css', $css);
361+
362+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip, zstd'], compression: 'zstd');
363+
364+ self::assertSame('zstd', $response['headers']['Content-Encoding'] ?? null);
365+ self::assertSame($css, zstd_uncompress((string) base64_decode($response['body'], true)));
366+ }
367+
368+ #[RequiresPhpExtension('brotli')]
369+ public function testCompressesWithBrotli(): void
370+ {
371+ $this->write('large.css', str_repeat('a', 2048));
372+
373+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'br'], compression: 'br');
374+
375+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
376+ }
377+
378+ private function write(string $path, string $content): void
379+ {
380+ new Filesystem()->dumpFile($this->root.'/public/'.$path, $content);
381+ }
382+
383+ private function staticFiles(?string $compression = null): StaticFiles
384+ {
385+ return StaticFiles::create($this->root.'/public', $compression ?? false, $this->errorLog);
386+ }
387+
388+ /**
389+ * @param array<string, string> $headers
390+ *
391+ * @return array{statusCode: int, headers: array<string, string>, body: string, isBase64Encoded?: bool}
392+ */
393+ private function serve(string $path, string $method = 'GET', array $headers = [], ?string $compression = null): array
394+ {
395+ $response = $this->staticFiles($compression)->serve(['path' => $path, 'httpMethod' => $method, 'headers' => $headers]);
396+ self::assertNotNull($response, $path);
397+ // Static Files never repeat a header: single values keep the assertions short.
398+ $response['headers'] = array_map(static fn (string|array $value): string => \is_string($value) ? $value : implode(', ', $value), $response['headers'] ?? []);
399+
400+ return $response;
401+ }
402+}
new file mode 100644
@@ -0,0 +1,402 @@
1+<?php
2+
3+declare(strict_types=1);
4+
5+namespace JDecool\ScalewayRuntime\Tests;
6+
7+use JDecool\ScalewayRuntime\StaticFiles;
8+use PHPUnit\Framework\Attributes\DataProvider;
9+use PHPUnit\Framework\Attributes\RequiresPhpExtension;
10+use PHPUnit\Framework\TestCase;
11+use Symfony\Component\Filesystem\Filesystem;
12+
13+final class StaticFilesTest extends TestCase
14+{
15+ private string $root;
16+ /** @var resource */
17+ private $errorLog;
18+
19+ protected function setUp(): void
20+ {
21+ $this->root = sys_get_temp_dir().'/static-files-'.bin2hex(random_bytes(4));
22+ $errorLog = fopen('php://memory', 'w+');
23+ self::assertNotFalse($errorLog);
24+ $this->errorLog = $errorLog;
25+ $this->write('app.css', 'body { color: red; }');
26+ $this->write('build/app.js', 'console.log("app");');
27+ $this->write('.env', 'APP_SECRET=leaked');
28+ $this->write('index.php', '<?php echo "source";');
29+ $this->write('.well-known/security.txt', 'Contact: mailto:security@example.com');
30+ }
31+
32+ protected function tearDown(): void
33+ {
34+ new Filesystem()->remove($this->root);
35+ }
36+
37+ public function testServesAFileWithItsTypeAndCacheHeaders(): void
38+ {
39+ $response = $this->serve('/app.css');
40+
41+ self::assertSame(200, $response['statusCode']);
42+ self::assertSame('body { color: red; }', $response['body']);
43+ self::assertArrayNotHasKey('isBase64Encoded', $response);
44+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
45+ self::assertSame('nosniff', $response['headers']['X-Content-Type-Options'] ?? null);
46+ self::assertSame('public, max-age=0, must-revalidate', $response['headers']['Cache-Control'] ?? null);
47+ self::assertMatchesRegularExpression('/^"[0-9a-f]{32}"$/', $response['headers']['ETag'] ?? '');
48+ self::assertArrayNotHasKey('Vary', $response['headers']);
49+ }
50+
51+ public function testServesBinaryFilesBase64Encoded(): void
52+ {
53+ $png = "\x89PNG\r\n\x1a\n\x00\xff";
54+ $this->write('logo.png', $png);
55+
56+ $response = $this->serve('/logo.png');
57+
58+ self::assertSame('image/png', $response['headers']['Content-Type'] ?? null);
59+ self::assertTrue($response['isBase64Encoded'] ?? false);
60+ self::assertSame($png, base64_decode($response['body'], true));
61+ }
62+
63+ public function testUnknownExtensionsAreOctetStreams(): void
64+ {
65+ $this->write('data.unknown-ext', 'x');
66+
67+ self::assertSame('application/octet-stream', $this->serve('/data.unknown-ext')['headers']['Content-Type'] ?? null);
68+ }
69+
70+ public function testDecodesThePath(): void
71+ {
72+ $this->write('with space.txt', 'spaced');
73+
74+ self::assertSame('spaced', $this->serve('/with%20space.txt')['body']);
75+ }
76+
77+ public function testHeadHasTheHeadersButNoBody(): void
78+ {
79+ $response = $this->serve('/app.css', 'HEAD');
80+
81+ self::assertSame(200, $response['statusCode']);
82+ self::assertSame('', $response['body']);
83+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
84+ }
85+
86+ /**
87+ * @return iterable<string, array{string, string}>
88+ */
89+ public static function invocationsForTheApplication(): iterable
90+ {
91+ yield 'POST' => ['/app.css', 'POST'];
92+ yield 'root' => ['/', 'GET'];
93+ yield 'directory' => ['/build', 'GET'];
94+ yield 'missing file' => ['/missing.css', 'GET'];
95+ yield 'PHP file' => ['/index.php', 'GET'];
96+ yield 'PHP file in upper case' => ['/INDEX.PHP', 'GET'];
97+ yield 'hidden file' => ['/.env', 'GET'];
98+ yield 'parent directory' => ['/build/../app.css', 'GET'];
99+ yield 'encoded parent directory' => ['/build/%2e%2e/app.css', 'GET'];
100+ yield 'escaping the web root' => ['/../composer.json', 'GET'];
101+ yield 'null byte' => ['/app.css%00.png', 'GET'];
102+ yield 'nested .well-known' => ['/build/.well-known/security.txt', 'GET'];
103+ }
104+
105+ #[DataProvider('invocationsForTheApplication')]
106+ public function testLeavesOtherInvocationsToTheApplication(string $path, string $method): void
107+ {
108+ new Filesystem()->dumpFile($this->root.'/composer.json', '{}');
109+
110+ self::assertNull($this->staticFiles()->serve(['path' => $path, 'httpMethod' => $method]));
111+ }
112+
113+ public function testServesWellKnownFiles(): void
114+ {
115+ self::assertSame('Contact: mailto:security@example.com', $this->serve('/.well-known/security.txt')['body']);
116+ }
117+
118+ public function testSymbolicLinksLeavingTheWebRootAreNotServed(): void
119+ {
120+ $outside = $this->root.'-outside';
121+ new Filesystem()->dumpFile($outside.'/secret.txt', 'secret');
122+ symlink($outside, $this->root.'/public/link');
123+
124+ try {
125+ self::assertNull($this->staticFiles()->serve(['path' => '/link/secret.txt']));
126+ } finally {
127+ new Filesystem()->remove($outside);
128+ }
129+ }
130+
131+ public function testMissingWebRootServesNothing(): void
132+ {
133+ self::assertNull(new StaticFiles($this->root.'/missing', null, $this->errorLog)->serve(['path' => '/app.css']));
134+ }
135+
136+ public function testMatchingIfNoneMatchIsA304WithoutBody(): void
137+ {
138+ $etag = $this->serve('/app.css')['headers']['ETag'] ?? '';
139+
140+ foreach ([$etag, 'W/'.$etag, '"other", '.$etag, '*'] as $ifNoneMatch) {
141+ $response = $this->serve('/app.css', headers: ['If-None-Match' => $ifNoneMatch]);
142+ self::assertSame(304, $response['statusCode'], $ifNoneMatch);
143+ self::assertSame('', $response['body']);
144+ self::assertSame($etag, $response['headers']['ETag'] ?? null);
145+ }
146+ self::assertSame(200, $this->serve('/app.css', headers: ['If-None-Match' => '"other"'])['statusCode']);
147+ }
148+
149+ public function testETagFollowsAFileChangingWithinTheWarmProcess(): void
150+ {
151+ $staticFiles = $this->staticFiles();
152+ $before = $staticFiles->serve(['path' => '/app.css'])['headers']['ETag'] ?? null;
153+ $this->write('app.css', 'body { color: blue; }');
154+ touch($this->root.'/public/app.css', time() + 10);
155+
156+ self::assertNotSame($before, $staticFiles->serve(['path' => '/app.css'])['headers']['ETag'] ?? null);
157+ }
158+
159+ public function testFilesADigestingManifestMapsAreImmutable(): void
160+ {
161+ // As AssetMapper writes it, then as Webpack Encore does, with versioning off for one entry.
162+ $this->write('assets/manifest.json', json_encode(['app.css' => '/assets/app-mH7q4W_.css', 'styles/x.css' => 'https://cdn.example.com/assets/styles/x-Ab1Cd2E.css']) ?: '');
163+ $this->write('assets/app-mH7q4W_.css', 'a');
164+ $this->write('assets/styles/x-Ab1Cd2E.css', 'x');
165+ $this->write('build/manifest.json', json_encode(['build/app.js' => '/build/app.js', 'build/vendor.js' => '/build/vendor.3f2a1b9c.js']) ?: '');
166+ $this->write('build/vendor.3f2a1b9c.js', 'v');
167+ $this->write('font-awesome.css', 'f');
168+
169+ $immutable = 'public, max-age=31536000, immutable';
170+ self::assertSame($immutable, $this->serve('/assets/app-mH7q4W_.css')['headers']['Cache-Control'] ?? null);
171+ self::assertSame($immutable, $this->serve('/assets/styles/x-Ab1Cd2E.css')['headers']['Cache-Control'] ?? null);
172+ self::assertSame($immutable, $this->serve('/build/vendor.3f2a1b9c.js')['headers']['Cache-Control'] ?? null);
173+ self::assertNotSame($immutable, $this->serve('/build/app.js')['headers']['Cache-Control'] ?? null);
174+ self::assertNotSame($immutable, $this->serve('/font-awesome.css')['headers']['Cache-Control'] ?? null);
175+ self::assertNotSame($immutable, $this->serve('/assets/manifest.json')['headers']['Cache-Control'] ?? null);
176+ }
177+
178+ /**
179+ * @return iterable<string, array{string, ?string}>
180+ */
181+ public static function acceptEncodings(): iterable
182+ {
183+ yield 'none' => ['', null];
184+ yield 'gzip only' => ['gzip', 'gzip'];
185+ yield 'both, brotli preferred whatever the weights' => ['gzip;q=1.0, br;q=0.1', 'br'];
186+ yield 'brotli refused' => ['gzip, br;q=0', 'gzip'];
187+ yield 'zstd preferred to gzip' => ['gzip, zstd', 'zstd'];
188+ yield 'brotli preferred to zstd' => ['zstd, br', 'br'];
189+ yield 'wildcard' => ['*', 'br'];
190+ yield 'wildcard but brotli' => ['*, br;q=0', 'zstd'];
191+ yield 'everything refused' => ['br;q=0, zstd;q=0, gzip;q=0', null];
192+ yield 'case insensitive' => ['GZIP', 'gzip'];
193+ }
194+
195+ #[DataProvider('acceptEncodings')]
196+ public function testServesThePreferredPrecompressedVariant(string $acceptEncoding, ?string $expected): void
197+ {
198+ $this->write('app.css.br', 'brotli bytes');
199+ $this->write('app.css.zst', "\x28\xb5\x2f\xfd zstd bytes");
200+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
201+
202+ $response = $this->serve('/app.css', headers: ['Accept-Encoding' => $acceptEncoding]);
203+
204+ self::assertSame($expected, $response['headers']['Content-Encoding'] ?? null);
205+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
206+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
207+ $body = true === ($response['isBase64Encoded'] ?? false) ? base64_decode($response['body'], true) : $response['body'];
208+ self::assertSame(match ($expected) {
209+ 'br' => 'brotli bytes',
210+ 'zstd' => "\x28\xb5\x2f\xfd zstd bytes",
211+ 'gzip' => "\x1f\x8b gzip bytes",
212+ default => 'body { color: red; }',
213+ }, $body);
214+ }
215+
216+ public function testEachEncodingHasItsOwnETag(): void
217+ {
218+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
219+
220+ $plain = $this->serve('/app.css')['headers']['ETag'] ?? null;
221+ $gzip = $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'])['headers']['ETag'] ?? null;
222+
223+ self::assertNotSame($plain, $gzip);
224+ self::assertSame(304, $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip', 'If-None-Match' => (string) $gzip])['statusCode']);
225+ self::assertSame(200, $this->serve('/app.css', headers: ['If-None-Match' => (string) $gzip])['statusCode']);
226+ }
227+
228+ public function testAPrecompressedVariantIsAlsoAFileOfItsOwn(): void
229+ {
230+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
231+
232+ $response = $this->serve('/app.css.gz');
233+
234+ self::assertSame("\x1f\x8b gzip bytes", base64_decode($response['body'], true));
235+ self::assertArrayNotHasKey('Content-Encoding', $response['headers']);
236+ }
237+
238+ public function testCompressesTextualFilesOnTheFly(): void
239+ {
240+ $css = str_repeat('body { color: red; }', 100);
241+ $this->write('large.css', $css);
242+
243+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
244+
245+ self::assertSame('gzip', $response['headers']['Content-Encoding'] ?? null);
246+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
247+ self::assertTrue($response['isBase64Encoded'] ?? false);
248+ self::assertSame($css, gzdecode((string) base64_decode($response['body'], true)));
249+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/large.css', compression: 'gzip')['headers']);
250+ }
251+
252+ public function testLeavesSmallAndAlreadyCompressedFilesUncompressed(): void
253+ {
254+ $this->write('large.png', str_repeat("\x89", 2048));
255+
256+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip')['headers']);
257+ $png = $this->serve('/large.png', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
258+ self::assertArrayNotHasKey('Content-Encoding', $png['headers']);
259+ self::assertArrayNotHasKey('Vary', $png['headers']);
260+ }
261+
262+ public function testPrefersAPrecompressedVariantToCompressingOnTheFly(): void
263+ {
264+ $this->write('large.css', str_repeat('a', 2048));
265+ $this->write('large.css.br', 'brotli bytes');
266+
267+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip, br'], compression: 'gzip');
268+
269+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
270+ }
271+
272+ public function testCompressedBodiesAreKeptWithinTheirCap(): void
273+ {
274+ $staticFiles = $this->staticFiles('gzip');
275+ $cache = new \ReflectionProperty(StaticFiles::class, 'compressed');
276+ // Hex digits of random bytes compress to about half their size: twelve such files fill the cache past its cap.
277+ $hex = bin2hex(random_bytes(3 * 1024 * 1024));
278+ $files = range(1, 12);
279+ foreach ($files as $name) {
280+ $this->write("$name.txt", $hex);
281+ $response = $staticFiles->serve(['path' => "/$name.txt", 'headers' => ['Accept-Encoding' => 'gzip']]);
282+ self::assertSame(200, $response['statusCode'] ?? null);
283+ }
284+
285+ $cached = $cache->getValue($staticFiles);
286+ self::assertIsArray($cached);
287+ self::assertLessThan(\count($files), \count($cached));
288+ self::assertLessThanOrEqual(StaticFiles::COMPRESSION_CACHE_SIZE, array_sum(array_map(strlen(...), array_filter($cached, \is_string(...)))));
289+ $last = $staticFiles->serve(['path' => '/12.txt', 'headers' => ['Accept-Encoding' => 'gzip']]);
290+ self::assertSame($hex, gzdecode((string) base64_decode($last['body'] ?? '', true)));
291+ }
292+
293+ public function testFilesTooLargeForAFunctionResponseAreA500AndLogged(): void
294+ {
295+ $this->write('large.bin', str_repeat("\xff", 5 * 1024 * 1024));
296+ $this->write('huge.txt', str_repeat('a', StaticFiles::MAX_RESPONSE_SIZE + 1));
297+
298+ foreach (['/large.bin', '/huge.txt'] as $path) {
299+ $response = $this->serve($path);
300+ self::assertSame(500, $response['statusCode']);
301+ self::assertSame('Internal Server Error', $response['body']);
302+ }
303+ rewind($this->errorLog);
304+ $log = (string) stream_get_contents($this->errorLog);
305+ self::assertStringContainsString('Static File "/large.bin" is 6990508 bytes once encoded', $log);
306+ self::assertStringContainsString('Static File "/huge.txt"', $log);
307+ }
308+
309+ public function testResponseSizeCountsTheBase64OfBinaryFiles(): void
310+ {
311+ $this->write('binary.bin', "\xff\xff\xff");
312+
313+ self::assertSame(20, StaticFiles::responseSize($this->root.'/public/app.css'));
314+ self::assertSame(4, StaticFiles::responseSize($this->root.'/public/binary.bin'));
315+ }
316+
317+ /**
318+ * @return iterable<string, array{mixed}>
319+ */
320+ public static function invalidCompressions(): iterable
321+ {
322+ yield 'unknown encoding' => ['deflate'];
323+ yield 'true' => [true];
324+ }
325+
326+ #[DataProvider('invalidCompressions')]
327+ public function testInvalidCompressionIsAnError(mixed $compression): void
328+ {
329+ $this->expectException(\InvalidArgumentException::class);
330+
331+ StaticFiles::create($this->root, $compression, $this->errorLog);
332+ }
333+
334+ public function testBrotliCompressionNeedsTheBrotliExtension(): void
335+ {
336+ if (\function_exists('brotli_compress')) {
337+ self::markTestSkipped('The brotli extension is loaded.');
338+ }
339+
340+ $this->expectExceptionMessage('the brotli extension is not loaded');
341+
342+ StaticFiles::create($this->root, 'br', $this->errorLog);
343+ }
344+
345+ public function testZstdCompressionNeedsTheZstdExtension(): void
346+ {
347+ if (\function_exists('zstd_compress')) {
348+ self::markTestSkipped('The zstd extension is loaded.');
349+ }
350+
351+ $this->expectExceptionMessage('the zstd extension is not loaded');
352+
353+ StaticFiles::create($this->root, 'zstd', $this->errorLog);
354+ }
355+
356+ #[RequiresPhpExtension('zstd')]
357+ public function testCompressesWithZstd(): void
358+ {
359+ $css = str_repeat('body { color: red; }', 100);
360+ $this->write('large.css', $css);
361+
362+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip, zstd'], compression: 'zstd');
363+
364+ self::assertSame('zstd', $response['headers']['Content-Encoding'] ?? null);
365+ self::assertSame($css, zstd_uncompress((string) base64_decode($response['body'], true)));
366+ }
367+
368+ #[RequiresPhpExtension('brotli')]
369+ public function testCompressesWithBrotli(): void
370+ {
371+ $this->write('large.css', str_repeat('a', 2048));
372+
373+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'br'], compression: 'br');
374+
375+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
376+ }
377+
378+ private function write(string $path, string $content): void
379+ {
380+ new Filesystem()->dumpFile($this->root.'/public/'.$path, $content);
381+ }
382+
383+ private function staticFiles(?string $compression = null): StaticFiles
384+ {
385+ return StaticFiles::create($this->root.'/public', $compression ?? false, $this->errorLog);
386+ }
387+
388+ /**
389+ * @param array<string, string> $headers
390+ *
391+ * @return array{statusCode: int, headers: array<string, string>, body: string, isBase64Encoded?: bool}
392+ */
393+ private function serve(string $path, string $method = 'GET', array $headers = [], ?string $compression = null): array
394+ {
395+ $response = $this->staticFiles($compression)->serve(['path' => $path, 'httpMethod' => $method, 'headers' => $headers]);
396+ self::assertNotNull($response, $path);
397+ // Static Files never repeat a header: single values keep the assertions short.
398+ $response['headers'] = array_map(static fn (string|array $value): string => \is_string($value) ? $value : implode(', ', $value), $response['headers'] ?? []);
399+
400+ return $response;
401+ }
402+}