Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions src/DonutBody.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

use BEAR\Resource\AbstractRequest;
use BEAR\Resource\ResourceInterface;
use BEAR\Resource\ResourceObject;
use Override;

use function assert;

/**
* A page stored as the body it returned, rendered again with its embedded requests put back
*
* @internal
*/
final readonly class DonutBody implements DonutCompositionInterface
{
/**
* @param array<array-key, mixed> $body each embedded request null
* @param array<array-key, string> $embeds toUri() of each request embedded in the body, by its key
* @param array<string, string> $headers
*/
public function __construct(
private array $body,
private array $embeds,
private array $headers,
private int $code,
) {
}

/** The renderer reads the stored headers and code; the code is set again in case the renderer changed it */
#[Override]
public function recompose(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void
{
$body = $this->body;
$requests = [];
foreach ($this->embeds as $key => $reference) {
$request = $resource->uri($reference);
assert($request instanceof AbstractRequest);
$requests[] = $body[$key] = $request;
}

$ro->body = $body;
$ro->headers = $this->headers;
$ro->code = $this->code;
$ro->view = null;
$ro->toString();
foreach ($requests as $request) {
// After rendering: what a request passes up from the requests it embeds itself is known once those have run
$dependencies->hole(DonutRequest::resultOf($request));
}

$ro->code = $this->code;
}
}
23 changes: 23 additions & 0 deletions src/DonutCompositionInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

use BEAR\Resource\ResourceInterface;
use BEAR\Resource\ResourceObject;

/**
* How a stored donut page is put together again on a hit
*
* @internal
*/
interface DonutCompositionInterface
{
/**
* Leaves the page's view, headers and code on $ro, and each hole it reads in $dependencies
*
* A failed rendering throws and may leave $ro partly written; it never yields an empty view.
*/
public function recompose(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void;
}
1 change: 0 additions & 1 deletion src/DonutRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,6 @@ private function write(ResourceObject $ro, bool $isPage, int|null $ttl, int|null
// A per-write renderer from the provider isolates hole views across requests and concurrent coroutines
$renderer = $this->rendererProvider->get();
$donut = ResourceDonut::create($ro, $renderer, $keys, $sMaxAge, $isPage)->withStorageState($ttl, $templateTags);
$donut->render($ro, $renderer);
// Checked on the rendered response before the write adds its own headers
$storability = $this->declaredCacheControl->storability($ro);
$keys->addTo($ro);
Expand Down
46 changes: 46 additions & 0 deletions src/DonutTemplate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace BEAR\QueryRepository;

use BEAR\Resource\ResourceInterface;
use BEAR\Resource\ResourceObject;
use Override;

use function preg_replace_callback;
use function rawurldecode;

/**
* A page stored as its rendered view, each hole a placeholder
*
* @internal
*/
final readonly class DonutTemplate implements DonutCompositionInterface
{
/** @param array<string, string> $headers */
public function __construct(
private string $template,
private array $headers,
private int $code,
) {
}

/** $ro is left untouched until every hole has been read */
#[Override]
public function recompose(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void
{
$view = preg_replace_callback(ResourceDonut::URI_REGEX, static function (array $matches) use ($resource, $dependencies): string {
$reference = rawurldecode($matches[1]);
// toString(), not (string): the cast turns a render failure into '', which would be served
$hole = $resource->get($reference);
$hole->toString();
$dependencies->hole($hole);

return (string) $hole->view;
}, $this->template);
$ro->headers = $this->headers;
$ro->view = $view;
$ro->code = $this->code;
}
}
120 changes: 20 additions & 100 deletions src/ResourceDonut.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
use function is_array;
use function is_iterable;
use function max;
use function preg_replace_callback;
use function rawurldecode;
use function rawurlencode;
use function serialize;
use function sprintf;
Expand All @@ -30,13 +28,13 @@
*
* @internal
*/
final class ResourceDonut
final readonly class ResourceDonut
{
// The reference is rawurlencode()'d: percent-encoding leaves no '&', '<', '>', '"' or '\'' for an HTML renderer's
// autoescaping to change, so the placeholder reads the same echoed raw or through Twig's `{{ hole }}`
private const FORMAT = '[le2:%s]';

private const URI_REGEX = '/\[le2:([^\]]+)]/';
public const URI_REGEX = '/\[le2:([^\]]+)]/';

/**
* Build the placeholder DonutRequest::__toString() embeds and DonutRenderer matches
Expand All @@ -47,48 +45,28 @@ public static function placeholder(string $reference): string
}

/**
* @param array<string, string> $headers
* @param int|null $sMaxAge CDN lifetime and stored lifetime of the page view; unused by a template-only donut
* @param int|null $lastModified Time when the composed content last actually changed
* @param list<string> $storageTags Invalidation tags of the donut template entry, without the application key the storage adds
* @param int $code Status code the page was stored with
* @param array<array-key, mixed>|null $body The body the page returned, each embedded request null, when its renderer prints no placeholder; null when the template holds the page
* @param array<array-key, string> $embeds toUri() of each request embedded in the body, by its key
*
* @SuppressWarnings("PHPMD.ExcessiveParameterList")
* @param int|null $sMaxAge CDN lifetime and stored lifetime of the page view; unused when $isPage is false
* @param int|null $lastModified Time when the composed content last actually changed
* @param list<string> $storageTags Invalidation tags of the donut template entry, without the application key the storage adds
*/
public function __construct(
private readonly string $template,
private readonly array $headers,
public readonly int|null $sMaxAge,
public readonly bool $isPage,
private readonly int|null $lastModified = null,
private readonly string|null $contentHash = null,
private readonly int|null $templateExpiresAt = null,
private readonly array $storageTags = [],
private readonly int $code = 200,
private readonly array|null $body = null,
private readonly array $embeds = [],
private DonutCompositionInterface $composition,
public int|null $sMaxAge,
public bool $isPage,
private int|null $lastModified = null,
private string|null $contentHash = null,
private int|null $templateExpiresAt = null,
private array $storageTags = [],
) {
}

/** Answers the page again from what was stored. Whatever fails on the way degrades the hit to a fresh run of the page. */
public function refresh(ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): ResourceObject
{
try {
if ($this->body === null) {
$view = $this->compose($resource, $dependencies);
$ro->headers = $this->headers;
$ro->view = $view;
}

if ($this->body !== null) {
$this->renderBody($this->body, $resource, $ro, $dependencies);
}
$this->composition->recompose($resource, $ro, $dependencies);

$ro->code = $this->code;

// $this->headers lacks the group tag; add the stored tags.
// The stored headers lack the group tag
(new TagSet($this->getStorageTags()))->addTo($ro);

$dependencies->addTo($ro);
Expand All @@ -99,58 +77,6 @@ public function refresh(ResourceInterface $resource, ResourceObject $ro, Depende
return $ro;
}

/** The template with the view of each embedded request, read again, in its place */
private function compose(ResourceInterface $resource, Dependencies $dependencies): string|null
{
return preg_replace_callback(self::URI_REGEX, static function (array $matches) use ($resource, $dependencies): string {
$reference = rawurldecode($matches[1]);
// toString(), not (string): the cast turns a render failure into '', which would be served
$ro = $resource->get($reference);
$ro->toString();
$dependencies->hole($ro);

return (string) $ro->view;
}, $this->template);
}

/**
* Renders the stored body with the page's own renderer, its embedded requests put back
*
* @param array<array-key, mixed> $body
*/
private function renderBody(array $body, ResourceInterface $resource, ResourceObject $ro, Dependencies $dependencies): void
{
$requests = [];
foreach ($this->embeds as $key => $reference) {
$request = $resource->uri($reference);
assert($request instanceof AbstractRequest);
$requests[] = $body[$key] = $request;
}

$ro->body = $body;
$ro->headers = $this->headers;
$ro->code = $this->code;
$ro->view = null;
$ro->toString();
foreach ($requests as $request) {
// After rendering: what a request passes up from the requests it embeds itself is known once those have run
$dependencies->hole(DonutRequest::resultOf($request));
}
}

public function render(ResourceObject $ro, DonutRendererInterface $storage): ResourceObject
{
// A page stored as its body was rendered when the donut was created
if ($this->body !== null) {
return $ro;
}

$view = $storage->render($this->template);
$ro->view = $view;

return $ro;
}

/**
* Return the Last-Modified time to carry over when the refreshed content is
* byte-identical to the content recorded with this donut, null otherwise.
Expand Down Expand Up @@ -180,17 +106,13 @@ public function withContentState(ResourceObject $ro): self
}

return new self(
$this->template,
$this->headers,
$this->composition,
$this->sMaxAge,
$this->isPage,
$lastModified,
$this->hashContent((string) $ro->view),
$this->templateExpiresAt,
$this->storageTags,
$this->code,
$this->body,
$this->embeds,
);
}

Expand All @@ -202,17 +124,13 @@ public function withContentState(ResourceObject $ro): self
public function withStorageState(int|null $ttl, array $tags): self
{
return new self(
$this->template,
$this->headers,
$this->composition,
$this->sMaxAge,
$this->isPage,
$this->lastModified,
$this->contentHash,
$ttl !== null && $ttl > 0 ? time() + $ttl : null,
$tags,
$this->code,
$this->body,
$this->embeds,
);
}

Expand Down Expand Up @@ -260,7 +178,9 @@ public static function create(ResourceObject $ro, DonutRendererInterface $storag
}
}

return new self($donutTemplate, $ro->headers, $sMaxAge, $isPage, code: $ro->code);
$ro->view = $storage->render($donutTemplate);

return new self(new DonutTemplate($donutTemplate, $ro->headers, $ro->code), $sMaxAge, $isPage);
}

/** @return array<array-key, DonutRequest> */
Expand Down Expand Up @@ -335,6 +255,6 @@ private static function ofBody(ResourceObject $ro, array $embeds, Dependencies $
$dependencies->hole($invoked[$key] ?? DonutRequest::resultOf($embed->request));
}

return new self('', $ro->headers, $sMaxAge, $isPage, code: $ro->code, body: $body, embeds: $references);
return new self(new DonutBody($body, $references, $ro->headers, $ro->code), $sMaxAge, $isPage);
}
}
2 changes: 1 addition & 1 deletion tests/AppSurrogateKeyModuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public function testInvalidatingTheKeyDropsEntriesSavedDirectly(): void
$view->uri = new Uri('app://self/direct-view');
$view->view = 'view';
$this->storage->saveValue($ro, 0);
$this->storage->saveDonut($ro->uri, new ResourceDonut('template', [], null, false), null, ['direct']);
$this->storage->saveDonut($ro->uri, new ResourceDonut(new DonutTemplate('template', [], 200), null, false), null, ['direct']);
$this->storage->saveDonutView($view, null, ['explicit']);
$this->assertNotNull($this->storage->get($ro->uri));
$this->assertNotNull($this->storage->getDonut($ro->uri));
Expand Down
Loading
Loading