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

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

Download ZIP

feat: serve Static Files before building the ApplicationUnverified

Jérémy DECOOL committed 2026-11-22T11:45:23+01:00 Browse files
72798f1 parent: b74f473
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": {
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/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" or "br", 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" or "br", 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 +350 -0
new file mode 100644
@@ -0,0 +1,350 @@
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', 'gzip' => '.gz'];
22+
23+ /** The values of the "static_compression" runtime option, but false. */
24+ public const array COMPRESSIONS = ['gzip', 'br'];
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'|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 (!\in_array($compression, self::COMPRESSIONS, true)) {
73+ throw new \InvalidArgumentException(\sprintf('The "static_compression" runtime option must be false, "gzip" or "br", "%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+ if ('br' === $compression && !\function_exists('brotli_compress')) {
77+ throw new \LogicException('The "static_compression" runtime option is "br", but the brotli extension is not loaded.');
78+ }
79+ if ('gzip' === $compression && !\function_exists('gzencode')) {
80+ throw new \LogicException('The "static_compression" runtime option is "gzip", but the zlib extension is not loaded.');
81+ }
82+
83+ return new self($webRoot, $compression, $errorLog);
84+ }
85+
86+ /**
87+ * @param array<mixed> $event
88+ *
89+ * @return FunctionResponse|null null when the Invocation is not for a Static File
90+ */
91+ public function serve(array $event): ?array
92+ {
93+ $method = strtoupper(\is_string($event['httpMethod'] ?? null) ? $event['httpMethod'] : (\is_string($event['method'] ?? null) ? $event['method'] : 'GET'));
94+ $path = \is_string($event['path'] ?? null) ? rawurldecode($event['path']) : '';
95+ if (!\in_array($method, ['GET', 'HEAD'], true) || null === $file = $this->resolve($path)) {
96+ return null;
97+ }
98+
99+ $headers = array_change_key_case(\is_array($event['headers'] ?? null) ? $event['headers'] : []);
100+ $type = MimeTypes::getDefault()->getMimeTypes(pathinfo($file, \PATHINFO_EXTENSION))[0] ?? 'application/octet-stream';
101+ $compressible = null !== $this->compression && $this->isCompressible($type);
102+ [$encoding, $bodyFile] = $this->negotiate($file, \is_string($headers['accept-encoding'] ?? null) ? $headers['accept-encoding'] : '', $compressible);
103+
104+ $etag = $this->etag($bodyFile ?? $file, $encoding);
105+ $responseHeaders = [
106+ 'Content-Type' => $type,
107+ 'Cache-Control' => $this->isDigested($path, $file) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
108+ 'ETag' => $etag,
109+ 'X-Content-Type-Options' => 'nosniff',
110+ ];
111+ if ($compressible || $this->hasVariant($file)) {
112+ $responseHeaders['Vary'] = 'Accept-Encoding';
113+ }
114+ if (null !== $encoding) {
115+ $responseHeaders['Content-Encoding'] = $encoding;
116+ }
117+
118+ if (self::matches(\is_string($headers['if-none-match'] ?? null) ? $headers['if-none-match'] : '', $etag)) {
119+ unset($responseHeaders['Content-Type']);
120+
121+ return ['statusCode' => 304, 'headers' => $responseHeaders, 'body' => ''];
122+ }
123+ if ('HEAD' === $method) {
124+ return ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => ''];
125+ }
126+
127+ $compressing = null === $bodyFile && null !== $encoding;
128+ // Checked before reading, so a large file cannot exhaust the memory of the Warm Process; a file compressed
129+ // on the fly may shrink below the limit, so it gets more room.
130+ $size = (int) filesize($bodyFile ?? $file);
131+ if ($size > ($compressing ? 4 : 1) * self::MAX_RESPONSE_SIZE) {
132+ return $this->tooLarge($path, $size);
133+ }
134+
135+ $body = $compressing ? $this->compress($file, $encoding) : (string) file_get_contents($bodyFile ?? $file);
136+ $base64 = null !== $encoding || 1 !== preg_match('//u', $body);
137+ $size = $base64 ? 4 * (int) ceil(\strlen($body) / 3) : \strlen($body);
138+ if ($size > self::MAX_RESPONSE_SIZE) {
139+ return $this->tooLarge($path, $size);
140+ }
141+
142+ return $base64
143+ ? ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => base64_encode($body), 'isBase64Encoded' => true]
144+ : ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => $body];
145+ }
146+
147+ /**
148+ * @return FunctionResponse
149+ */
150+ private function tooLarge(string $path, int $size): array
151+ {
152+ // The platform would answer an opaque error: the log says which file and why.
153+ 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);
154+
155+ return ['statusCode' => 500, 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'], 'body' => 'Internal Server Error'];
156+ }
157+
158+ /**
159+ * The size a file takes in a Function Response, base64 included, for scaleway-package to warn about.
160+ */
161+ public static function responseSize(string $file): int
162+ {
163+ $size = (int) filesize($file);
164+ if ($size > self::MAX_RESPONSE_SIZE) {
165+ return $size;
166+ }
167+
168+ return 1 === preg_match('//u', (string) file_get_contents($file)) ? $size : 4 * (int) ceil($size / 3);
169+ }
170+
171+ private function resolve(string $path): ?string
172+ {
173+ if (str_contains($path, "\0") || str_ends_with(strtolower($path), '.php')) {
174+ return null;
175+ }
176+ // Dot segments cover "..", and hidden files such as .htaccess or .env that a web server would not serve either;
177+ // /.well-known/ is the one public prefix starting with a dot (RFC 8615).
178+ foreach (explode('/', ltrim($path, '/')) as $i => $segment) {
179+ if (str_starts_with($segment, '.') && (0 !== $i || '.well-known' !== $segment)) {
180+ return null;
181+ }
182+ }
183+
184+ $this->root ??= realpath($this->webRoot) ?: '';
185+ if ('' === $this->root) {
186+ return null;
187+ }
188+ // A symbolic link leading out of the web root is not served either.
189+ $file = realpath($this->root.'/'.ltrim($path, '/'));
190+
191+ return false !== $file && str_starts_with($file, $this->root.\DIRECTORY_SEPARATOR) && is_file($file) ? $file : null;
192+ }
193+
194+ /**
195+ * Picks the encoding the client accepts, a precompressed variant first.
196+ *
197+ * @return array{?string, ?string} the encoding, and the precompressed file holding the body if any
198+ */
199+ private function negotiate(string $file, string $acceptEncoding, bool $compressible): array
200+ {
201+ $accepted = self::acceptedEncodings($acceptEncoding);
202+ foreach (self::PRECOMPRESSED as $encoding => $extension) {
203+ if ($accepted($encoding) && is_file($file.$extension)) {
204+ return [$encoding, $file.$extension];
205+ }
206+ }
207+ if ($compressible && \is_string($this->compression) && $accepted($this->compression) && filesize($file) >= self::COMPRESSION_MIN_SIZE) {
208+ return [$this->compression, null];
209+ }
210+
211+ return [null, null];
212+ }
213+
214+ /**
215+ * Only q=0 refuses an encoding: the order of preference is the runtime's, not the client's weights.
216+ *
217+ * @return \Closure(string): bool
218+ */
219+ private static function acceptedEncodings(string $header): \Closure
220+ {
221+ $weights = [];
222+ foreach (explode(',', $header) as $item) {
223+ $parts = explode(';', $item);
224+ $name = strtolower(trim($parts[0]));
225+ if ('' === $name) {
226+ continue;
227+ }
228+ $weights[$name] = 1.0;
229+ foreach (\array_slice($parts, 1) as $parameter) {
230+ if (1 === preg_match('/^\s*q\s*=\s*([0-9.]+)\s*$/i', $parameter, $match)) {
231+ $weights[$name] = (float) $match[1];
232+ }
233+ }
234+ }
235+
236+ return static fn (string $encoding): bool => ($weights[$encoding] ?? $weights['*'] ?? 0.0) > 0.0;
237+ }
238+
239+ private function hasVariant(string $file): bool
240+ {
241+ return array_any(self::PRECOMPRESSED, static fn (string $extension): bool => is_file($file.$extension));
242+ }
243+
244+ private function isCompressible(string $type): bool
245+ {
246+ return str_starts_with($type, 'text/') || \in_array($type, self::COMPRESSIBLE_TYPES, true)
247+ || str_ends_with($type, '+json') || str_ends_with($type, '+xml');
248+ }
249+
250+ private function compress(string $file, string $encoding): string
251+ {
252+ $key = $this->key($file).':'.$encoding;
253+ if (isset($this->compressed[$key])) {
254+ return $this->compressed[$key];
255+ }
256+
257+ $content = (string) file_get_contents($file);
258+ $body = (string) ('br' === $encoding ? brotli_compress($content) : gzencode($content));
259+ // Past the cap, files are compressed again for each Invocation rather than growing the Warm Process.
260+ if ($this->compressedSize + \strlen($body) <= self::COMPRESSION_CACHE_SIZE) {
261+ $this->compressed[$key] = $body;
262+ $this->compressedSize += \strlen($body);
263+ }
264+
265+ return $body;
266+ }
267+
268+ /**
269+ * A strong ETag of the bytes sent, each encoding having its own as its bytes differ.
270+ */
271+ private function etag(string $file, ?string $encoding): string
272+ {
273+ $key = $this->key($file);
274+ $this->etags[$key] ??= hash_file('xxh128', $file) ?: '';
275+
276+ return '"'.$this->etags[$key].(null === $encoding ? '' : '-'.$encoding).'"';
277+ }
278+
279+ /**
280+ * Files written at runtime, such as uploads, may change within a Warm Process: their key changes with them.
281+ */
282+ private function key(string $file): string
283+ {
284+ clearstatcache(true, $file);
285+
286+ return $file.':'.filemtime($file).':'.filesize($file);
287+ }
288+
289+ /**
290+ * Weak comparison, as RFC 9110 asks for If-None-Match.
291+ */
292+ private static function matches(string $ifNoneMatch, string $etag): bool
293+ {
294+ if ('*' === trim($ifNoneMatch)) {
295+ return true;
296+ }
297+ foreach (explode(',', $ifNoneMatch) as $candidate) {
298+ $candidate = trim($candidate);
299+ if ((str_starts_with($candidate, 'W/') ? substr($candidate, 2) : $candidate) === $etag) {
300+ return true;
301+ }
302+ }
303+
304+ return false;
305+ }
306+
307+ /**
308+ * A file is cached for good only when a manifest.json above it, as written by AssetMapper or Webpack Encore, maps a
309+ * logical path to it under another name: its name then changes with its content. Guessing a digest from the name
310+ * alone would also match plain names such as "font-awesome.css".
311+ */
312+ private function isDigested(string $path, string $file): bool
313+ {
314+ $public = '/'.ltrim($path, '/');
315+ for ($dir = \dirname($file); str_starts_with($dir.\DIRECTORY_SEPARATOR, (string) $this->root.\DIRECTORY_SEPARATOR); $dir = \dirname($dir)) {
316+ if (isset($this->manifest($dir.'/manifest.json')[$public])) {
317+ return true;
318+ }
319+ if ($dir === $this->root) {
320+ break;
321+ }
322+ }
323+
324+ return false;
325+ }
326+
327+ /**
328+ * @return array<string, true>
329+ */
330+ private function manifest(string $file): array
331+ {
332+ if (!isset($this->manifests[$file])) {
333+ $digested = [];
334+ $entries = is_file($file) ? json_decode((string) file_get_contents($file), true) : null;
335+ foreach (\is_array($entries) ? $entries : [] as $logical => $public) {
336+ if (!\is_string($public)) {
337+ continue;
338+ }
339+ // Assets served from a CDN or with a base path are listed as URLs: only their path is ours.
340+ $publicPath = parse_url($public, \PHP_URL_PATH);
341+ if (\is_string($publicPath) && basename($publicPath) !== basename((string) $logical)) {
342+ $digested['/'.ltrim($publicPath, '/')] = true;
343+ }
344+ }
345+ $this->manifests[$file] = $digested;
346+ }
347+
348+ return $this->manifests[$file];
349+ }
350+}
new file mode 100644
@@ -0,0 +1,350 @@
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', 'gzip' => '.gz'];
22+
23+ /** The values of the "static_compression" runtime option, but false. */
24+ public const array COMPRESSIONS = ['gzip', 'br'];
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'|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 (!\in_array($compression, self::COMPRESSIONS, true)) {
73+ throw new \InvalidArgumentException(\sprintf('The "static_compression" runtime option must be false, "gzip" or "br", "%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+ if ('br' === $compression && !\function_exists('brotli_compress')) {
77+ throw new \LogicException('The "static_compression" runtime option is "br", but the brotli extension is not loaded.');
78+ }
79+ if ('gzip' === $compression && !\function_exists('gzencode')) {
80+ throw new \LogicException('The "static_compression" runtime option is "gzip", but the zlib extension is not loaded.');
81+ }
82+
83+ return new self($webRoot, $compression, $errorLog);
84+ }
85+
86+ /**
87+ * @param array<mixed> $event
88+ *
89+ * @return FunctionResponse|null null when the Invocation is not for a Static File
90+ */
91+ public function serve(array $event): ?array
92+ {
93+ $method = strtoupper(\is_string($event['httpMethod'] ?? null) ? $event['httpMethod'] : (\is_string($event['method'] ?? null) ? $event['method'] : 'GET'));
94+ $path = \is_string($event['path'] ?? null) ? rawurldecode($event['path']) : '';
95+ if (!\in_array($method, ['GET', 'HEAD'], true) || null === $file = $this->resolve($path)) {
96+ return null;
97+ }
98+
99+ $headers = array_change_key_case(\is_array($event['headers'] ?? null) ? $event['headers'] : []);
100+ $type = MimeTypes::getDefault()->getMimeTypes(pathinfo($file, \PATHINFO_EXTENSION))[0] ?? 'application/octet-stream';
101+ $compressible = null !== $this->compression && $this->isCompressible($type);
102+ [$encoding, $bodyFile] = $this->negotiate($file, \is_string($headers['accept-encoding'] ?? null) ? $headers['accept-encoding'] : '', $compressible);
103+
104+ $etag = $this->etag($bodyFile ?? $file, $encoding);
105+ $responseHeaders = [
106+ 'Content-Type' => $type,
107+ 'Cache-Control' => $this->isDigested($path, $file) ? 'public, max-age=31536000, immutable' : 'public, max-age=0, must-revalidate',
108+ 'ETag' => $etag,
109+ 'X-Content-Type-Options' => 'nosniff',
110+ ];
111+ if ($compressible || $this->hasVariant($file)) {
112+ $responseHeaders['Vary'] = 'Accept-Encoding';
113+ }
114+ if (null !== $encoding) {
115+ $responseHeaders['Content-Encoding'] = $encoding;
116+ }
117+
118+ if (self::matches(\is_string($headers['if-none-match'] ?? null) ? $headers['if-none-match'] : '', $etag)) {
119+ unset($responseHeaders['Content-Type']);
120+
121+ return ['statusCode' => 304, 'headers' => $responseHeaders, 'body' => ''];
122+ }
123+ if ('HEAD' === $method) {
124+ return ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => ''];
125+ }
126+
127+ $compressing = null === $bodyFile && null !== $encoding;
128+ // Checked before reading, so a large file cannot exhaust the memory of the Warm Process; a file compressed
129+ // on the fly may shrink below the limit, so it gets more room.
130+ $size = (int) filesize($bodyFile ?? $file);
131+ if ($size > ($compressing ? 4 : 1) * self::MAX_RESPONSE_SIZE) {
132+ return $this->tooLarge($path, $size);
133+ }
134+
135+ $body = $compressing ? $this->compress($file, $encoding) : (string) file_get_contents($bodyFile ?? $file);
136+ $base64 = null !== $encoding || 1 !== preg_match('//u', $body);
137+ $size = $base64 ? 4 * (int) ceil(\strlen($body) / 3) : \strlen($body);
138+ if ($size > self::MAX_RESPONSE_SIZE) {
139+ return $this->tooLarge($path, $size);
140+ }
141+
142+ return $base64
143+ ? ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => base64_encode($body), 'isBase64Encoded' => true]
144+ : ['statusCode' => 200, 'headers' => $responseHeaders, 'body' => $body];
145+ }
146+
147+ /**
148+ * @return FunctionResponse
149+ */
150+ private function tooLarge(string $path, int $size): array
151+ {
152+ // The platform would answer an opaque error: the log says which file and why.
153+ 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);
154+
155+ return ['statusCode' => 500, 'headers' => ['Content-Type' => 'text/plain; charset=UTF-8'], 'body' => 'Internal Server Error'];
156+ }
157+
158+ /**
159+ * The size a file takes in a Function Response, base64 included, for scaleway-package to warn about.
160+ */
161+ public static function responseSize(string $file): int
162+ {
163+ $size = (int) filesize($file);
164+ if ($size > self::MAX_RESPONSE_SIZE) {
165+ return $size;
166+ }
167+
168+ return 1 === preg_match('//u', (string) file_get_contents($file)) ? $size : 4 * (int) ceil($size / 3);
169+ }
170+
171+ private function resolve(string $path): ?string
172+ {
173+ if (str_contains($path, "\0") || str_ends_with(strtolower($path), '.php')) {
174+ return null;
175+ }
176+ // Dot segments cover "..", and hidden files such as .htaccess or .env that a web server would not serve either;
177+ // /.well-known/ is the one public prefix starting with a dot (RFC 8615).
178+ foreach (explode('/', ltrim($path, '/')) as $i => $segment) {
179+ if (str_starts_with($segment, '.') && (0 !== $i || '.well-known' !== $segment)) {
180+ return null;
181+ }
182+ }
183+
184+ $this->root ??= realpath($this->webRoot) ?: '';
185+ if ('' === $this->root) {
186+ return null;
187+ }
188+ // A symbolic link leading out of the web root is not served either.
189+ $file = realpath($this->root.'/'.ltrim($path, '/'));
190+
191+ return false !== $file && str_starts_with($file, $this->root.\DIRECTORY_SEPARATOR) && is_file($file) ? $file : null;
192+ }
193+
194+ /**
195+ * Picks the encoding the client accepts, a precompressed variant first.
196+ *
197+ * @return array{?string, ?string} the encoding, and the precompressed file holding the body if any
198+ */
199+ private function negotiate(string $file, string $acceptEncoding, bool $compressible): array
200+ {
201+ $accepted = self::acceptedEncodings($acceptEncoding);
202+ foreach (self::PRECOMPRESSED as $encoding => $extension) {
203+ if ($accepted($encoding) && is_file($file.$extension)) {
204+ return [$encoding, $file.$extension];
205+ }
206+ }
207+ if ($compressible && \is_string($this->compression) && $accepted($this->compression) && filesize($file) >= self::COMPRESSION_MIN_SIZE) {
208+ return [$this->compression, null];
209+ }
210+
211+ return [null, null];
212+ }
213+
214+ /**
215+ * Only q=0 refuses an encoding: the order of preference is the runtime's, not the client's weights.
216+ *
217+ * @return \Closure(string): bool
218+ */
219+ private static function acceptedEncodings(string $header): \Closure
220+ {
221+ $weights = [];
222+ foreach (explode(',', $header) as $item) {
223+ $parts = explode(';', $item);
224+ $name = strtolower(trim($parts[0]));
225+ if ('' === $name) {
226+ continue;
227+ }
228+ $weights[$name] = 1.0;
229+ foreach (\array_slice($parts, 1) as $parameter) {
230+ if (1 === preg_match('/^\s*q\s*=\s*([0-9.]+)\s*$/i', $parameter, $match)) {
231+ $weights[$name] = (float) $match[1];
232+ }
233+ }
234+ }
235+
236+ return static fn (string $encoding): bool => ($weights[$encoding] ?? $weights['*'] ?? 0.0) > 0.0;
237+ }
238+
239+ private function hasVariant(string $file): bool
240+ {
241+ return array_any(self::PRECOMPRESSED, static fn (string $extension): bool => is_file($file.$extension));
242+ }
243+
244+ private function isCompressible(string $type): bool
245+ {
246+ return str_starts_with($type, 'text/') || \in_array($type, self::COMPRESSIBLE_TYPES, true)
247+ || str_ends_with($type, '+json') || str_ends_with($type, '+xml');
248+ }
249+
250+ private function compress(string $file, string $encoding): string
251+ {
252+ $key = $this->key($file).':'.$encoding;
253+ if (isset($this->compressed[$key])) {
254+ return $this->compressed[$key];
255+ }
256+
257+ $content = (string) file_get_contents($file);
258+ $body = (string) ('br' === $encoding ? brotli_compress($content) : gzencode($content));
259+ // Past the cap, files are compressed again for each Invocation rather than growing the Warm Process.
260+ if ($this->compressedSize + \strlen($body) <= self::COMPRESSION_CACHE_SIZE) {
261+ $this->compressed[$key] = $body;
262+ $this->compressedSize += \strlen($body);
263+ }
264+
265+ return $body;
266+ }
267+
268+ /**
269+ * A strong ETag of the bytes sent, each encoding having its own as its bytes differ.
270+ */
271+ private function etag(string $file, ?string $encoding): string
272+ {
273+ $key = $this->key($file);
274+ $this->etags[$key] ??= hash_file('xxh128', $file) ?: '';
275+
276+ return '"'.$this->etags[$key].(null === $encoding ? '' : '-'.$encoding).'"';
277+ }
278+
279+ /**
280+ * Files written at runtime, such as uploads, may change within a Warm Process: their key changes with them.
281+ */
282+ private function key(string $file): string
283+ {
284+ clearstatcache(true, $file);
285+
286+ return $file.':'.filemtime($file).':'.filesize($file);
287+ }
288+
289+ /**
290+ * Weak comparison, as RFC 9110 asks for If-None-Match.
291+ */
292+ private static function matches(string $ifNoneMatch, string $etag): bool
293+ {
294+ if ('*' === trim($ifNoneMatch)) {
295+ return true;
296+ }
297+ foreach (explode(',', $ifNoneMatch) as $candidate) {
298+ $candidate = trim($candidate);
299+ if ((str_starts_with($candidate, 'W/') ? substr($candidate, 2) : $candidate) === $etag) {
300+ return true;
301+ }
302+ }
303+
304+ return false;
305+ }
306+
307+ /**
308+ * A file is cached for good only when a manifest.json above it, as written by AssetMapper or Webpack Encore, maps a
309+ * logical path to it under another name: its name then changes with its content. Guessing a digest from the name
310+ * alone would also match plain names such as "font-awesome.css".
311+ */
312+ private function isDigested(string $path, string $file): bool
313+ {
314+ $public = '/'.ltrim($path, '/');
315+ for ($dir = \dirname($file); str_starts_with($dir.\DIRECTORY_SEPARATOR, (string) $this->root.\DIRECTORY_SEPARATOR); $dir = \dirname($dir)) {
316+ if (isset($this->manifest($dir.'/manifest.json')[$public])) {
317+ return true;
318+ }
319+ if ($dir === $this->root) {
320+ break;
321+ }
322+ }
323+
324+ return false;
325+ }
326+
327+ /**
328+ * @return array<string, true>
329+ */
330+ private function manifest(string $file): array
331+ {
332+ if (!isset($this->manifests[$file])) {
333+ $digested = [];
334+ $entries = is_file($file) ? json_decode((string) file_get_contents($file), true) : null;
335+ foreach (\is_array($entries) ? $entries : [] as $logical => $public) {
336+ if (!\is_string($public)) {
337+ continue;
338+ }
339+ // Assets served from a CDN or with a base path are listed as URLs: only their path is ours.
340+ $publicPath = parse_url($public, \PHP_URL_PATH);
341+ if (\is_string($publicPath) && basename($publicPath) !== basename((string) $logical)) {
342+ $digested['/'.ltrim($publicPath, '/')] = true;
343+ }
344+ }
345+ $this->manifests[$file] = $digested;
346+ }
347+
348+ return $this->manifests[$file];
349+ }
350+}
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" or "br"', $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" or "br"', $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([], []);
added tests/StaticFilesTest.php +375 -0
new file mode 100644
@@ -0,0 +1,375 @@
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 'wildcard' => ['*', 'br'];
188+ yield 'wildcard but brotli' => ['*, br;q=0', 'gzip'];
189+ yield 'everything refused' => ['br;q=0, gzip;q=0', null];
190+ yield 'case insensitive' => ['GZIP', 'gzip'];
191+ }
192+
193+ #[DataProvider('acceptEncodings')]
194+ public function testServesThePreferredPrecompressedVariant(string $acceptEncoding, ?string $expected): void
195+ {
196+ $this->write('app.css.br', 'brotli bytes');
197+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
198+
199+ $response = $this->serve('/app.css', headers: ['Accept-Encoding' => $acceptEncoding]);
200+
201+ self::assertSame($expected, $response['headers']['Content-Encoding'] ?? null);
202+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
203+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
204+ $body = true === ($response['isBase64Encoded'] ?? false) ? base64_decode($response['body'], true) : $response['body'];
205+ self::assertSame(match ($expected) {
206+ 'br' => 'brotli bytes',
207+ 'gzip' => "\x1f\x8b gzip bytes",
208+ default => 'body { color: red; }',
209+ }, $body);
210+ }
211+
212+ public function testEachEncodingHasItsOwnETag(): void
213+ {
214+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
215+
216+ $plain = $this->serve('/app.css')['headers']['ETag'] ?? null;
217+ $gzip = $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'])['headers']['ETag'] ?? null;
218+
219+ self::assertNotSame($plain, $gzip);
220+ self::assertSame(304, $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip', 'If-None-Match' => (string) $gzip])['statusCode']);
221+ self::assertSame(200, $this->serve('/app.css', headers: ['If-None-Match' => (string) $gzip])['statusCode']);
222+ }
223+
224+ public function testAPrecompressedVariantIsAlsoAFileOfItsOwn(): void
225+ {
226+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
227+
228+ $response = $this->serve('/app.css.gz');
229+
230+ self::assertSame("\x1f\x8b gzip bytes", base64_decode($response['body'], true));
231+ self::assertArrayNotHasKey('Content-Encoding', $response['headers']);
232+ }
233+
234+ public function testCompressesTextualFilesOnTheFly(): void
235+ {
236+ $css = str_repeat('body { color: red; }', 100);
237+ $this->write('large.css', $css);
238+
239+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
240+
241+ self::assertSame('gzip', $response['headers']['Content-Encoding'] ?? null);
242+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
243+ self::assertTrue($response['isBase64Encoded'] ?? false);
244+ self::assertSame($css, gzdecode((string) base64_decode($response['body'], true)));
245+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/large.css', compression: 'gzip')['headers']);
246+ }
247+
248+ public function testLeavesSmallAndAlreadyCompressedFilesUncompressed(): void
249+ {
250+ $this->write('large.png', str_repeat("\x89", 2048));
251+
252+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip')['headers']);
253+ $png = $this->serve('/large.png', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
254+ self::assertArrayNotHasKey('Content-Encoding', $png['headers']);
255+ self::assertArrayNotHasKey('Vary', $png['headers']);
256+ }
257+
258+ public function testPrefersAPrecompressedVariantToCompressingOnTheFly(): void
259+ {
260+ $this->write('large.css', str_repeat('a', 2048));
261+ $this->write('large.css.br', 'brotli bytes');
262+
263+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip, br'], compression: 'gzip');
264+
265+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
266+ }
267+
268+ public function testCompressedBodiesAreKeptWithinTheirCap(): void
269+ {
270+ $staticFiles = $this->staticFiles('gzip');
271+ $cache = new \ReflectionProperty(StaticFiles::class, 'compressed');
272+ // Hex digits of random bytes compress to about half their size: twelve such files fill the cache past its cap.
273+ $hex = bin2hex(random_bytes(3 * 1024 * 1024));
274+ $files = range(1, 12);
275+ foreach ($files as $name) {
276+ $this->write("$name.txt", $hex);
277+ $response = $staticFiles->serve(['path' => "/$name.txt", 'headers' => ['Accept-Encoding' => 'gzip']]);
278+ self::assertSame(200, $response['statusCode'] ?? null);
279+ }
280+
281+ $cached = $cache->getValue($staticFiles);
282+ self::assertIsArray($cached);
283+ self::assertLessThan(\count($files), \count($cached));
284+ self::assertLessThanOrEqual(StaticFiles::COMPRESSION_CACHE_SIZE, array_sum(array_map(strlen(...), array_filter($cached, \is_string(...)))));
285+ $last = $staticFiles->serve(['path' => '/12.txt', 'headers' => ['Accept-Encoding' => 'gzip']]);
286+ self::assertSame($hex, gzdecode((string) base64_decode($last['body'] ?? '', true)));
287+ }
288+
289+ public function testFilesTooLargeForAFunctionResponseAreA500AndLogged(): void
290+ {
291+ $this->write('large.bin', str_repeat("\xff", 5 * 1024 * 1024));
292+ $this->write('huge.txt', str_repeat('a', StaticFiles::MAX_RESPONSE_SIZE + 1));
293+
294+ foreach (['/large.bin', '/huge.txt'] as $path) {
295+ $response = $this->serve($path);
296+ self::assertSame(500, $response['statusCode']);
297+ self::assertSame('Internal Server Error', $response['body']);
298+ }
299+ rewind($this->errorLog);
300+ $log = (string) stream_get_contents($this->errorLog);
301+ self::assertStringContainsString('Static File "/large.bin" is 6990508 bytes once encoded', $log);
302+ self::assertStringContainsString('Static File "/huge.txt"', $log);
303+ }
304+
305+ public function testResponseSizeCountsTheBase64OfBinaryFiles(): void
306+ {
307+ $this->write('binary.bin', "\xff\xff\xff");
308+
309+ self::assertSame(20, StaticFiles::responseSize($this->root.'/public/app.css'));
310+ self::assertSame(4, StaticFiles::responseSize($this->root.'/public/binary.bin'));
311+ }
312+
313+ /**
314+ * @return iterable<string, array{mixed}>
315+ */
316+ public static function invalidCompressions(): iterable
317+ {
318+ yield 'unknown encoding' => ['deflate'];
319+ yield 'true' => [true];
320+ }
321+
322+ #[DataProvider('invalidCompressions')]
323+ public function testInvalidCompressionIsAnError(mixed $compression): void
324+ {
325+ $this->expectException(\InvalidArgumentException::class);
326+
327+ StaticFiles::create($this->root, $compression, $this->errorLog);
328+ }
329+
330+ public function testBrotliCompressionNeedsTheBrotliExtension(): void
331+ {
332+ if (\function_exists('brotli_compress')) {
333+ self::markTestSkipped('The brotli extension is loaded.');
334+ }
335+
336+ $this->expectExceptionMessage('the brotli extension is not loaded');
337+
338+ StaticFiles::create($this->root, 'br', $this->errorLog);
339+ }
340+
341+ #[RequiresPhpExtension('brotli')]
342+ public function testCompressesWithBrotli(): void
343+ {
344+ $this->write('large.css', str_repeat('a', 2048));
345+
346+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'br'], compression: 'br');
347+
348+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
349+ }
350+
351+ private function write(string $path, string $content): void
352+ {
353+ new Filesystem()->dumpFile($this->root.'/public/'.$path, $content);
354+ }
355+
356+ private function staticFiles(?string $compression = null): StaticFiles
357+ {
358+ return StaticFiles::create($this->root.'/public', $compression ?? false, $this->errorLog);
359+ }
360+
361+ /**
362+ * @param array<string, string> $headers
363+ *
364+ * @return array{statusCode: int, headers: array<string, string>, body: string, isBase64Encoded?: bool}
365+ */
366+ private function serve(string $path, string $method = 'GET', array $headers = [], ?string $compression = null): array
367+ {
368+ $response = $this->staticFiles($compression)->serve(['path' => $path, 'httpMethod' => $method, 'headers' => $headers]);
369+ self::assertNotNull($response, $path);
370+ // Static Files never repeat a header: single values keep the assertions short.
371+ $response['headers'] = array_map(static fn (string|array $value): string => \is_string($value) ? $value : implode(', ', $value), $response['headers'] ?? []);
372+
373+ return $response;
374+ }
375+}
new file mode 100644
@@ -0,0 +1,375 @@
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 'wildcard' => ['*', 'br'];
188+ yield 'wildcard but brotli' => ['*, br;q=0', 'gzip'];
189+ yield 'everything refused' => ['br;q=0, gzip;q=0', null];
190+ yield 'case insensitive' => ['GZIP', 'gzip'];
191+ }
192+
193+ #[DataProvider('acceptEncodings')]
194+ public function testServesThePreferredPrecompressedVariant(string $acceptEncoding, ?string $expected): void
195+ {
196+ $this->write('app.css.br', 'brotli bytes');
197+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
198+
199+ $response = $this->serve('/app.css', headers: ['Accept-Encoding' => $acceptEncoding]);
200+
201+ self::assertSame($expected, $response['headers']['Content-Encoding'] ?? null);
202+ self::assertSame('text/css', $response['headers']['Content-Type'] ?? null);
203+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
204+ $body = true === ($response['isBase64Encoded'] ?? false) ? base64_decode($response['body'], true) : $response['body'];
205+ self::assertSame(match ($expected) {
206+ 'br' => 'brotli bytes',
207+ 'gzip' => "\x1f\x8b gzip bytes",
208+ default => 'body { color: red; }',
209+ }, $body);
210+ }
211+
212+ public function testEachEncodingHasItsOwnETag(): void
213+ {
214+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
215+
216+ $plain = $this->serve('/app.css')['headers']['ETag'] ?? null;
217+ $gzip = $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'])['headers']['ETag'] ?? null;
218+
219+ self::assertNotSame($plain, $gzip);
220+ self::assertSame(304, $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip', 'If-None-Match' => (string) $gzip])['statusCode']);
221+ self::assertSame(200, $this->serve('/app.css', headers: ['If-None-Match' => (string) $gzip])['statusCode']);
222+ }
223+
224+ public function testAPrecompressedVariantIsAlsoAFileOfItsOwn(): void
225+ {
226+ $this->write('app.css.gz', "\x1f\x8b gzip bytes");
227+
228+ $response = $this->serve('/app.css.gz');
229+
230+ self::assertSame("\x1f\x8b gzip bytes", base64_decode($response['body'], true));
231+ self::assertArrayNotHasKey('Content-Encoding', $response['headers']);
232+ }
233+
234+ public function testCompressesTextualFilesOnTheFly(): void
235+ {
236+ $css = str_repeat('body { color: red; }', 100);
237+ $this->write('large.css', $css);
238+
239+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
240+
241+ self::assertSame('gzip', $response['headers']['Content-Encoding'] ?? null);
242+ self::assertSame('Accept-Encoding', $response['headers']['Vary'] ?? null);
243+ self::assertTrue($response['isBase64Encoded'] ?? false);
244+ self::assertSame($css, gzdecode((string) base64_decode($response['body'], true)));
245+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/large.css', compression: 'gzip')['headers']);
246+ }
247+
248+ public function testLeavesSmallAndAlreadyCompressedFilesUncompressed(): void
249+ {
250+ $this->write('large.png', str_repeat("\x89", 2048));
251+
252+ self::assertArrayNotHasKey('Content-Encoding', $this->serve('/app.css', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip')['headers']);
253+ $png = $this->serve('/large.png', headers: ['Accept-Encoding' => 'gzip'], compression: 'gzip');
254+ self::assertArrayNotHasKey('Content-Encoding', $png['headers']);
255+ self::assertArrayNotHasKey('Vary', $png['headers']);
256+ }
257+
258+ public function testPrefersAPrecompressedVariantToCompressingOnTheFly(): void
259+ {
260+ $this->write('large.css', str_repeat('a', 2048));
261+ $this->write('large.css.br', 'brotli bytes');
262+
263+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'gzip, br'], compression: 'gzip');
264+
265+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
266+ }
267+
268+ public function testCompressedBodiesAreKeptWithinTheirCap(): void
269+ {
270+ $staticFiles = $this->staticFiles('gzip');
271+ $cache = new \ReflectionProperty(StaticFiles::class, 'compressed');
272+ // Hex digits of random bytes compress to about half their size: twelve such files fill the cache past its cap.
273+ $hex = bin2hex(random_bytes(3 * 1024 * 1024));
274+ $files = range(1, 12);
275+ foreach ($files as $name) {
276+ $this->write("$name.txt", $hex);
277+ $response = $staticFiles->serve(['path' => "/$name.txt", 'headers' => ['Accept-Encoding' => 'gzip']]);
278+ self::assertSame(200, $response['statusCode'] ?? null);
279+ }
280+
281+ $cached = $cache->getValue($staticFiles);
282+ self::assertIsArray($cached);
283+ self::assertLessThan(\count($files), \count($cached));
284+ self::assertLessThanOrEqual(StaticFiles::COMPRESSION_CACHE_SIZE, array_sum(array_map(strlen(...), array_filter($cached, \is_string(...)))));
285+ $last = $staticFiles->serve(['path' => '/12.txt', 'headers' => ['Accept-Encoding' => 'gzip']]);
286+ self::assertSame($hex, gzdecode((string) base64_decode($last['body'] ?? '', true)));
287+ }
288+
289+ public function testFilesTooLargeForAFunctionResponseAreA500AndLogged(): void
290+ {
291+ $this->write('large.bin', str_repeat("\xff", 5 * 1024 * 1024));
292+ $this->write('huge.txt', str_repeat('a', StaticFiles::MAX_RESPONSE_SIZE + 1));
293+
294+ foreach (['/large.bin', '/huge.txt'] as $path) {
295+ $response = $this->serve($path);
296+ self::assertSame(500, $response['statusCode']);
297+ self::assertSame('Internal Server Error', $response['body']);
298+ }
299+ rewind($this->errorLog);
300+ $log = (string) stream_get_contents($this->errorLog);
301+ self::assertStringContainsString('Static File "/large.bin" is 6990508 bytes once encoded', $log);
302+ self::assertStringContainsString('Static File "/huge.txt"', $log);
303+ }
304+
305+ public function testResponseSizeCountsTheBase64OfBinaryFiles(): void
306+ {
307+ $this->write('binary.bin', "\xff\xff\xff");
308+
309+ self::assertSame(20, StaticFiles::responseSize($this->root.'/public/app.css'));
310+ self::assertSame(4, StaticFiles::responseSize($this->root.'/public/binary.bin'));
311+ }
312+
313+ /**
314+ * @return iterable<string, array{mixed}>
315+ */
316+ public static function invalidCompressions(): iterable
317+ {
318+ yield 'unknown encoding' => ['deflate'];
319+ yield 'true' => [true];
320+ }
321+
322+ #[DataProvider('invalidCompressions')]
323+ public function testInvalidCompressionIsAnError(mixed $compression): void
324+ {
325+ $this->expectException(\InvalidArgumentException::class);
326+
327+ StaticFiles::create($this->root, $compression, $this->errorLog);
328+ }
329+
330+ public function testBrotliCompressionNeedsTheBrotliExtension(): void
331+ {
332+ if (\function_exists('brotli_compress')) {
333+ self::markTestSkipped('The brotli extension is loaded.');
334+ }
335+
336+ $this->expectExceptionMessage('the brotli extension is not loaded');
337+
338+ StaticFiles::create($this->root, 'br', $this->errorLog);
339+ }
340+
341+ #[RequiresPhpExtension('brotli')]
342+ public function testCompressesWithBrotli(): void
343+ {
344+ $this->write('large.css', str_repeat('a', 2048));
345+
346+ $response = $this->serve('/large.css', headers: ['Accept-Encoding' => 'br'], compression: 'br');
347+
348+ self::assertSame('br', $response['headers']['Content-Encoding'] ?? null);
349+ }
350+
351+ private function write(string $path, string $content): void
352+ {
353+ new Filesystem()->dumpFile($this->root.'/public/'.$path, $content);
354+ }
355+
356+ private function staticFiles(?string $compression = null): StaticFiles
357+ {
358+ return StaticFiles::create($this->root.'/public', $compression ?? false, $this->errorLog);
359+ }
360+
361+ /**
362+ * @param array<string, string> $headers
363+ *
364+ * @return array{statusCode: int, headers: array<string, string>, body: string, isBase64Encoded?: bool}
365+ */
366+ private function serve(string $path, string $method = 'GET', array $headers = [], ?string $compression = null): array
367+ {
368+ $response = $this->staticFiles($compression)->serve(['path' => $path, 'httpMethod' => $method, 'headers' => $headers]);
369+ self::assertNotNull($response, $path);
370+ // Static Files never repeat a header: single values keep the assertions short.
371+ $response['headers'] = array_map(static fn (string|array $value): string => \is_string($value) ? $value : implode(', ', $value), $response['headers'] ?? []);
372+
373+ return $response;
374+ }
375+}