From fc92b45ea8820d85b2e45ec0d1906daadfa38799 Mon Sep 17 00:00:00 2001 From: Paul Golmann Date: Tue, 3 Nov 2026 03:13:34 +0100 Subject: [PATCH] Support Open Graph images in the next host API --- CHANGELOG.md | 8 ++ README.md | 34 ++++++++ src/Embed/EmbedRequest.php | 2 + src/Embed/SsrCacheKey.php | 5 +- src/Embed/SsrClient.php | 155 ++++++++++++++++++++++++++++++------- src/Embed/SsrOgImage.php | 18 +++++ tests/SsrClientTest.php | 133 +++++++++++++++++++++++++++++++ 7 files changed, 324 insertions(+), 31 deletions(-) create mode 100644 src/Embed/SsrOgImage.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 868ec0f..2450060 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,14 @@ shared by `Renderer` and `SsrPublish`. `render()` returns `RenderedEmbed` hardening. `health()` and `warm()`. `Testing\FakeSsrTransport`. - PHPStan at max, `composer validate --strict`, `--prefer-lowest` CI, `failOnDeprecation`. `SECURITY.md`. +- `SsrClient::ogImage(EmbedRequest)` fetches a place's Open Graph card from + sidecar `POST /v1/og` (`@mapsight/ssr-sidecar` 0.2) with the same body as + the render, for the host's own public OG endpoint: `SsrOgImage` + (`contentType`, `body`) or null (no share param, breaker open, sidecar + 404 or error). `EmbedRequest::$ogImageEndpoint` forwards that endpoint as + `options.ogImageEndpoint`, so the sidecar links + `{endpoint}?feature=…&module=…&src=…` as `og:image` of a place; it is + part of `SsrCacheKey`. - Streams fallback reads the response headers from the stream metadata (`stream_get_meta_data()`), not `$http_response_header` (deprecated in PHP 8.5) or `$GLOBALS` (empty there). One code path for PHP 8.2–8.5. diff --git a/README.md b/README.md index 5545d89..db339d5 100644 --- a/README.md +++ b/README.md @@ -226,6 +226,40 @@ here: --- +## Open Graph cards + +Sidecar 0.2 renders a place's Open Graph card on `POST /v1/og` (same body as +`/v1/render`). The sidecar stays off public ingress, so the host serves the +card from an endpoint of its own and names it on the placement: + +```php +// On the page: the sidecar links {endpoint}?feature=…&module=…&src=… +// as og:image of a place instead of the static card. +$request = new EmbedRequest( + preset: 'simpleMap', + containerId: 'mapsight-embed-1', + config: $mapOptions, // the same preset options used on the page + requestUrl: '/map/?feature=poi-1', // use the endpoint's validated share params + pageOrigin: 'https://www.example.com', + ogImageEndpoint: 'https://www.example.com/mapsight/og.php', +); + +// On that endpoint, with the same EmbedRequest (requestUrl carrying the +// feature, module and src params of the request): +$image = $ssr->ogImage($request); +if ($image === null) { + header('Location: https://www.example.com/plan/img/og-default.png', true, 302); + exit; +} +header('Content-Type: ' . $image->contentType); +header('Cache-Control: public, max-age=3600'); +echo $image->body; +``` + +`ogImage()` is fail-open: null without a share param on `requestUrl`, while +the breaker is open, and on a sidecar `404` or error. Add `src` to +`shareParams` when your request URLs carry a feature-source hint. + ## Publish / purge When a feature-source or GeoJSON file changes, call `SsrPublish` **before** diff --git a/src/Embed/EmbedRequest.php b/src/Embed/EmbedRequest.php index 60176fb..e3e34c2 100644 --- a/src/Embed/EmbedRequest.php +++ b/src/Embed/EmbedRequest.php @@ -40,6 +40,8 @@ public function __construct( public readonly ?string $pageOrigin = null, public readonly ?string $ogImage = null, public readonly ?string $scriptNonce = null, + /** Absolute URL of the host's own Open Graph endpoint ({@see SsrClient::ogImage()}). */ + public readonly ?string $ogImageEndpoint = null, ) { self::assertJsIdentifier($this->preset, 'preset'); if (preg_match('/^[A-Za-z][A-Za-z0-9_:.-]*$/', $this->containerId) !== 1) { diff --git a/src/Embed/SsrCacheKey.php b/src/Embed/SsrCacheKey.php index 6baf228..5e07eee 100644 --- a/src/Embed/SsrCacheKey.php +++ b/src/Embed/SsrCacheKey.php @@ -6,8 +6,8 @@ /** * Stable key for a v1 SSR placement: config + locale/deviceClass + assetVersion - * + normalised requestUrl + contract. pageOrigin / ogImage stay in the key - * so cached pageMeta stays absolute. + * + normalised requestUrl + contract. pageOrigin / ogImage / ogImageEndpoint + * stay in the key so cached pageMeta stays absolute and links the right card. */ final class SsrCacheKey { @@ -25,6 +25,7 @@ public static function for(EmbedRequest $request, ?string $requestUrl): string 'requestUrl' => $requestUrl, 'pageOrigin' => self::nonEmpty($request->pageOrigin), 'ogImage' => self::nonEmpty($request->ogImage), + 'ogImageEndpoint' => self::nonEmpty($request->ogImageEndpoint), ]; return hash( diff --git a/src/Embed/SsrClient.php b/src/Embed/SsrClient.php index bfd0b40..0158aec 100644 --- a/src/Embed/SsrClient.php +++ b/src/Embed/SsrClient.php @@ -20,6 +20,9 @@ final class SsrClient public const MAX_REQUEST_URL_BYTES = 2048; + /** Cards are a few dozen KB; anything larger is not a card. */ + public const MAX_IMAGE_BYTES = 4194304; + private const MAX_BODY_BYTES = 262144; /** @var list */ @@ -142,6 +145,52 @@ public function warm(EmbedRequest $request): SsrOutcome return $this->resolve($request, true)->outcome; } + /** + * The sidecar's Open Graph card of the place on `$request->requestUrl` + * (`?feature=`), for the host's own public OG endpoint. Same payload as + * the page render, so both resolve the same place. + * + * Fail-open: null when the request has no share param, the breaker is + * open, the sidecar has no card (404) or fails. Serve the static card then. + */ + public function ogImage(EmbedRequest $request): ?SsrOgImage + { + $started = microtime(true); + $requestUrl = $this->normalizeRequestUrl($request->requestUrl); + if (!$this->requestHasPageMetaParam($requestUrl)) { + return null; + } + if (!$this->breaker->allow()) { + $this->logger->warning('mapsight ssr og skipped', [ + 'reason' => 'breaker_open', + 'url' => rtrim($this->ssrUrl, '/') . '/v1/og', + 'request_id' => $request->requestId, + ]); + + return null; + } + + try { + $image = $this->fetchOgImage($request, $requestUrl); + $this->breaker->recordSuccess(); + + return $image; + } catch (SsrUnavailable $error) { + $this->noteBreakerFailure(); + } catch (\Throwable $error) { + // Bad request or response: not the sidecar's health. + } + $this->logger->warning('mapsight ssr og skipped', [ + 'reason' => $error->getMessage(), + 'status' => self::statusFromMessage($error->getMessage()), + 'url' => rtrim($this->ssrUrl, '/') . '/v1/og', + 'elapsed_ms' => $this->elapsedMs($started), + 'request_id' => $request->requestId, + ]); + + return null; + } + public function health(): bool { try { @@ -253,6 +302,70 @@ public function requestHasPageMetaParam(?string $normalizedRequestUrl): bool } private function fetchDocument(EmbedRequest $request, ?string $requestUrl): SsrDocument + { + $url = rtrim($this->ssrUrl, '/') . '/v1/render'; + $response = $this->transport->send(new SsrHttpRequest( + 'POST', + $url, + ['Accept' => 'application/json'] + $this->requestHeaders($request), + $this->encodeBody($request, $requestUrl), + $this->timeoutSeconds, + $this->connectTimeoutSeconds, + )); + + if (strlen($response->body) > $this->maxResponseBytes) { + throw new SsrClientError('SSR response exceeds size cap'); + } + if ($response->status >= 400 && $response->status < 500) { + throw new SsrClientError('SSR HTTP status ' . $response->status); + } + if ($response->status < 200 || $response->status >= 300) { + throw new SsrUnavailable('SSR HTTP status ' . $response->status); + } + if (!$this->isJsonContentType($response->contentType)) { + throw new SsrClientError('SSR response Content-Type must be application/json'); + } + + return SsrV1Document::fromResponse( + $response->body, + $request->containerId, + $this->maxStateBytes, + ); + } + + private function fetchOgImage(EmbedRequest $request, ?string $requestUrl): ?SsrOgImage + { + $response = $this->transport->send(new SsrHttpRequest( + 'POST', + rtrim($this->ssrUrl, '/') . '/v1/og', + ['Accept' => 'image/png, application/json'] + $this->requestHeaders($request), + $this->encodeBody($request, $requestUrl), + $this->timeoutSeconds, + $this->connectTimeoutSeconds, + )); + + if ($response->status === 404) { + return null; + } + if ($response->status >= 400 && $response->status < 500) { + throw new SsrClientError('SSR og HTTP status ' . $response->status); + } + if ($response->status < 200 || $response->status >= 300) { + throw new SsrUnavailable('SSR og HTTP status ' . $response->status); + } + $type = strtolower(trim((string) strtok((string) $response->contentType, ';'))); + if (!str_starts_with($type, 'image/')) { + throw new SsrClientError('SSR og response Content-Type must be an image'); + } + if ($response->body === '' || strlen($response->body) > self::MAX_IMAGE_BYTES) { + throw new SsrClientError('SSR og response has no usable image'); + } + + return new SsrOgImage($type, $response->body); + } + + /** The v1 body both `/v1/render` and `/v1/og` take. */ + private function encodeBody(EmbedRequest $request, ?string $requestUrl): string { $payload = [ 'v' => SsrContract::VERSION, @@ -275,7 +388,15 @@ private function fetchDocument(EmbedRequest $request, ?string $requestUrl): SsrD throw new SsrClientError('SSR request body exceeds size cap'); } - $headers = ['Accept' => 'application/json']; + return $json; + } + + /** + * @return array + */ + private function requestHeaders(EmbedRequest $request): array + { + $headers = []; if ($request->requestId !== null && $request->requestId !== '') { $headers['X-Request-Id'] = $request->requestId; } @@ -283,34 +404,7 @@ private function fetchDocument(EmbedRequest $request, ?string $requestUrl): SsrD $headers['X-Mapsight-Asset-Version'] = $request->assetVersion; } - $url = rtrim($this->ssrUrl, '/') . '/v1/render'; - $response = $this->transport->send(new SsrHttpRequest( - 'POST', - $url, - $headers, - $json, - $this->timeoutSeconds, - $this->connectTimeoutSeconds, - )); - - if (strlen($response->body) > $this->maxResponseBytes) { - throw new SsrClientError('SSR response exceeds size cap'); - } - if ($response->status >= 400 && $response->status < 500) { - throw new SsrClientError('SSR HTTP status ' . $response->status); - } - if ($response->status < 200 || $response->status >= 300) { - throw new SsrUnavailable('SSR HTTP status ' . $response->status); - } - if (!$this->isJsonContentType($response->contentType)) { - throw new SsrClientError('SSR response Content-Type must be application/json'); - } - - return SsrV1Document::fromResponse( - $response->body, - $request->containerId, - $this->maxStateBytes, - ); + return $headers; } /** @@ -332,6 +426,9 @@ private function ssrOptions(EmbedRequest $request, ?string $requestUrl): array if ($request->ogImage !== null && $request->ogImage !== '') { $options['ogImage'] = $request->ogImage; } + if ($request->ogImageEndpoint !== null && $request->ogImageEndpoint !== '') { + $options['ogImageEndpoint'] = $request->ogImageEndpoint; + } if ($request->locale !== null && $request->locale !== '') { $options['locale'] = $request->locale; } diff --git a/src/Embed/SsrOgImage.php b/src/Embed/SsrOgImage.php new file mode 100644 index 0000000..65cdd0e --- /dev/null +++ b/src/Embed/SsrOgImage.php @@ -0,0 +1,18 @@ +assertNull($cache->get('k0')); $this->assertNotNull($cache->get('k' . (ArraySsrResultCache::MAX_ENTRIES + 1))); } + + public function test_og_image_posts_the_render_payload_and_returns_the_card(): void + { + $transport = new FakeSsrTransport(); + $transport->queue(new SsrHttpResponse(200, 'image/png', "\x89PNG")); + $client = new SsrClient(ssrUrl: 'http://ssr:4123', transport: $transport); + + $image = $client->ogImage($this->placeRequest()); + + $this->assertSame('image/png', $image?->contentType); + $this->assertSame("\x89PNG", $image?->body); + $sent = $transport->requests[0]; + $this->assertSame('POST', $sent->method); + $this->assertSame('http://ssr:4123/v1/og', $sent->url); + $this->assertSame('image/png, application/json', $sent->headers['Accept']); + $this->assertSame('og-1', $sent->headers['X-Request-Id']); + $this->assertSame('bundle-1', $sent->headers['X-Mapsight-Asset-Version']); + $payload = json_decode((string) $sent->body, true, 512, JSON_THROW_ON_ERROR); + $this->assertSame(1, $payload['v']); + $this->assertSame('og-1', $payload['requestId']); + $this->assertSame('bundle-1', $payload['assetVersion']); + $this->assertSame('placeMap', $payload['preset']); + $this->assertSame('/plan/?feature=poi-1&module=landmarks', $payload['options']['requestUrl']); + $this->assertSame('https://www.example.de/mapsight/og.php', $payload['options']['ogImageEndpoint']); + $this->assertSame('/plan/img/og-default.png', $payload['options']['ogImage']); + $this->assertSame('https://www.example.de', $payload['options']['pageOrigin']); + } + + public function test_og_image_is_null_without_a_share_param(): void + { + $transport = new FakeSsrTransport(); + $client = new SsrClient(ssrUrl: 'http://ssr:4123', transport: $transport); + + $this->assertNull($client->ogImage($this->placeRequest('/plan/'))); + $this->assertSame([], $transport->requests); + } + + public function test_og_image_is_null_when_the_sidecar_has_no_card_or_answers_badly(): void + { + $transport = new FakeSsrTransport(); + $transport->queue(new SsrHttpResponse(404, 'application/json', '{"v":1,"error":{"code":"NOT_FOUND","message":"no og image"}}')); + $transport->queue(new SsrHttpResponse(200, 'text/html', '')); + $transport->queue(new SsrHttpResponse(503, 'text/plain', 'down')); + $transport->queue(new \OpenMapsight\Embed\SsrUnavailable('connect timeout')); + $client = new SsrClient(ssrUrl: 'http://ssr:4123', transport: $transport); + + $this->assertNull($client->ogImage($this->placeRequest())); + $this->assertNull($client->ogImage($this->placeRequest())); + $this->assertNull($client->ogImage($this->placeRequest())); + $this->assertNull($client->ogImage($this->placeRequest())); + $this->assertCount(4, $transport->requests); + } + + public function test_cache_key_includes_the_og_image_endpoint(): void + { + $url = '/plan/?module=landmarks&feature=poi-1'; + $with = $this->placeRequest($url); + $without = $this->placeRequest($url, null); + + $this->assertNotSame(SsrCacheKey::for($with, $with->requestUrl), SsrCacheKey::for($without, $without->requestUrl)); + } + + public function test_og_image_rejects_empty_and_oversized_images(): void + { + $transport = new FakeSsrTransport(); + $transport->queue(new SsrHttpResponse(200, 'image/png', '')); + $transport->queue(new SsrHttpResponse(200, 'image/png', str_repeat('x', SsrClient::MAX_IMAGE_BYTES + 1))); + $client = new SsrClient(ssrUrl: 'http://ssr:4123', transport: $transport); + + $this->assertNull($client->ogImage($this->placeRequest())); + $this->assertNull($client->ogImage($this->placeRequest())); + $this->assertCount(2, $transport->requests); + } + + public function test_og_request_size_cap_is_checked_before_transport(): void + { + $transport = new FakeSsrTransport(); + $client = new SsrClient(ssrUrl: 'http://ssr:4123', transport: $transport); + $request = new EmbedRequest( + preset: 'placeMap', + containerId: 'host-map', + config: ['padding' => str_repeat('x', 262144)], + requestUrl: '/plan/?feature=poi-1', + ); + + $this->assertNull($client->ogImage($request)); + $this->assertSame([], $transport->requests); + } + + public function test_source_and_module_hints_are_forwarded_and_do_not_reuse_another_placement(): void + { + $transport = new FakeSsrTransport(); + for ($i = 0; $i < 3; $i++) { + $transport->queueV1('
'); + } + $client = new SsrClient( + ssrUrl: 'http://ssr:4123', + transport: $transport, + resultCache: new ArraySsrResultCache(), + shareParams: ['module', 'feature', 'src'], + ); + $url = '/plan/?module=landmarks&feature=shared-id&src=places'; + $places = $this->placeRequest($url); + $otherSource = $this->placeRequest(str_replace('src=places', 'src=museums', $url)); + $otherModule = $this->placeRequest(str_replace('module=landmarks', 'module=culture', $url)); + + $this->assertSame(SsrOutcome::Rendered, $client->resolve($places)->outcome); + $this->assertSame(SsrOutcome::Cached, $client->resolve($places)->outcome); + $this->assertSame(SsrOutcome::Rendered, $client->resolve($otherSource)->outcome); + $this->assertSame(SsrOutcome::Rendered, $client->resolve($otherModule)->outcome); + $this->assertCount(3, $transport->requests); + $payload = json_decode((string) $transport->requests[0]->body, true, 512, JSON_THROW_ON_ERROR); + $this->assertSame('/plan/?feature=shared-id&module=landmarks&src=places', $payload['options']['requestUrl']); + } + + private function placeRequest( + string $requestUrl = '/plan/?module=landmarks&feature=poi-1&x=1', + ?string $ogImageEndpoint = 'https://www.example.de/mapsight/og.php', + ): EmbedRequest + { + return new EmbedRequest( + preset: 'placeMap', + containerId: 'host-map', + config: ['project' => ['version' => 1]], + requestId: 'og-1', + assetVersion: 'bundle-1', + requestUrl: $requestUrl, + pageOrigin: 'https://www.example.de', + ogImage: '/plan/img/og-default.png', + ogImageEndpoint: $ogImageEndpoint, + ); + } }