Skip to content

Commit

Permalink
UI: add HTTP cache headers; cache files content
Browse files Browse the repository at this point in the history
  • Loading branch information
roxblnfk committed Dec 29, 2023
1 parent e5e642d commit a0c6e60
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
19 changes: 13 additions & 6 deletions src/Sender/Frontend/Http/StaticFiles.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ public function handle(ServerRequestInterface $request, callable $next): Respons
if (\preg_match('#^/((?:[a-zA-Z0-9\\-_]+/)*[a-zA-Z0-9.\\-\\[\\]() _]+?\\.([a-zA-Z0-4]++))$#', $path, $matches)) {
$file = \sprintf("%s/resources/frontend/%s", Info::TRAP_ROOT, $matches[1]);
if (!\is_file($file)) {
/** @var array<non-empty-string, string> $cache */
static $cache = [];
if (!\array_key_exists($file, $cache) && !\is_file($file)) {
return new Response(404);
}
Expand All @@ -51,11 +54,11 @@ public function handle(ServerRequestInterface $request, callable $next): Respons

if ($path === '/index.html') {
if (empty($this->earlyResponse)) {
$content = \file_get_contents($file);
$cache[$file] ??= \file_get_contents($file);
// Find all CSS files
\preg_match_all(
'#\\bhref="([^"]+?\\.css)"#i',
$content,
$cache[$file],
$matches,
);
$this->earlyResponse = \array_unique($matches[1]);
Expand All @@ -71,14 +74,18 @@ public function handle(ServerRequestInterface $request, callable $next): Respons
// (new \Buggregator\Trap\Support\Timer(2))->wait(); // to test early hints
}

$cache[$file] ??= \file_get_contents($file);

return new Response(
200,
[
'Content-Type' => $type,
'Content-Length' => \filesize($file),
'Content-Type' => [$type],
'Content-Length' => [\filesize($file)],
'Date' => [\gmdate('D, d M Y H:i:s T')],
'Cache-Control' => ['max-age=604801'],
'ETag' => [\sha1($cache[$file])],
] + $headers,
$content ?? \file_get_contents($file),
$cache[$file] ??= \file_get_contents($file),
);
}

Expand Down
6 changes: 3 additions & 3 deletions src/Support/StreamHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
*/
final class StreamHelper
{
private const CHUNK_SIZE = 1048576; // 1 Mb
private const WRITE_STREAM_CHUNK_SIZE = 8388608; // 8 Mb
private const MAX_FILE_MEMORY_SIZE = 4194304; // 4MB
private const CHUNK_SIZE = 1 * 1024 * 1024; // 1 Mb
private const WRITE_STREAM_CHUNK_SIZE = 8 * 1024 * 1024; // 8 Mb
private const MAX_FILE_MEMORY_SIZE = 4 * 1024 * 1024; // 4MB

/**
* @param non-empty-string $substr
Expand Down

0 comments on commit a0c6e60

Please sign in to comment.