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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**
Expand Down
2 changes: 2 additions & 0 deletions src/Embed/EmbedRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
5 changes: 3 additions & 2 deletions src/Embed/SsrCacheKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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(
Expand Down
155 changes: 126 additions & 29 deletions src/Embed/SsrClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> */
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
Expand All @@ -275,42 +388,23 @@ 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<string, string>
*/
private function requestHeaders(EmbedRequest $request): array
{
$headers = [];
if ($request->requestId !== null && $request->requestId !== '') {
$headers['X-Request-Id'] = $request->requestId;
}
if ($request->assetVersion !== null && $request->assetVersion !== '') {
$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;
}

/**
Expand All @@ -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;
}
Expand Down
18 changes: 18 additions & 0 deletions src/Embed/SsrOgImage.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

declare(strict_types=1);

namespace OpenMapsight\Embed;

/**
* A rendered Open Graph card from sidecar `POST /v1/og`: bytes plus their
* content type (`image/png`). Serve it with long-lived public caching.
*/
final class SsrOgImage
{
public function __construct(
public readonly string $contentType,
public readonly string $body,
) {
}
}
Loading
Loading