From 4b5e30f8698995b8e8a026e7351250d242e60d9d Mon Sep 17 00:00:00 2001 From: Jean Gerard Bousiquot Date: Sun, 6 Dec 2026 01:02:26 -0500 Subject: [PATCH 1/3] kit/speed: the Speed client, starting with social cards createSocialCardsClient({ url, token, timeoutMs? }).getCard(input) over gRPC-Web on fetch (Connect-ES 2.3, protobuf-es 2.17): Bearer token, a 1.5 s deadline, no retries, typed SpeedError codes, redirects refused (sent as 'manual': Workers refuse Connect's 'error' before 2026-12-22). socialCardOr(defaultUrl, promise) never throws and falls back to the app's own card. The proto is copied from Speed's repository at 10648f9 (proto/README.md); bun run generate rewrites src/speed/gen, and CI checks the two match. Optional peers; 34.5 kB gzipped, budget 40 kB. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 + CHANGELOG.md | 4 + README.md | 20 ++ buf.gen.yaml | 11 + buf.yaml | 8 + bun.lock | 39 +++ docs/speed.md | 138 ++++++++ package.json | 31 +- proto/README.md | 6 + proto/speed/socialcards/v1/social_cards.proto | 90 ++++++ scripts/check-package.ts | 5 + scripts/check-size.ts | 8 + src/speed.test.ts | 234 ++++++++++++++ src/speed.ts | 29 ++ .../speed/socialcards/v1/social_cards_pb.ts | 300 ++++++++++++++++++ src/speed/social-cards.ts | 254 +++++++++++++++ 16 files changed, 1176 insertions(+), 3 deletions(-) create mode 100644 buf.gen.yaml create mode 100644 buf.yaml create mode 100644 docs/speed.md create mode 100644 proto/README.md create mode 100644 proto/speed/socialcards/v1/social_cards.proto create mode 100644 src/speed.test.ts create mode 100644 src/speed.ts create mode 100644 src/speed/gen/speed/socialcards/v1/social_cards_pb.ts create mode 100644 src/speed/social-cards.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 286ec67..5a969c3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,8 @@ jobs: - run: bun audit --audit-level=high - run: bun run format:check - run: bun run typecheck + # kit/speed: the copied proto passes buf lint, and the generated code matches it. + - run: bunx buf lint && bun run generate && git diff --exit-code src/speed/gen - run: bun run test # The published files: built, loadable, and free of anything app-specific (scripts/check-package.ts). - run: bun run build diff --git a/CHANGELOG.md b/CHANGELOG.md index 26dd90c..bad374b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ All notable changes to `@jgb-solutions/kit`. Versions follow semver. +## Unreleased + +- `kit/speed` (new): typed clients for the Speed service, starting with social cards. `createSocialCardsClient({ url, token, timeoutMs? })` and `.getCard(input)` speak gRPC-Web over `fetch` (Connect-ES 2.3, protobuf-es 2.17), so they run on Workers, Bun and Node; one call, no retries, a 1.5 s deadline; `SpeedError` with typed codes; `socialCardOr(defaultUrl, promise)` never throws and falls back to the app's own card. `@connectrpc/connect`, `@connectrpc/connect-web` and `@bufbuild/protobuf` are new optional peer dependencies, needed only by this module. About 35 kB gzipped with them bundled, held by `check:size`. + ## 0.9.0-beta.2 A beta, published under npm's `next` tag; `latest` stays 0.8.1. diff --git a/README.md b/README.md index 758e0fe..8132ff8 100644 --- a/README.md +++ b/README.md @@ -529,6 +529,26 @@ function AccountButton() { - A menu, popover or tooltip works inside a `Dialog`: it draws above it, and Escape closes it before the dialog. - The page's global stylesheet starts with `@layer ui-sdk;`. Under a Content-Security-Policy, pages with a menu, popover or tooltip need `style-src-attr 'unsafe-inline'` and a ``: UI SDK positions popups with inline styles. The core components, dialogs and drawers included, need neither. +### `@jgb-solutions/kit/speed`: the clients for Speed (server-side) + +Typed clients for Speed, the service that does heavy work (drawing images) for an app's server, one per feature, over gRPC-Web on `fetch` (Connect-ES 2, protobuf-es 2): Cloudflare Workers, Bun and Node. Needs `@connectrpc/connect`, `@connectrpc/connect-web` and `@bufbuild/protobuf` (optional peers). The first feature is social cards, the share images for pages without one of their own: + +```ts +import { createSocialCardsClient, socialCardOr } from '@jgb-solutions/kit/speed' + +const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) // timeoutMs: 1500 by default +const image = await socialCardOr( + 'https://example.com/og.png', + cards.getCard({ locale: 'en', page: { title: 'Animals', emoji: ['🐶', '🐱'] } }), +) +``` + +- `getCard` returns `{ url, width, height, contentType, created, key }`. The same input always gives the same URL, so cache it (KV, the Cache API or SQLite); prerendered pages ask while they are built. +- One call, no retries, a 1.5 s deadline. A failure throws a `SpeedError` with a `code` (`timeout`, `unauthenticated`, `forbidden`, `invalid_input`, `rate_limited`, `unavailable`, `bad_response`, `failed`); `socialCardOr` never throws and returns the app's default card instead, so a page never fails or hangs because of Speed. +- `SPEED_TOKEN` is the app's key: server-side only. Mobile apps never call Speed; they ask their site, through its oRPC procedures. + +More in [docs/speed.md](docs/speed.md): Workers and Bun, the fallback, caching, updating the API. + ## What goes in, and what never goes in **In:** generic plumbing that several apps need in the same shape, written once and tested: checking a signed token, parsing a header, a retry or rate-limit helper, a typed client for a public protocol. Every module: diff --git a/buf.gen.yaml b/buf.gen.yaml new file mode 100644 index 0000000..56aa1a7 --- /dev/null +++ b/buf.gen.yaml @@ -0,0 +1,11 @@ +# `bun run generate`: protoc-gen-es (protobuf-es 2) writes the messages and the service +# descriptor that Connect-ES 2 reads; no other plugin is needed since v2. +version: v2 +inputs: + - directory: proto +plugins: + - local: protoc-gen-es + out: src/speed/gen + opt: + - target=ts + - import_extension=js diff --git a/buf.yaml b/buf.yaml new file mode 100644 index 0000000..1779606 --- /dev/null +++ b/buf.yaml @@ -0,0 +1,8 @@ +# The Speed service's API, copied from its own repository (see proto/README.md). Lint only: +# breaking changes are decided there, not here. +version: v2 +modules: + - path: proto +lint: + use: + - STANDARD diff --git a/bun.lock b/bun.lock index f2f58a5..4971451 100644 --- a/bun.lock +++ b/bun.lock @@ -10,6 +10,11 @@ "devDependencies": { "@axe-core/playwright": "4.14.1", "@better-auth/passkey": "1.7.29", + "@bufbuild/buf": "1.75.0", + "@bufbuild/protobuf": "2.17.0", + "@bufbuild/protoc-gen-es": "2.17.0", + "@connectrpc/connect": "2.3.0", + "@connectrpc/connect-web": "2.3.0", "@orpc/server": "2.0.0-beta.53", "@playwright/test": "1.65.1", "@simplewebauthn/browser": "13.3.0", @@ -30,6 +35,8 @@ "peerDependencies": { "@better-auth/passkey": ">=1.7.22 <2", "@orpc/server": ">=2.0.0-beta.52 <3", + "@ui-sdk/core": "0.1.0-beta.23", + "@ui-sdk/react": "0.1.0-beta.23", "better-auth": ">=1.7.22 <2", "react": ">=19 <20", "react-dom": ">=19 <20", @@ -39,6 +46,8 @@ "optionalPeers": [ "@better-auth/passkey", "@orpc/server", + "@ui-sdk/core", + "@ui-sdk/react", "better-auth", "react", "react-dom", @@ -104,6 +113,32 @@ "@better-fetch/fetch": ["@better-fetch/fetch@1.3.3", "", {}, "sha512-U6SlDt/GUWtK2JAxS/NhdoYTEim+EL1G5byz2TUj83KjLZBUpYzb5SmX0aXaCnbGkAjFKnV/o/0+cyXMbEcqqg=="], + "@bufbuild/buf": ["@bufbuild/buf@1.75.0", "", { "optionalDependencies": { "@bufbuild/buf-darwin-arm64": "1.75.0", "@bufbuild/buf-darwin-x64": "1.75.0", "@bufbuild/buf-linux-aarch64": "1.75.0", "@bufbuild/buf-linux-armv7": "1.75.0", "@bufbuild/buf-linux-x64": "1.75.0", "@bufbuild/buf-win32-arm64": "1.75.0", "@bufbuild/buf-win32-x64": "1.75.0" }, "hasInstallScript": true, "bin": { "buf": "bin/buf", "protoc-gen-buf-lint": "bin/protoc-gen-buf-lint", "protoc-gen-buf-breaking": "bin/protoc-gen-buf-breaking" } }, "sha512-uMuBCULLDax9/3d5Lo9mea38vuPDv4mrRVE4XfSq3qPcD5UUxlg0RJ9hm84lYCzI3A3lIvLeChxrw9c1RUiD2w=="], + + "@bufbuild/buf-darwin-arm64": ["@bufbuild/buf-darwin-arm64@1.75.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QiQYSmtVUcKy9DK/d+zJ3+D4iUQmmiDQ3i8/yBr8cf7Nr28lqKMAIKznJE/uGRsjr90fHaUQO+Xsedec0ArN5g=="], + + "@bufbuild/buf-darwin-x64": ["@bufbuild/buf-darwin-x64@1.75.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U2W+MRE9jJ7Am7x02ZWt87U5lfPrjKMdB1aZDslsuyOHo+fEUvZolupmhoW30v6syNAWBOfkoi0k5TLc2FNGqQ=="], + + "@bufbuild/buf-linux-aarch64": ["@bufbuild/buf-linux-aarch64@1.75.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-eX+XyokzJDqsNIFo8b1O3DBvbnksOozPJX4QVsNn61JqSUtWspyTNeYqwg8lRDancML+bDqZEDFPABjAsVCQGQ=="], + + "@bufbuild/buf-linux-armv7": ["@bufbuild/buf-linux-armv7@1.75.0", "", { "os": "linux", "cpu": "arm" }, "sha512-2RVhmr3vJ145DazYTk9dWAzeQPtcJ0SiSzY02v1Su/JIfgzhv9lgOm+y3nGuLjyZFF8UfTtmuHfHso5zDBgsCQ=="], + + "@bufbuild/buf-linux-x64": ["@bufbuild/buf-linux-x64@1.75.0", "", { "os": "linux", "cpu": "x64" }, "sha512-YGGJAx0lpMCE7aMWjNOJcfoEaG/e+iYHnTC4SZ0P5eS4IffMryA9Z4/bb1m1wNXAEJ8ATFMEZOAk/5x9VE47ig=="], + + "@bufbuild/buf-win32-arm64": ["@bufbuild/buf-win32-arm64@1.75.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-iRge6Ntta41gt0i7P8/EZFDWe3uLNnCEN86r1tKTWctumWxPET3UJcSzzYPyL4gxvzu1/1VTu+AB3+MYAqHy6Q=="], + + "@bufbuild/buf-win32-x64": ["@bufbuild/buf-win32-x64@1.75.0", "", { "os": "win32", "cpu": "x64" }, "sha512-/BgLt3VWndocuG4lbMdlBc1i41I+Bap4zm8R1Cnmov6DtoAQp4dy/leRrvT4aDArIUQ1o7W/Y92xTRITedU4ww=="], + + "@bufbuild/protobuf": ["@bufbuild/protobuf@2.17.0", "", {}, "sha512-hcPkSz6D7MiTU/5VBBhK+kxaYDoOdQ6yJRFJ3kS8Nydp+VZXfg1vrpABKPNod8bXMufsVCmiUJVIKFzCzta4uw=="], + + "@bufbuild/protoc-gen-es": ["@bufbuild/protoc-gen-es@2.17.0", "", { "dependencies": { "@bufbuild/protobuf": "2.17.0", "@bufbuild/protoplugin": "2.17.0" }, "bin": { "protoc-gen-es": "bin/protoc-gen-es" } }, "sha512-Uk8Hx145z76lDOEPhWChy53jtKITUnqG0vASuOiRybbZbBbx4oho9JDqt8QZsHemeTCNl6q4yy4Qpc2iV5outQ=="], + + "@bufbuild/protoplugin": ["@bufbuild/protoplugin@2.17.0", "", { "dependencies": { "@bufbuild/protobuf": "2.17.0", "@typescript/vfs": "^1.6.2", "typescript": "5.4.5" } }, "sha512-4ExU8AGygKkwIx3U8D5kyBOn9rcCM1qnj4wCP95RbP1CRe73QvVGHQ/lOp6IQiyvQMh9BGrYGht+ZDa8gwC2fg=="], + + "@connectrpc/connect": ["@connectrpc/connect@2.3.0", "", { "peerDependencies": { "@bufbuild/protobuf": "^2.7.0" } }, "sha512-rjAn8L9KbAZrkwiB8m1qzDsLs74hkYmwwM2iSWuxTPVOTRm/EZw31smKbQqPU50AXqJC5eKKpEnA6Uf/swQOgQ=="], + + "@connectrpc/connect-web": ["@connectrpc/connect-web@2.3.0", "", { "peerDependencies": { "@bufbuild/protobuf": "^2.7.0", "@connectrpc/connect": "2.3.0" } }, "sha512-JPXOiWaVsj+ZwaXOQjwvhc0ORnkl0a1w36Qyl3j1WTuak6/VYyuWGl1Aq8I60gQfQRjsjLLFGr64tO0sjwstcg=="], + "@hexagon/base64": ["@hexagon/base64@1.1.28", "", {}, "sha512-lhqDEAvWixy3bZ+UOYbPwUbBkwBq5C1LAJ/xPC8Oi+lL54oyakv/npbA0aU2hgCsx/1NUd4IBvV03+aUBWxerw=="], "@isaacs/ttlcache": ["@isaacs/ttlcache@1.4.1", "", {}, "sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA=="], @@ -224,6 +259,8 @@ "@types/yargs-parser": ["@types/yargs-parser@21.0.3", "", {}, "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ=="], + "@typescript/vfs": ["@typescript/vfs@1.6.6", "", { "dependencies": { "debug": "^4.4.3" }, "peerDependencies": { "typescript": "*" } }, "sha512-gXw0+tpchiQUjTcbnNIPnyLFIhbwJ7M1VaxLQ1vXhjQxtTBK3sdDLY1ih0jxCu1I5K3V0dDxq8CkVZtIMspC3A=="], + "@ui-sdk/core": ["@ui-sdk/core@0.1.0-beta.23", "", {}, "sha512-lf+hlu/5gijnjXsPL/VtTPTSzzoL18lSt4WJ9jfUg7xdU3QN4WH/AjXs/z6Vdp6+Ctg2gqpliAqidlJkYg8omg=="], "@ui-sdk/react": ["@ui-sdk/react@0.1.0-beta.23", "", { "peerDependencies": { "@types/react": ">=19.2.10", "@ui-sdk/core": "^0.1.0-beta.23", "react": ">=19", "react-dom": ">=19" }, "optionalPeers": ["@types/react"] }, "sha512-3ahRPFjaN5TgVV/lucbZ8mZ8G/vqmaEVPFS2EGAY0u5SsvvhW9BMTr5Mx5iiRcOvF5e/qd1WNmnj7wQs2o1ekQ=="], @@ -630,6 +667,8 @@ "@babel/helper-compilation-targets/semver": ["semver@6.3.2", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ=="], + "@bufbuild/protoplugin/typescript": ["typescript@5.4.5", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ=="], + "chalk/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], "chalk/supports-color": ["supports-color@7.2.0", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw=="], diff --git a/docs/speed.md b/docs/speed.md new file mode 100644 index 0000000..37707b4 --- /dev/null +++ b/docs/speed.md @@ -0,0 +1,138 @@ +# kit/speed: the clients for Speed + +Speed is a separate service that does work an app's server shouldn't do on each request, such as drawing +images. `@jgb-solutions/kit/speed` holds one typed client per feature. The first feature is **social cards**: +the share images (og:image, twitter:image, Pinterest pins, stories) for pages without an image of their own. + +The clients speak gRPC-Web over `fetch`, through [Connect-ES](https://connectrpc.com/docs/web/getting-started) +2 and messages generated by [protobuf-es](https://github.com/bufbuild/protobuf-es) 2, so the same code runs +on Cloudflare Workers, Bun and Node. Install the three optional peers next to the kit: + +```sh +bun add @connectrpc/connect @connectrpc/connect-web @bufbuild/protobuf +``` + +## Settings + +| Variable | What | +| ------------- | --------------------------------------------------------------------------------------- | +| `SPEED_URL` | Speed's base address, `https://…` (plain `http://` is accepted on localhost only). | +| `SPEED_TOKEN` | The app's key for Speed, sent as `authorization: Bearer …`. A secret, server-side only. | + +The token says which app is calling; Speed keeps each app's colours, logo and fonts, so a request carries +only the text. Keep the token in a Worker secret (`wrangler secret put SPEED_TOKEN`) or the server's +environment, never in code or in anything sent to a browser or a phone. + +## Social cards + +```ts +import { createSocialCardsClient, socialCardOr } from '@jgb-solutions/kit/speed' + +const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) + +const card = await cards.getCard({ + locale: 'fr', // en, fr, es or ht: the text is already in this language + format: 'link', // link 1200×630 (the default), square 1080×1080, portrait 1000×1500, story 1080×1920 + emoji: { emoji: '🐶', title: 'Chien', subtitle: 'Un ami fidèle', label: 'Animaux' }, + // or: page: { title: 'Animaux', subtitle: '…', emoji: ['🐶', '🐱'] } +}) +// { url: 'https://…/….png', width: 1200, height: 630, contentType: 'image/png', created: true, key: '…' } +``` + +- **Same input, same URL.** Speed draws a card once and stores it; asking again returns the stored URL. +- **A short deadline, no retries.** A call gives up after 1500 ms (`timeoutMs` changes it) and is never + retried, because it sits on a page's path. Pass `{ signal }` as `getCard`'s second argument to stop it sooner. +- **Typed errors.** A failed call throws a `SpeedError` whose `code` is `timeout`, `unauthenticated`, + `forbidden`, `invalid_input`, `rate_limited`, `unavailable`, `bad_response` or `failed`. Its message never + holds the token. +- **Checked settings.** `createSocialCardsClient` refuses an address that isn't HTTPS (or HTTP on + localhost), or that carries a user name, password, query or fragment, and a token that is empty or holds + spaces or control characters. An answer whose card address isn't HTTPS is refused as `bad_response`. + +### The fallback: a page never fails because of Speed + +`socialCardOr(defaultUrl, promise, onError?)` returns the card's URL, or the app's own default card when +the call fails or times out. It never throws. `onError` receives the `SpeedError`: log its `code`. + +```ts +const image = await socialCardOr('https://example.com/og.png', cards.getCard(input), (error) => console.warn('social card', error.code)) +``` + +The fallback is always a `link`-shaped card, so set `og:image:width` and `og:image:height` from the card +when you have one, and from your default otherwise. + +### Cache the URL + +The card's URL never changes for the same input, so ask Speed once per page and language, and keep the +answer. Key it by what the card shows (the input's fields, or a hash of them), not by the request: + +- **Cloudflare Workers:** KV (`env.CARDS.get(key)`, then `put(key, url)` after a miss), or the Cache API for + the page itself. +- **Bun on a server:** a small SQLite table (`card_key TEXT PRIMARY KEY, url TEXT`). +- **Both:** cache only real cards. Don't store the fallback, so the next visit tries Speed again. + +```ts +import { SpeedError, type GetCardInput } from '@jgb-solutions/kit/speed' + +async function cardFor(env: Env, input: GetCardInput): Promise { + // A hash keeps the key short (KV keys stop at 512 bytes) whatever the text. + const what = new TextEncoder().encode(JSON.stringify([input.locale, input.format ?? 'link', input.emoji ?? input.page])) + const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', what)) + const key = `card:${Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join('')}` + const cached = await env.CARDS.get(key) + if (cached) return cached + try { + const card = await cards.getCard(input) + await env.CARDS.put(key, card.url) + return card.url + } catch (error) { + console.warn('social card', error instanceof SpeedError ? error.code : 'failed') + return 'https://example.com/og.png' + } +} +``` + +### Prerendered pages + +A page that is prerendered asks for its card while it is built: the build runs with `SPEED_URL` and +`SPEED_TOKEN` in its environment and writes the URL into the page's tags. With the fallback, a build never +fails because Speed is down; the next build picks the card up. + +### Mobile apps + +A mobile app never calls Speed and never holds `SPEED_TOKEN`. When it needs a card (to share a page, say), +it asks its own site, through the site's oRPC procedures, and the site calls Speed. + +## On a Worker + +```ts +import { createSocialCardsClient, socialCardOr } from '@jgb-solutions/kit/speed' + +export default { + async fetch(request, env: { SPEED_URL: string; SPEED_TOKEN: string }) { + const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) + const image = await socialCardOr('https://example.com/og.png', cards.getCard({ locale: 'en', page: { title: 'Home' } })) + // Put it in the page's tags through the app's own head helper, which escapes it. + return Response.json({ image }) + }, +} satisfies ExportedHandler<{ SPEED_URL: string; SPEED_TOKEN: string }> +``` + +The client is about 35 kB gzipped (Connect-ES and protobuf-es included), counted in the Worker's size. +Create it once per request, or once per isolate from `env`. + +## On Bun + +```ts +import { createSocialCardsClient } from '@jgb-solutions/kit/speed' + +const cards = createSocialCardsClient({ url: Bun.env.SPEED_URL!, token: Bun.env.SPEED_TOKEN! }) +``` + +Create it once at start-up and share it. + +## Updating the API + +The `.proto` files in `proto/` are copies of Speed's own (see `proto/README.md`). After copying a new +version, run `bun run generate` (buf, then protoc-gen-es) and commit `src/speed/gen/` with it. CI checks +that the two match. diff --git a/package.json b/package.json index f7876fd..a3d4864 100644 --- a/package.json +++ b/package.json @@ -26,7 +26,10 @@ "design-system", "accessible", "sign-in", - "react-native" + "react-native", + "grpc-web", + "connect-rpc", + "social-cards" ], "type": "module", "sideEffects": [ @@ -119,6 +122,10 @@ "import": "./dist/ui/overlays.js" }, "./ui/overlays.css": "./dist/ui/overlays.css", + "./speed": { + "types": "./dist/speed.d.ts", + "import": "./dist/speed.js" + }, "./package.json": "./package.json" }, "engines": { @@ -148,7 +155,8 @@ "screenshots:account": "bun --bun playwright test e2e/account-screenshots.spec.ts", "screenshots:ui": "bun --bun playwright test e2e/ui-screenshots.spec.ts", "screenshots:overlays": "bun --bun playwright test e2e/overlays-screenshots.spec.ts", - "screenshots:showcase": "bun --bun playwright test e2e/showcase-screenshots.spec.ts" + "screenshots:showcase": "bun --bun playwright test e2e/showcase-screenshots.spec.ts", + "generate": "buf generate && bun fmt src/speed/gen" }, "dependencies": { "jose": "6.2.19" @@ -162,7 +170,10 @@ "react-native": ">=0.79 <1", "react-native-svg": ">=15 <16", "@ui-sdk/core": "0.1.0-beta.23", - "@ui-sdk/react": "0.1.0-beta.23" + "@ui-sdk/react": "0.1.0-beta.23", + "@bufbuild/protobuf": ">=2.17.0 <3", + "@connectrpc/connect": ">=2.3.0 <3", + "@connectrpc/connect-web": ">=2.3.0 <3" }, "peerDependenciesMeta": { "better-auth": { @@ -191,11 +202,25 @@ }, "@ui-sdk/react": { "optional": true + }, + "@bufbuild/protobuf": { + "optional": true + }, + "@connectrpc/connect": { + "optional": true + }, + "@connectrpc/connect-web": { + "optional": true } }, "devDependencies": { "@axe-core/playwright": "4.14.1", "@better-auth/passkey": "1.7.29", + "@bufbuild/buf": "1.75.0", + "@bufbuild/protobuf": "2.17.0", + "@bufbuild/protoc-gen-es": "2.17.0", + "@connectrpc/connect": "2.3.0", + "@connectrpc/connect-web": "2.3.0", "@orpc/server": "2.0.0-beta.53", "@playwright/test": "1.65.1", "@simplewebauthn/browser": "13.3.0", diff --git a/proto/README.md b/proto/README.md new file mode 100644 index 0000000..78a0c8a --- /dev/null +++ b/proto/README.md @@ -0,0 +1,6 @@ +# Speed's API, copied + +`speed/socialcards/v1/social_cards.proto` is a copy of the Speed service's own definition (package +`speed.socialcards.v1`), taken unchanged from the service's repository at commit `10648f9`. The service owns +it: changes are made there first, then copied here, and `bun run generate` rewrites `src/speed/gen/` from it +(buf and protobuf-es's `protoc-gen-es`). CI fails if the generated code no longer matches this file. diff --git a/proto/speed/socialcards/v1/social_cards.proto b/proto/speed/socialcards/v1/social_cards.proto new file mode 100644 index 0000000..85910f2 --- /dev/null +++ b/proto/speed/socialcards/v1/social_cards.proto @@ -0,0 +1,90 @@ +syntax = "proto3"; + +package speed.socialcards.v1; + +// Social cards: share images (og:image, twitter:image, Pinterest pins, stories) +// for pages that have no real image of their own. +// +// The calling app is not part of the request. The bearer token in the +// `authorization` header says which app is calling, and the app picks the look: +// its colours, logo and fonts live in Speed, never in the request. Every text +// field arrives already translated into `locale`. +// +// Cards are stored, not returned. The request's fields fully determine the +// card's storage key, so the same request always gives the same URL. When the +// card already exists Speed returns its URL without rendering; otherwise it +// renders the card, stores it, then returns the URL. +service SocialCardService { + // Returns the URL of the card for these parameters, making it first if needed. + rpc GetCard(GetCardRequest) returns (GetCardResponse); +} + +enum Locale { + LOCALE_UNSPECIFIED = 0; // treated as LOCALE_EN + LOCALE_EN = 1; + LOCALE_FR = 2; + LOCALE_ES = 3; + LOCALE_HT = 4; +} + +// The shape each network wants. Every card is a PNG: all networks accept PNG, +// while some link scrapers still refuse WebP. +enum CardFormat { + CARD_FORMAT_UNSPECIFIED = 0; // treated as CARD_FORMAT_LINK + // 1200x630: og:image and twitter:image (link previews everywhere). + CARD_FORMAT_LINK = 1; + // 1080x1080: square posts. + CARD_FORMAT_SQUARE = 2; + // 1000x1500: Pinterest pins. + CARD_FORMAT_PORTRAIT = 3; + // 1080x1920: stories and reels. + CARD_FORMAT_STORY = 4; +} + +message GetCardRequest { + Locale locale = 1; + CardFormat format = 2; + + // What the card shows. Typed templates only, never HTML or free-form markup. + oneof template { + EmojiCard emoji = 10; + PageCard page = 11; + } +} + +// A page about one emoji: the emoji drawn large beside its name. +message EmojiCard { + // One emoji, e.g. "😀", a flag or a ZWJ sequence. At most 16 code points, + // and only emoji Speed has artwork for. + string emoji = 1; + // Its name. 1 to 80 characters. + string title = 2; + // A short line under the name. Up to 160 characters. + string subtitle = 3; + // A small line above the name, e.g. its category. Up to 40 characters. + string label = 4; +} + +// Any other page (home, category, list): a title, a line and up to 4 emoji. +message PageCard { + // 1 to 80 characters. + string title = 1; + // Up to 160 characters. + string subtitle = 2; + // 0 to 4 emoji, each as in EmojiCard.emoji. + repeated string emoji = 3; +} + +message GetCardResponse { + // Public HTTPS URL of the stored card, on the bucket's own domain. + string url = 1; + // Pixel size of the card, for og:image:width and og:image:height. + uint32 width = 2; + uint32 height = 3; + // Always "image/png" for now. + string content_type = 4; + // True when this call rendered and stored the card; false when it already existed. + bool created = 5; + // The card's storage key: /socialcards///.png + string key = 6; +} diff --git a/scripts/check-package.ts b/scripts/check-package.ts index a748514..96ee85d 100644 --- a/scripts/check-package.ts +++ b/scripts/check-package.ts @@ -44,6 +44,8 @@ const IMPORTS: Record = { './ui': ['react'], // The one module that carries a behaviour library: an app loads it after first paint. './ui/overlays': ['react', '@ui-sdk/react'], + // Speed's clients: Connect-ES over gRPC-Web, and the messages protobuf-es generates. + './speed': ['@connectrpc/connect', '@connectrpc/connect-web', '@bufbuild/protobuf'], } const OPTIONAL_PEERS = [ 'better-auth', @@ -55,6 +57,9 @@ const OPTIONAL_PEERS = [ 'react-native-svg', '@ui-sdk/core', '@ui-sdk/react', + '@bufbuild/protobuf', + '@connectrpc/connect', + '@connectrpc/connect-web', ] /** Modules that only load inside their platform: React Native's own code doesn't run in Bun, so they're checked by their imports alone. */ const NOT_LOADED_HERE = ['./account/native'] diff --git a/scripts/check-size.ts b/scripts/check-size.ts index 93fef73..0e52e76 100644 --- a/scripts/check-size.ts +++ b/scripts/check-size.ts @@ -83,6 +83,14 @@ await cost( 'allowed', ) +// kit/speed runs on an app's server (a Worker counts its script size), with Connect-ES and protobuf-es bundled in. +const speed = JSON.stringify(resolve('dist/speed.js')) +await cost( + 'kit/speed: the social cards client', + `import { createSocialCardsClient, socialCardOr } from ${speed}; globalThis.__keep = [createSocialCardsClient, socialCardOr]`, + 40 * 1024, +) + const width = Math.max(...rows.map((row) => row.what.length)) console.log(`${'gzipped'.padEnd(width)} ${'size'.padStart(9)} ${'budget'.padStart(9)}`) for (const row of rows) { diff --git a/src/speed.test.ts b/src/speed.test.ts new file mode 100644 index 0000000..af7556c --- /dev/null +++ b/src/speed.test.ts @@ -0,0 +1,234 @@ +import { describe, expect, test } from 'bun:test' +import { create, fromBinary, toBinary } from '@bufbuild/protobuf' +import { createSocialCardsClient, socialCardOr, SpeedError, type SocialCard, type SpeedErrorCode } from './speed' +import { + CardFormat, + GetCardRequestSchema, + GetCardResponseSchema, + Locale, + type GetCardRequest, +} from './speed/gen/speed/socialcards/v1/social_cards_pb.js' + +const URL_BASE = 'https://speed.example.com' +const TOKEN = 'test-token-not-a-secret' + +/** One gRPC-Web frame: a flag byte, the length (4 bytes, big-endian), then the bytes. */ +function frame(flag: number, bytes: Uint8Array): Uint8Array { + const out = new Uint8Array(5 + bytes.length) + out[0] = flag + new DataView(out.buffer).setUint32(1, bytes.length) + out.set(bytes, 5) + return out +} +const trailer = (status: number, message = '') => + frame(0x80, new TextEncoder().encode(`grpc-status: ${status}\r\ngrpc-message: ${encodeURIComponent(message)}\r\n`)) +const GRPC_WEB = { 'content-type': 'application/grpc-web+proto' } + +type Seen = { url: string; headers: Headers; redirect: RequestRedirect | undefined; request: GetCardRequest } + +/** A fake fetch that answers as Speed would, and records what it was sent. */ +function fakeSpeed(answer: (request: GetCardRequest) => Response | Promise) { + const seen: Seen[] = [] + const fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const body = new Uint8Array(init?.body as ArrayBuffer) + const request = fromBinary(GetCardRequestSchema, body.subarray(5)) + seen.push({ url: String(input), headers: new Headers(init?.headers), redirect: init?.redirect, request }) + return answer(request) + }) as typeof globalThis.fetch + return { fetch, seen } +} +const card = (fields: Partial = {}) => + new Response( + new Blob([ + frame( + 0, + toBinary( + GetCardResponseSchema, + create(GetCardResponseSchema, { + url: 'https://cards.example.com/app/socialcards/link/en/abc.png', + width: 1200, + height: 630, + contentType: 'image/png', + created: true, + key: 'app/socialcards/link/en/abc.png', + ...fields, + }), + ), + ), + trailer(0), + ]), + { headers: GRPC_WEB }, + ) +/** A trailers-only error, as gRPC servers send one. */ +const failure = (status: number, message: string) => + new Response(null, { headers: { ...GRPC_WEB, 'grpc-status': String(status), 'grpc-message': encodeURIComponent(message) } }) + +describe('createSocialCardsClient', () => { + test('sends the request to the GetCard method, with the Bearer token', async () => { + const speed = fakeSpeed(() => card()) + const cards = createSocialCardsClient({ url: `${URL_BASE}/`, token: TOKEN, fetch: speed.fetch }) + await cards.getCard({ locale: 'fr', format: 'story', emoji: { emoji: '😀', title: 'Visage souriant', label: 'Smileys' } }) + const [call] = speed.seen + expect(call?.url).toBe(`${URL_BASE}/speed.socialcards.v1.SocialCardService/GetCard`) + expect(call?.headers.get('authorization')).toBe(`Bearer ${TOKEN}`) + expect(call?.headers.get('grpc-timeout')).toBe('1500m') + expect(call?.request.locale).toBe(Locale.FR) + expect(call?.request.format).toBe(CardFormat.STORY) + expect(call?.request.template.case).toBe('emoji') + expect(call?.request.template.value).toMatchObject({ emoji: '😀', title: 'Visage souriant', subtitle: '', label: 'Smileys' }) + }) + + test('a page card, in the link shape when no format is given', async () => { + const speed = fakeSpeed(() => card()) + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: speed.fetch, timeoutMs: 800 }) + await cards.getCard({ locale: 'ht', page: { title: 'Bèt', emoji: ['🐶', '🐱'] } }) + const [call] = speed.seen + expect(call?.headers.get('grpc-timeout')).toBe('800m') + expect(call?.request.format).toBe(CardFormat.LINK) + expect(call?.request.locale).toBe(Locale.HT) + expect(call?.request.template.case).toBe('page') + expect(call?.request.template.value).toMatchObject({ title: 'Bèt', subtitle: '', emoji: ['🐶', '🐱'] }) + }) + + test('maps the answer', async () => { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card({ created: false })).fetch }) + expect(await cards.getCard({ locale: 'en', page: { title: 'Home' } })).toEqual({ + url: 'https://cards.example.com/app/socialcards/link/en/abc.png', + width: 1200, + height: 630, + contentType: 'image/png', + created: false, + key: 'app/socialcards/link/en/abc.png', + }) + }) + + test('an answer without an HTTPS address or a size is refused', async () => { + for (const fields of [{ url: 'javascript:alert(1)' }, { url: 'http://cards.example.com/a.png' }, { url: '' }, { width: 0 }]) { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card(fields)).fetch }) + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect(error).toBeInstanceOf(SpeedError) + expect((error as SpeedError).code).toBe('bad_response') + } + }) + + test('maps Speed errors to codes, and never puts the token in the message', async () => { + const cases: [number, SpeedErrorCode][] = [ + [16, 'unauthenticated'], + [7, 'forbidden'], + [3, 'invalid_input'], + [8, 'rate_limited'], + [14, 'unavailable'], + [13, 'failed'], + ] + for (const [status, code] of cases) { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(status, 'no')).fetch }) + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect(error).toBeInstanceOf(SpeedError) + expect((error as SpeedError).code).toBe(code) + expect((error as SpeedError).message).not.toContain(TOKEN) + } + }) + + test('an HTTP error or a network failure is a SpeedError too', async () => { + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => new Response('', { status: 503 })).fetch }) + expect(((await down.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe( + 'unavailable', + ) + const offline = createSocialCardsClient({ + url: URL_BASE, + token: TOKEN, + fetch: (() => Promise.reject(new TypeError('fetch failed'))) as unknown as typeof globalThis.fetch, + }) + expect(await offline.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)).toBeInstanceOf(SpeedError) + }) + + test('never follows a redirect, so the token stays with Speed', async () => { + const speed = fakeSpeed(() => new Response(null, { status: 302, headers: { location: 'https://elsewhere.example.com/' } })) + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: speed.fetch }) + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect((error as SpeedError).code).toBe('unavailable') + // 'manual', not Connect's 'error': Workers without the fetch_redirect_error flag refuse 'error' outright. + expect(speed.seen.map((call) => [call.url, call.redirect])).toEqual([ + [`${URL_BASE}/speed.socialcards.v1.SocialCardService/GetCard`, 'manual'], + ]) + }) + + test('gives up at the deadline, once (no retry)', async () => { + let calls = 0 + const hang = ((_input: RequestInfo | URL, init?: RequestInit) => { + calls++ + return new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(init.signal?.reason))) + }) as typeof globalThis.fetch + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang, timeoutMs: 30 }) + const started = performance.now() + const error = await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e) + expect((error as SpeedError).code).toBe('timeout') + expect(performance.now() - started).toBeLessThan(1000) + expect(calls).toBe(1) + }) + + test('refuses unsafe settings before any call', () => { + const ok = { url: URL_BASE, token: TOKEN } + for (const url of [ + 'http://speed.example.com', + 'ftp://speed.example.com', + 'not a url', + 'https://user:pw@speed.example.com', + 'https://speed.example.com/?a=1', + 'https://speed.example.com/#x', + ]) + expect(() => createSocialCardsClient({ ...ok, url })).toThrow(SpeedError) + for (const token of ['', ' ', 'a b', 'a\r\nx-evil: 1']) expect(() => createSocialCardsClient({ ...ok, token })).toThrow(SpeedError) + expect(() => createSocialCardsClient({ ...ok, timeoutMs: 0 })).toThrow(SpeedError) + // Plain HTTP is allowed on the machine itself, for development. + expect(() => createSocialCardsClient({ ...ok, url: 'http://localhost:8080' })).not.toThrow() + expect(() => createSocialCardsClient({ ...ok, url: 'http://127.0.0.1:8080' })).not.toThrow() + }) + + test('an unsafe setting never shows the token', () => { + try { + createSocialCardsClient({ url: 'http://speed.example.com', token: TOKEN }) + } catch (error) { + expect(String(error)).not.toContain(TOKEN) + } + }) +}) + +describe('socialCardOr', () => { + const input = { locale: 'en', page: { title: 'Home' } } as const + + test("returns the card's URL when Speed answers", async () => { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card()).fetch }) + expect(await socialCardOr('https://example.com/og.png', cards.getCard(input))).toBe( + 'https://cards.example.com/app/socialcards/link/en/abc.png', + ) + }) + + test('returns the default card on an error or a timeout, and reports why', async () => { + const seen: SpeedErrorCode[] = [] + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(14, 'down')).fetch }) + expect(await socialCardOr('https://example.com/og.png', down.getCard(input), (e) => seen.push(e.code))).toBe( + 'https://example.com/og.png', + ) + const hang = ((_: RequestInfo | URL, init?: RequestInit) => + new Promise((_, reject) => + init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)), + )) as typeof globalThis.fetch + const slow = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang, timeoutMs: 20 }) + expect(await socialCardOr('https://example.com/og.png', slow.getCard(input), (e) => seen.push(e.code))).toBe( + 'https://example.com/og.png', + ) + expect(seen).toEqual(['unavailable', 'timeout']) + }) + + test('never throws, even when the logger does or the input was refused', async () => { + expect( + await socialCardOr('/og.png', Promise.reject(new Error('boom')), () => { + throw new Error('logger down') + }), + ).toBe('/og.png') + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card()).fetch }) + // @ts-expect-error: a locale Speed doesn't have + expect(await socialCardOr('/og.png', cards.getCard({ locale: 'de', page: { title: 'Start' } }))).toBe('/og.png') + }) +}) diff --git a/src/speed.ts b/src/speed.ts new file mode 100644 index 0000000..fb2ef44 --- /dev/null +++ b/src/speed.ts @@ -0,0 +1,29 @@ +/** + * Speed: the clients for JGB Solutions' Speed service, one per feature, called from an app's server. + * + * Social cards: share images (og:image, twitter:image, pins, stories) for pages without an image of + * their own. Speed draws each card once, stores it and answers with its public URL; the same input + * always gives the same URL. A page never waits on Speed for long (a 1.5 s deadline, no retries), and + * `socialCardOr` falls back to the app's own default card when Speed is slow or down. + * + * import { createSocialCardsClient, socialCardOr } from '@jgb-solutions/kit/speed' + * const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) + * const image = await socialCardOr('https://example.com/og.png', cards.getCard({ locale: 'en', page: { title: 'Animals' } })) + * + * Needs @connectrpc/connect, @connectrpc/connect-web and @bufbuild/protobuf (optional peers). See docs/speed.md. + */ +export { + createSocialCardsClient, + socialCardOr, + SpeedError, + DEFAULT_TIMEOUT_MS, + type CardLocale, + type CardShape, + type EmojiCardInput, + type PageCardInput, + type GetCardInput, + type SocialCard, + type SocialCardsClient, + type SpeedClientOptions, + type SpeedErrorCode, +} from './speed/social-cards' diff --git a/src/speed/gen/speed/socialcards/v1/social_cards_pb.ts b/src/speed/gen/speed/socialcards/v1/social_cards_pb.ts new file mode 100644 index 0000000..b571c67 --- /dev/null +++ b/src/speed/gen/speed/socialcards/v1/social_cards_pb.ts @@ -0,0 +1,300 @@ +// @generated by protoc-gen-es v2.17.0 with parameter "target=ts,import_extension=js" +// @generated from file speed/socialcards/v1/social_cards.proto (package speed.socialcards.v1, syntax proto3) +/* eslint-disable */ + +import type { GenEnum, GenFile, GenMessage, GenService } from '@bufbuild/protobuf/codegenv2' +import { enumDesc, fileDesc, messageDesc, serviceDesc } from '@bufbuild/protobuf/codegenv2' +import type { Message } from '@bufbuild/protobuf' + +/** + * Describes the file speed/socialcards/v1/social_cards.proto. + */ +export const file_speed_socialcards_v1_social_cards: GenFile = + /*@__PURE__*/ + fileDesc( + 'CidzcGVlZC9zb2NpYWxjYXJkcy92MS9zb2NpYWxfY2FyZHMucHJvdG8SFHNwZWVkLnNvY2lhbGNhcmRzLnYxIt4BCg5HZXRDYXJkUmVxdWVzdBIsCgZsb2NhbGUYASABKA4yHC5zcGVlZC5zb2NpYWxjYXJkcy52MS5Mb2NhbGUSMAoGZm9ybWF0GAIgASgOMiAuc3BlZWQuc29jaWFsY2FyZHMudjEuQ2FyZEZvcm1hdBIwCgVlbW9qaRgKIAEoCzIfLnNwZWVkLnNvY2lhbGNhcmRzLnYxLkVtb2ppQ2FyZEgAEi4KBHBhZ2UYCyABKAsyHi5zcGVlZC5zb2NpYWxjYXJkcy52MS5QYWdlQ2FyZEgAQgoKCHRlbXBsYXRlIkoKCUVtb2ppQ2FyZBINCgVlbW9qaRgBIAEoCRINCgV0aXRsZRgCIAEoCRIQCghzdWJ0aXRsZRgDIAEoCRINCgVsYWJlbBgEIAEoCSI6CghQYWdlQ2FyZBINCgV0aXRsZRgBIAEoCRIQCghzdWJ0aXRsZRgCIAEoCRINCgVlbW9qaRgDIAMoCSJxCg9HZXRDYXJkUmVzcG9uc2USCwoDdXJsGAEgASgJEg0KBXdpZHRoGAIgASgNEg4KBmhlaWdodBgDIAEoDRIUCgxjb250ZW50X3R5cGUYBCABKAkSDwoHY3JlYXRlZBgFIAEoCBILCgNrZXkYBiABKAkqXAoGTG9jYWxlEhYKEkxPQ0FMRV9VTlNQRUNJRklFRBAAEg0KCUxPQ0FMRV9FThABEg0KCUxPQ0FMRV9GUhACEg0KCUxPQ0FMRV9FUxADEg0KCUxPQ0FMRV9IVBAEKogBCgpDYXJkRm9ybWF0EhsKF0NBUkRfRk9STUFUX1VOU1BFQ0lGSUVEEAASFAoQQ0FSRF9GT1JNQVRfTElOSxABEhYKEkNBUkRfRk9STUFUX1NRVUFSRRACEhgKFENBUkRfRk9STUFUX1BPUlRSQUlUEAMSFQoRQ0FSRF9GT1JNQVRfU1RPUlkQBDJrChFTb2NpYWxDYXJkU2VydmljZRJWCgdHZXRDYXJkEiQuc3BlZWQuc29jaWFsY2FyZHMudjEuR2V0Q2FyZFJlcXVlc3QaJS5zcGVlZC5zb2NpYWxjYXJkcy52MS5HZXRDYXJkUmVzcG9uc2ViBnByb3RvMw', + ) + +/** + * @generated from message speed.socialcards.v1.GetCardRequest + */ +export type GetCardRequest = Message<'speed.socialcards.v1.GetCardRequest'> & { + /** + * @generated from field: speed.socialcards.v1.Locale locale = 1; + */ + locale: Locale + + /** + * @generated from field: speed.socialcards.v1.CardFormat format = 2; + */ + format: CardFormat + + /** + * What the card shows. Typed templates only, never HTML or free-form markup. + * + * @generated from oneof speed.socialcards.v1.GetCardRequest.template + */ + template: + | { + /** + * @generated from field: speed.socialcards.v1.EmojiCard emoji = 10; + */ + value: EmojiCard + case: 'emoji' + } + | { + /** + * @generated from field: speed.socialcards.v1.PageCard page = 11; + */ + value: PageCard + case: 'page' + } + | { case: undefined; value?: undefined } +} + +/** + * Describes the message speed.socialcards.v1.GetCardRequest. + * Use `create(GetCardRequestSchema)` to create a new message. + */ +export const GetCardRequestSchema: GenMessage = /*@__PURE__*/ messageDesc(file_speed_socialcards_v1_social_cards, 0) + +/** + * A page about one emoji: the emoji drawn large beside its name. + * + * @generated from message speed.socialcards.v1.EmojiCard + */ +export type EmojiCard = Message<'speed.socialcards.v1.EmojiCard'> & { + /** + * One emoji, e.g. "😀", a flag or a ZWJ sequence. At most 16 code points, + * and only emoji Speed has artwork for. + * + * @generated from field: string emoji = 1; + */ + emoji: string + + /** + * Its name. 1 to 80 characters. + * + * @generated from field: string title = 2; + */ + title: string + + /** + * A short line under the name. Up to 160 characters. + * + * @generated from field: string subtitle = 3; + */ + subtitle: string + + /** + * A small line above the name, e.g. its category. Up to 40 characters. + * + * @generated from field: string label = 4; + */ + label: string +} + +/** + * Describes the message speed.socialcards.v1.EmojiCard. + * Use `create(EmojiCardSchema)` to create a new message. + */ +export const EmojiCardSchema: GenMessage = /*@__PURE__*/ messageDesc(file_speed_socialcards_v1_social_cards, 1) + +/** + * Any other page (home, category, list): a title, a line and up to 4 emoji. + * + * @generated from message speed.socialcards.v1.PageCard + */ +export type PageCard = Message<'speed.socialcards.v1.PageCard'> & { + /** + * 1 to 80 characters. + * + * @generated from field: string title = 1; + */ + title: string + + /** + * Up to 160 characters. + * + * @generated from field: string subtitle = 2; + */ + subtitle: string + + /** + * 0 to 4 emoji, each as in EmojiCard.emoji. + * + * @generated from field: repeated string emoji = 3; + */ + emoji: string[] +} + +/** + * Describes the message speed.socialcards.v1.PageCard. + * Use `create(PageCardSchema)` to create a new message. + */ +export const PageCardSchema: GenMessage = /*@__PURE__*/ messageDesc(file_speed_socialcards_v1_social_cards, 2) + +/** + * @generated from message speed.socialcards.v1.GetCardResponse + */ +export type GetCardResponse = Message<'speed.socialcards.v1.GetCardResponse'> & { + /** + * Public HTTPS URL of the stored card, on the bucket's own domain. + * + * @generated from field: string url = 1; + */ + url: string + + /** + * Pixel size of the card, for og:image:width and og:image:height. + * + * @generated from field: uint32 width = 2; + */ + width: number + + /** + * @generated from field: uint32 height = 3; + */ + height: number + + /** + * Always "image/png" for now. + * + * @generated from field: string content_type = 4; + */ + contentType: string + + /** + * True when this call rendered and stored the card; false when it already existed. + * + * @generated from field: bool created = 5; + */ + created: boolean + + /** + * The card's storage key: /socialcards///.png + * + * @generated from field: string key = 6; + */ + key: string +} + +/** + * Describes the message speed.socialcards.v1.GetCardResponse. + * Use `create(GetCardResponseSchema)` to create a new message. + */ +export const GetCardResponseSchema: GenMessage = /*@__PURE__*/ messageDesc(file_speed_socialcards_v1_social_cards, 3) + +/** + * @generated from enum speed.socialcards.v1.Locale + */ +export enum Locale { + /** + * treated as LOCALE_EN + * + * @generated from enum value: LOCALE_UNSPECIFIED = 0; + */ + UNSPECIFIED = 0, + + /** + * @generated from enum value: LOCALE_EN = 1; + */ + EN = 1, + + /** + * @generated from enum value: LOCALE_FR = 2; + */ + FR = 2, + + /** + * @generated from enum value: LOCALE_ES = 3; + */ + ES = 3, + + /** + * @generated from enum value: LOCALE_HT = 4; + */ + HT = 4, +} + +/** + * Describes the enum speed.socialcards.v1.Locale. + */ +export const LocaleSchema: GenEnum = /*@__PURE__*/ enumDesc(file_speed_socialcards_v1_social_cards, 0) + +/** + * The shape each network wants. Every card is a PNG: all networks accept PNG, + * while some link scrapers still refuse WebP. + * + * @generated from enum speed.socialcards.v1.CardFormat + */ +export enum CardFormat { + /** + * treated as CARD_FORMAT_LINK + * + * @generated from enum value: CARD_FORMAT_UNSPECIFIED = 0; + */ + UNSPECIFIED = 0, + + /** + * 1200x630: og:image and twitter:image (link previews everywhere). + * + * @generated from enum value: CARD_FORMAT_LINK = 1; + */ + LINK = 1, + + /** + * 1080x1080: square posts. + * + * @generated from enum value: CARD_FORMAT_SQUARE = 2; + */ + SQUARE = 2, + + /** + * 1000x1500: Pinterest pins. + * + * @generated from enum value: CARD_FORMAT_PORTRAIT = 3; + */ + PORTRAIT = 3, + + /** + * 1080x1920: stories and reels. + * + * @generated from enum value: CARD_FORMAT_STORY = 4; + */ + STORY = 4, +} + +/** + * Describes the enum speed.socialcards.v1.CardFormat. + */ +export const CardFormatSchema: GenEnum = /*@__PURE__*/ enumDesc(file_speed_socialcards_v1_social_cards, 1) + +/** + * Social cards: share images (og:image, twitter:image, Pinterest pins, stories) + * for pages that have no real image of their own. + * + * The calling app is not part of the request. The bearer token in the + * `authorization` header says which app is calling, and the app picks the look: + * its colours, logo and fonts live in Speed, never in the request. Every text + * field arrives already translated into `locale`. + * + * Cards are stored, not returned. The request's fields fully determine the + * card's storage key, so the same request always gives the same URL. When the + * card already exists Speed returns its URL without rendering; otherwise it + * renders the card, stores it, then returns the URL. + * + * @generated from service speed.socialcards.v1.SocialCardService + */ +export const SocialCardService: GenService<{ + /** + * Returns the URL of the card for these parameters, making it first if needed. + * + * @generated from rpc speed.socialcards.v1.SocialCardService.GetCard + */ + getCard: { + methodKind: 'unary' + input: typeof GetCardRequestSchema + output: typeof GetCardResponseSchema + } +}> = /*@__PURE__*/ serviceDesc(file_speed_socialcards_v1_social_cards, 0) diff --git a/src/speed/social-cards.ts b/src/speed/social-cards.ts new file mode 100644 index 0000000..41df7cc --- /dev/null +++ b/src/speed/social-cards.ts @@ -0,0 +1,254 @@ +import { Code, ConnectError, createClient, type Interceptor } from '@connectrpc/connect' +import { createGrpcWebTransport } from '@connectrpc/connect-web' +import { CardFormat, Locale, SocialCardService, type GetCardRequest } from './gen/speed/socialcards/v1/social_cards_pb.js' + +/** The languages a card can be drawn in. Its text arrives already translated into it. */ +export type CardLocale = 'en' | 'fr' | 'es' | 'ht' + +/** + * The shape each network wants, every one a PNG: `link` 1200×630 (og:image, twitter:image), `square` + * 1080×1080, `portrait` 1000×1500 (Pinterest pins), `story` 1080×1920 (stories and reels). + */ +export type CardShape = 'link' | 'square' | 'portrait' | 'story' + +/** A page about one emoji: the emoji drawn large beside its name. */ +export type EmojiCardInput = { + /** One emoji (a flag or a ZWJ sequence counts as one), at most 16 code points. */ + emoji: string + /** Its name, 1 to 80 characters. */ + title: string + /** A short line under the name, up to 160 characters. */ + subtitle?: string + /** A small line above the name (its category, say), up to 40 characters. */ + label?: string +} + +/** Any other page (home, category, list): a title, a line and up to 4 emoji. */ +export type PageCardInput = { + /** 1 to 80 characters. */ + title: string + /** Up to 160 characters. */ + subtitle?: string + /** 0 to 4 emoji. */ + emoji?: readonly string[] +} + +/** What to draw: one typed template, never HTML. The app's colours, logo and fonts live in Speed. */ +export type GetCardInput = { + locale: CardLocale + /** `link` when left out. */ + format?: CardShape +} & ({ emoji: EmojiCardInput; page?: never } | { page: PageCardInput; emoji?: never }) + +export type SocialCard = { + /** The stored card's public HTTPS address: the same input always gives the same one. */ + url: string + /** In pixels, for og:image:width and og:image:height. */ + width: number + height: number + /** `image/png` for now. */ + contentType: string + /** True when this call drew and stored the card, false when it already existed. */ + created: boolean + /** Where Speed stored it: `/socialcards///.png`. A good cache key's value. */ + key: string +} + +/** + * Why a call failed. `timeout`: no answer within the deadline. `unauthenticated` / `forbidden`: the + * token is wrong or isn't allowed this. `invalid_input`: Speed refused the input (too long, an emoji it + * has no artwork for). `rate_limited`, `unavailable`: try again later. `bad_response`: Speed answered + * with something that isn't a card. `failed`: anything else. + */ +export type SpeedErrorCode = + 'timeout' | 'unauthenticated' | 'forbidden' | 'invalid_input' | 'rate_limited' | 'unavailable' | 'bad_response' | 'failed' + +/** A Speed call that failed. The message never holds the token. */ +export class SpeedError extends Error { + override readonly name = 'SpeedError' + constructor( + readonly code: SpeedErrorCode, + message: string, + options?: { cause?: unknown }, + ) { + super(message, options) + } +} + +export type SpeedClientOptions = { + /** Speed's base address (`SPEED_URL`): `https://…`, or `http://` on localhost for development. */ + url: string + /** The app's key (`SPEED_TOKEN`), sent as `authorization: Bearer …`. A secret: keep it server-side. */ + token: string + /** How long a call may take before it gives up, in milliseconds. 1500 by default. No call is retried. */ + timeoutMs?: number + /** The fetch to call through. The runtime's own by default; tests pass a fake. */ + fetch?: typeof globalThis.fetch +} + +export type SocialCardsClient = { + /** The card for this input, drawn first if Speed doesn't have it yet. Throws a SpeedError. */ + getCard(input: GetCardInput, options?: { signal?: AbortSignal }): Promise +} + +export const DEFAULT_TIMEOUT_MS = 1500 + +const LOCALES: Record = { en: Locale.EN, fr: Locale.FR, es: Locale.ES, ht: Locale.HT } +const FORMATS: Record = { + link: CardFormat.LINK, + square: CardFormat.SQUARE, + portrait: CardFormat.PORTRAIT, + story: CardFormat.STORY, +} +const CODES: Partial> = { + [Code.DeadlineExceeded]: 'timeout', + [Code.Canceled]: 'timeout', + [Code.Unauthenticated]: 'unauthenticated', + [Code.PermissionDenied]: 'forbidden', + [Code.InvalidArgument]: 'invalid_input', + [Code.OutOfRange]: 'invalid_input', + [Code.FailedPrecondition]: 'invalid_input', + [Code.ResourceExhausted]: 'rate_limited', + [Code.Unavailable]: 'unavailable', +} + +/** The base address, checked: HTTPS, or plain HTTP on the machine itself; no user name, password, query or fragment. */ +function baseUrl(raw: string): string { + let url: URL + try { + url = new URL(raw) + } catch { + throw new SpeedError('failed', 'Speed: url is not an address') + } + const local = url.hostname === 'localhost' || url.hostname === '127.0.0.1' || url.hostname === '[::1]' + if (url.protocol !== 'https:' && !(url.protocol === 'http:' && local)) + throw new SpeedError('failed', 'Speed: url must use https (http only on localhost)') + if (url.username || url.password || url.search || url.hash) + throw new SpeedError('failed', 'Speed: url must not carry a user name, password, query or fragment') + return url.href.replace(/\/+$/, '') +} + +/** The wire request for an input. */ +export function toRequest(input: GetCardInput): Omit { + const locale = LOCALES[input.locale] + const format = FORMATS[input.format ?? 'link'] + if (locale === undefined) throw new SpeedError('invalid_input', `Speed: unknown locale ${JSON.stringify(input.locale)}`) + if (format === undefined) throw new SpeedError('invalid_input', `Speed: unknown format ${JSON.stringify(input.format)}`) + if (input.emoji) { + const { emoji, title, subtitle = '', label = '' } = input.emoji + return { + locale, + format, + template: { case: 'emoji', value: { $typeName: 'speed.socialcards.v1.EmojiCard', emoji, title, subtitle, label } }, + } + } + if (input.page) { + const { title, subtitle = '', emoji = [] } = input.page + return { + locale, + format, + template: { case: 'page', value: { $typeName: 'speed.socialcards.v1.PageCard', title, subtitle, emoji: [...emoji] } }, + } + } + throw new SpeedError('invalid_input', 'Speed: give an emoji or a page template') +} + +/** + * The fetch the transport calls. Connect asks for `redirect: 'error'`, which Cloudflare Workers refuse + * before any request is sent unless the Worker sets the `fetch_redirect_error` flag (on by default only + * from the 2026-12-22 compatibility date). So the request goes out with `redirect: 'manual'`, and a + * redirect is refused here: the token is never sent on to another address, on any runtime. The + * runtime's fetch is looked up at call time and called as a plain function (no `this` to lose on Workers). + */ +function noRedirects(given: typeof globalThis.fetch | undefined): typeof globalThis.fetch { + const send = async (input: RequestInfo | URL, init?: RequestInit): Promise => { + const fetch = given ?? globalThis.fetch + const response = await fetch(input, { ...init, redirect: 'manual' }) + if (response.type === 'opaqueredirect' || (response.status >= 300 && response.status < 400)) + throw new ConnectError(`Speed answered with a redirect (${response.status})`, Code.Unavailable) + return response + } + // Typed as the runtime's fetch (Bun's carries extra members such as `preconnect`). + return Object.assign(send, globalThis.fetch) +} + +/** A Connect error, or anything else a call threw, as a SpeedError. */ +export function toSpeedError(error: unknown): SpeedError { + if (error instanceof SpeedError) return error + const connect = ConnectError.from(error) + return new SpeedError(CODES[connect.code] ?? 'failed', `Speed: ${connect.rawMessage || Code[connect.code]}`, { cause: error }) +} + +/** + * A client for Speed's social cards, over gRPC-Web on fetch (Cloudflare Workers, Bun, Node). Call it + * on the server only: the token is the app's key. + * + * const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) + * const image = await socialCardOr('/og.png', cards.getCard({ locale: 'en', page: { title: 'Animals' } })) + */ +export function createSocialCardsClient(options: SpeedClientOptions): SocialCardsClient { + const base = baseUrl(options.url) + const token = options.token.trim() + if (!token || /[\s\u0000-\u001f\u007f]/.test(token)) + throw new SpeedError('failed', 'Speed: token is empty or has spaces or control characters') + const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS + if (!(timeoutMs > 0)) throw new SpeedError('failed', 'Speed: timeoutMs must be above 0') + const auth: Interceptor = (next) => (request) => { + request.header.set('authorization', `Bearer ${token}`) + return next(request) + } + const client = createClient( + SocialCardService, + createGrpcWebTransport({ + baseUrl: base, + fetch: noRedirects(options.fetch), + interceptors: [auth], + defaultTimeoutMs: timeoutMs, + }), + ) + return { + async getCard(input, callOptions = {}) { + const request = toRequest(input) + let response + try { + response = await client.getCard(request, callOptions.signal ? { signal: callOptions.signal } : {}) + } catch (error) { + throw toSpeedError(error) + } + let url: URL | undefined + try { + url = new URL(response.url) + } catch { + url = undefined + } + if (url?.protocol !== 'https:' || !response.width || !response.height) + throw new SpeedError('bad_response', 'Speed: the answer has no HTTPS card address or no size') + return { + url: url.href, + width: response.width, + height: response.height, + contentType: response.contentType, + created: response.created, + key: response.key, + } + }, + } +} + +/** + * The card's URL, or `fallback` (the app's own default card) when the call fails or times out, so a + * page never fails or waits because of Speed. Never throws; `onError` hears what went wrong (log its + * `code`, never the request's token). + */ +export async function socialCardOr(fallback: string, card: Promise, onError?: (error: SpeedError) => void): Promise { + try { + return (await card).url + } catch (error) { + try { + onError?.(toSpeedError(error)) + } catch { + // A logger that throws must not break the page either. + } + return fallback + } +} From 9f518d3bcf3ecf584ac7d3ca0d709551433aa2ff Mon Sep 17 00:00:00 2001 From: Jean Gerard Bousiquot Date: Sun, 6 Dec 2026 01:06:55 -0500 Subject: [PATCH 2/3] kit/speed: a shared failover for every Speed feature withFallback never throws and never waits past its deadline; it returns { url, width, height, fromSpeed }, with the app's own image or a hex colour (an inline SVG of the format's size). CircuitBreaker per client: 3 failures in 30 s skip Speed for 30 s, then one trial call. onFallback(reason): timeout, error, breaker-open, not-configured. No SPEED_URL or SPEED_TOKEN: the fallback at once, so apps ship before Speed is live. getCardOr replaces socialCardOr. From the security review: printable-ASCII tokens only, the client's own deadline (a fetch that ignores its signal can't hang it), answers with a user:password address or a malformed key are refused, a caller's abort is 'canceled' (not 'timeout'), redirect bodies are cancelled. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- README.md | 18 ++-- docs/speed.md | 140 ++++++++++++++++--------- scripts/check-size.ts | 2 +- src/speed.test.ts | 212 +++++++++++++++++++++++++++++++++----- src/speed.ts | 35 +++++-- src/speed/errors.ts | 33 ++++++ src/speed/fallback.ts | 197 +++++++++++++++++++++++++++++++++++ src/speed/social-cards.ts | 203 ++++++++++-------------------------- src/speed/transport.ts | 158 ++++++++++++++++++++++++++++ 10 files changed, 751 insertions(+), 249 deletions(-) create mode 100644 src/speed/errors.ts create mode 100644 src/speed/fallback.ts create mode 100644 src/speed/transport.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index bad374b..79089e8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ All notable changes to `@jgb-solutions/kit`. Versions follow semver. ## Unreleased -- `kit/speed` (new): typed clients for the Speed service, starting with social cards. `createSocialCardsClient({ url, token, timeoutMs? })` and `.getCard(input)` speak gRPC-Web over `fetch` (Connect-ES 2.3, protobuf-es 2.17), so they run on Workers, Bun and Node; one call, no retries, a 1.5 s deadline; `SpeedError` with typed codes; `socialCardOr(defaultUrl, promise)` never throws and falls back to the app's own card. `@connectrpc/connect`, `@connectrpc/connect-web` and `@bufbuild/protobuf` are new optional peer dependencies, needed only by this module. About 35 kB gzipped with them bundled, held by `check:size`. +- `kit/speed` (new): typed clients for the Speed service, one per feature, starting with social cards. `createSocialCardsClient({ url, token, timeoutMs?, onFallback? })` speaks gRPC-Web over `fetch` (Connect-ES 2.3, protobuf-es 2.17), so it runs on Workers, Bun and Node: one call, no retries, a 1.5 s deadline, no redirects followed. `getCardOr(input, fallback)` never throws and never waits past the deadline: when Speed is slow, failing or not set up yet, it returns the app's own image or a colour, sized to the format, with `fromSpeed: false`. A circuit breaker per client skips Speed for 30 s after 3 failures in 30 s. `withFallback`, `CircuitBreaker` and `colorImage` are shared by every feature client. `getCard` throws a `SpeedError` with typed codes. `@connectrpc/connect`, `@connectrpc/connect-web` and `@bufbuild/protobuf` are new optional peer dependencies, needed only by this module. About 35 kB gzipped with them bundled, held by `check:size`. ## 0.9.0-beta.2 diff --git a/README.md b/README.md index 8132ff8..ef843de 100644 --- a/README.md +++ b/README.md @@ -534,20 +534,22 @@ function AccountButton() { Typed clients for Speed, the service that does heavy work (drawing images) for an app's server, one per feature, over gRPC-Web on `fetch` (Connect-ES 2, protobuf-es 2): Cloudflare Workers, Bun and Node. Needs `@connectrpc/connect`, `@connectrpc/connect-web` and `@bufbuild/protobuf` (optional peers). The first feature is social cards, the share images for pages without one of their own: ```ts -import { createSocialCardsClient, socialCardOr } from '@jgb-solutions/kit/speed' +import { createSocialCardsClient } from '@jgb-solutions/kit/speed' -const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) // timeoutMs: 1500 by default -const image = await socialCardOr( - 'https://example.com/og.png', - cards.getCard({ locale: 'en', page: { title: 'Animals', emoji: ['🐶', '🐱'] } }), +const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) // once per isolate or process +const image = await cards.getCardOr( + { locale: 'en', page: { title: 'Animals', emoji: ['🐶', '🐱'] } }, + { url: 'https://example.com/share.png' }, ) +// { url, width, height, fromSpeed } ``` -- `getCard` returns `{ url, width, height, contentType, created, key }`. The same input always gives the same URL, so cache it (KV, the Cache API or SQLite); prerendered pages ask while they are built. -- One call, no retries, a 1.5 s deadline. A failure throws a `SpeedError` with a `code` (`timeout`, `unauthenticated`, `forbidden`, `invalid_input`, `rate_limited`, `unavailable`, `bad_response`, `failed`); `socialCardOr` never throws and returns the app's default card instead, so a page never fails or hangs because of Speed. +- **Speed never breaks a page.** `getCardOr` (and every feature's `…Or` call, built on `withFallback`) never throws and never waits past the deadline (1.5 s, no retries): when Speed is slow, failing or not set up yet (no `SPEED_URL`), it returns the app's own image (the logo on the brand colour is the recommended share image) or a colour, sized to the format. A circuit breaker skips Speed for 30 s after 3 failures in 30 s. `onFallback(reason)` counts them: `timeout`, `error`, `breaker-open`, `not-configured`. +- The same input always gives the same URL: cache it (KV, the Cache API or SQLite), but a fallback (`fromSpeed: false`) for 60 s at most. Prerendered pages ask while they are built. +- `getCard` is the call without the failover: `{ url, width, height, contentType, created, key }`, or a `SpeedError` with a `code`. - `SPEED_TOKEN` is the app's key: server-side only. Mobile apps never call Speed; they ask their site, through its oRPC procedures. -More in [docs/speed.md](docs/speed.md): Workers and Bun, the fallback, caching, updating the API. +More in [docs/speed.md](docs/speed.md): the failover, Workers and Bun, caching, updating the API. ## What goes in, and what never goes in diff --git a/docs/speed.md b/docs/speed.md index 37707b4..5c005bc 100644 --- a/docs/speed.md +++ b/docs/speed.md @@ -1,8 +1,9 @@ # kit/speed: the clients for Speed Speed is a separate service that does work an app's server shouldn't do on each request, such as drawing -images. `@jgb-solutions/kit/speed` holds one typed client per feature. The first feature is **social cards**: -the share images (og:image, twitter:image, Pinterest pins, stories) for pages without an image of their own. +images. `@jgb-solutions/kit/speed` holds one typed client per feature, all with the same failover. The first +feature is **social cards**: the share images (og:image, twitter:image, Pinterest pins, stories) for pages +without an image of their own. The clients speak gRPC-Web over `fetch`, through [Connect-ES](https://connectrpc.com/docs/web/getting-started) 2 and messages generated by [protobuf-es](https://github.com/bufbuild/protobuf-es) 2, so the same code runs @@ -23,13 +24,61 @@ The token says which app is calling; Speed keeps each app's colours, logo and fo only the text. Keep the token in a Worker secret (`wrangler secret put SPEED_TOKEN`) or the server's environment, never in code or in anything sent to a browser or a phone. -## Social cards +**Not set yet?** Leave both out. The client still works: every `…Or` call returns its fallback at once, +without a call or an error (`onFallback` hears `not-configured`). So an app can ship before Speed is live, +and switches to Speed's images when the two variables appear. Settings that are set but unsafe (an address +that isn't HTTPS, a token with spaces or control characters) throw when the client is created. + +## The failover: Speed never breaks a page + +Every feature has a `…Or` call that returns an image whatever happens: + +```ts +{ url: string, width: number, height: number, fromSpeed: boolean } +``` + +- **Never throws, never waits past the deadline** (1500 ms by default, `timeoutMs` to change it; no retries). + When Speed is slow, answers with an error, or refuses the input, you get the fallback. +- **A circuit breaker per client.** After 3 failures within 30 s, the client stops calling Speed for 30 s + and returns the fallback at once, so a down Speed adds no time to page views. Then one trial call goes + through: a success closes the circuit, a failure opens it for another 30 s. Create the client once per + Worker isolate (at module level, or cached from `env`) or once per Bun process, so it remembers. +- **The fallback is yours:** an image of the app's own, or a hex colour. + - **Recommended for social cards: the site's logo on its brand colour**, as an image at the card's size + (the 1200×630 share image every project already has in `branding/`). It is sized to the format unless you + give `width` and `height`. + - **A colour** (`{ color: '#1f6feb' }`) becomes a tiny inline SVG of the format's size. Use it for images + inside your own pages; social networks don't read inline (`data:`) images, so og:image needs a URL. +- **Count them.** `onFallback(reason, error?)` hears each fallback: `timeout`, `error`, `breaker-open` or + `not-configured`. Its `error` is a `SpeedError`; log its `code` and `message`, never the token (the client + never puts it in either). ```ts -import { createSocialCardsClient, socialCardOr } from '@jgb-solutions/kit/speed' +import { createSocialCardsClient } from '@jgb-solutions/kit/speed' + +const cards = createSocialCardsClient({ + url: env.SPEED_URL, + token: env.SPEED_TOKEN, + onFallback: (reason) => fallbacks.add(1, { reason }), // your metrics +}) + +const image = await cards.getCardOr( + { locale: 'fr', format: 'link', page: { title: 'Animaux', emoji: ['🐶', '🐱'] } }, + { url: 'https://example.com/share.png' }, // the logo on the brand colour, 1200×630 +) +``` -const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) +New feature clients reuse the same parts: `withFallback(call, fallback, { timeoutMs, breaker, onFallback })` +never throws and never waits past `timeoutMs`, whatever `call` does; `CircuitBreaker` and `colorImage` are +exported too. +**Images inside the app's pages** (posters, avatars) that are missing in the browser fall back in the +component instead: kit/ui's Avatar (and the poster fallback) draws initials on a colour. The failover here is +the server's, for images it asks Speed for. + +## Social cards + +```ts const card = await cards.getCard({ locale: 'fr', // en, fr, es or ht: the text is already in this language format: 'link', // link 1200×630 (the default), square 1080×1080, portrait 1000×1500, story 1080×1920 @@ -39,63 +88,49 @@ const card = await cards.getCard({ // { url: 'https://…/….png', width: 1200, height: 630, contentType: 'image/png', created: true, key: '…' } ``` +- `getCard` is the call without the failover: it throws a `SpeedError` whose `code` is `timeout`, + `canceled`, `unauthenticated`, `forbidden`, `invalid_input`, `rate_limited`, `unavailable`, + `bad_response`, `not_configured` or `failed`. Pass `{ signal }` as its second argument to stop it sooner. + Pages should use `getCardOr`. - **Same input, same URL.** Speed draws a card once and stores it; asking again returns the stored URL. -- **A short deadline, no retries.** A call gives up after 1500 ms (`timeoutMs` changes it) and is never - retried, because it sits on a page's path. Pass `{ signal }` as `getCard`'s second argument to stop it sooner. -- **Typed errors.** A failed call throws a `SpeedError` whose `code` is `timeout`, `unauthenticated`, - `forbidden`, `invalid_input`, `rate_limited`, `unavailable`, `bad_response` or `failed`. Its message never - holds the token. -- **Checked settings.** `createSocialCardsClient` refuses an address that isn't HTTPS (or HTTP on - localhost), or that carries a user name, password, query or fragment, and a token that is empty or holds - spaces or control characters. An answer whose card address isn't HTTPS is refused as `bad_response`. - -### The fallback: a page never fails because of Speed - -`socialCardOr(defaultUrl, promise, onError?)` returns the card's URL, or the app's own default card when -the call fails or times out. It never throws. `onError` receives the `SpeedError`: log its `code`. - -```ts -const image = await socialCardOr('https://example.com/og.png', cards.getCard(input), (error) => console.warn('social card', error.code)) -``` - -The fallback is always a `link`-shaped card, so set `og:image:width` and `og:image:height` from the card -when you have one, and from your default otherwise. +- **Checked answers.** A card whose address isn't HTTPS (or carries a user name or password), without a + size, or with a malformed `key` is refused as `bad_response`. `key` is an identifier: never use it as a + file path. The URL is a URL: escape it like any other value when you write it into HTML (the app's `seo()` + helper does). +- **No redirects.** The client never follows one, so the token never goes to another address. +- `CARD_SIZES` holds each format's size, for og:image:width and og:image:height. ### Cache the URL The card's URL never changes for the same input, so ask Speed once per page and language, and keep the -answer. Key it by what the card shows (the input's fields, or a hash of them), not by the request: +answer. Key it by what the card shows (a hash of the input), not by the request. -- **Cloudflare Workers:** KV (`env.CARDS.get(key)`, then `put(key, url)` after a miss), or the Cache API for - the page itself. -- **Bun on a server:** a small SQLite table (`card_key TEXT PRIMARY KEY, url TEXT`). -- **Both:** cache only real cards. Don't store the fallback, so the next visit tries Speed again. +- **Cloudflare Workers:** KV (`get`, then `put` after a miss), or the Cache API for the page itself. +- **Bun on a server:** a small SQLite table (`card_key TEXT PRIMARY KEY, url TEXT, expires_at INTEGER`). +- **Never cache a fallback as the answer.** When `fromSpeed` is false, keep it for at most + `FALLBACK_TTL_SECONDS` (60), marked as a fallback, so Speed's card replaces it as soon as Speed is back. ```ts -import { SpeedError, type GetCardInput } from '@jgb-solutions/kit/speed' +import { FALLBACK_TTL_SECONDS, type GetCardInput } from '@jgb-solutions/kit/speed' -async function cardFor(env: Env, input: GetCardInput): Promise { +async function cardFor(env: Env, input: GetCardInput) { // A hash keeps the key short (KV keys stop at 512 bytes) whatever the text. const what = new TextEncoder().encode(JSON.stringify([input.locale, input.format ?? 'link', input.emoji ?? input.page])) const hash = new Uint8Array(await crypto.subtle.digest('SHA-256', what)) const key = `card:${Array.from(hash, (byte) => byte.toString(16).padStart(2, '0')).join('')}` - const cached = await env.CARDS.get(key) + const cached = await env.CARDS.get<{ url: string; width: number; height: number }>(key, 'json') if (cached) return cached - try { - const card = await cards.getCard(input) - await env.CARDS.put(key, card.url) - return card.url - } catch (error) { - console.warn('social card', error instanceof SpeedError ? error.code : 'failed') - return 'https://example.com/og.png' - } + const image = await cards.getCardOr(input, { url: 'https://example.com/share.png' }) + // Speed's card for good; a fallback for a minute only (KV's shortest expiry). + await env.CARDS.put(key, JSON.stringify(image), image.fromSpeed ? {} : { expirationTtl: FALLBACK_TTL_SECONDS }) + return image } ``` ### Prerendered pages A page that is prerendered asks for its card while it is built: the build runs with `SPEED_URL` and -`SPEED_TOKEN` in its environment and writes the URL into the page's tags. With the fallback, a build never +`SPEED_TOKEN` in its environment and writes the URL into the page's tags. With the failover, a build never fails because Speed is down; the next build picks the card up. ### Mobile apps @@ -106,27 +141,32 @@ it asks its own site, through the site's oRPC procedures, and the site calls Spe ## On a Worker ```ts -import { createSocialCardsClient, socialCardOr } from '@jgb-solutions/kit/speed' +import { createSocialCardsClient, type SocialCardsClient } from '@jgb-solutions/kit/speed' + +type Env = { SPEED_URL?: string; SPEED_TOKEN?: string } +let cards: SocialCardsClient | undefined // one per isolate, so its circuit breaker remembers export default { - async fetch(request, env: { SPEED_URL: string; SPEED_TOKEN: string }) { - const cards = createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) - const image = await socialCardOr('https://example.com/og.png', cards.getCard({ locale: 'en', page: { title: 'Home' } })) + async fetch(request, env) { + cards ??= createSocialCardsClient({ url: env.SPEED_URL, token: env.SPEED_TOKEN }) + const image = await cards.getCardOr({ locale: 'en', page: { title: 'Home' } }, { url: 'https://example.com/share.png' }) // Put it in the page's tags through the app's own head helper, which escapes it. - return Response.json({ image }) + return Response.json(image) }, -} satisfies ExportedHandler<{ SPEED_URL: string; SPEED_TOKEN: string }> +} satisfies ExportedHandler ``` The client is about 35 kB gzipped (Connect-ES and protobuf-es included), counted in the Worker's size. -Create it once per request, or once per isolate from `env`. +It works whatever the Worker's compatibility date: Connect asks fetch for `redirect: 'error'`, which Workers +refuse before 2026-12-22 unless the `fetch_redirect_error` flag is set, so the client sends `manual` and +refuses redirects itself. ## On Bun ```ts import { createSocialCardsClient } from '@jgb-solutions/kit/speed' -const cards = createSocialCardsClient({ url: Bun.env.SPEED_URL!, token: Bun.env.SPEED_TOKEN! }) +export const cards = createSocialCardsClient({ url: Bun.env.SPEED_URL, token: Bun.env.SPEED_TOKEN }) ``` Create it once at start-up and share it. diff --git a/scripts/check-size.ts b/scripts/check-size.ts index 0e52e76..7071b1c 100644 --- a/scripts/check-size.ts +++ b/scripts/check-size.ts @@ -87,7 +87,7 @@ await cost( const speed = JSON.stringify(resolve('dist/speed.js')) await cost( 'kit/speed: the social cards client', - `import { createSocialCardsClient, socialCardOr } from ${speed}; globalThis.__keep = [createSocialCardsClient, socialCardOr]`, + `import { createSocialCardsClient } from ${speed}; globalThis.__keep = [createSocialCardsClient]`, 40 * 1024, ) diff --git a/src/speed.test.ts b/src/speed.test.ts index af7556c..21cb91e 100644 --- a/src/speed.test.ts +++ b/src/speed.test.ts @@ -1,6 +1,15 @@ import { describe, expect, test } from 'bun:test' import { create, fromBinary, toBinary } from '@bufbuild/protobuf' -import { createSocialCardsClient, socialCardOr, SpeedError, type SocialCard, type SpeedErrorCode } from './speed' +import { + CircuitBreaker, + colorImage, + createSocialCardsClient, + SpeedError, + withFallback, + type FallbackReason, + type SocialCard, + type SpeedErrorCode, +} from './speed' import { CardFormat, GetCardRequestSchema, @@ -171,6 +180,7 @@ describe('createSocialCardsClient', () => { const ok = { url: URL_BASE, token: TOKEN } for (const url of [ 'http://speed.example.com', + 'http://localhost.example.com', 'ftp://speed.example.com', 'not a url', 'https://user:pw@speed.example.com', @@ -178,7 +188,7 @@ describe('createSocialCardsClient', () => { 'https://speed.example.com/#x', ]) expect(() => createSocialCardsClient({ ...ok, url })).toThrow(SpeedError) - for (const token of ['', ' ', 'a b', 'a\r\nx-evil: 1']) expect(() => createSocialCardsClient({ ...ok, token })).toThrow(SpeedError) + for (const token of ['a b', 'a\r\nx-evil: 1', 'tokĀen']) expect(() => createSocialCardsClient({ ...ok, token })).toThrow(SpeedError) expect(() => createSocialCardsClient({ ...ok, timeoutMs: 0 })).toThrow(SpeedError) // Plain HTTP is allowed on the machine itself, for development. expect(() => createSocialCardsClient({ ...ok, url: 'http://localhost:8080' })).not.toThrow() @@ -192,43 +202,189 @@ describe('createSocialCardsClient', () => { expect(String(error)).not.toContain(TOKEN) } }) -}) -describe('socialCardOr', () => { - const input = { locale: 'en', page: { title: 'Home' } } as const + test('a malformed key or an address with a password is a bad response', async () => { + for (const fields of [{ key: '../../etc/passwd' }, { key: 'a b.png' }, { url: 'https://u:p@cards.example.com/a.png' }]) { + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card(fields)).fetch }) + expect(((await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe( + 'bad_response', + ) + } + }) - test("returns the card's URL when Speed answers", async () => { - const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card()).fetch }) - expect(await socialCardOr('https://example.com/og.png', cards.getCard(input))).toBe( - 'https://cards.example.com/app/socialcards/link/en/abc.png', - ) + test('ends on time even with a fetch that ignores the abort signal', async () => { + const deaf = (() => new Promise(() => {})) as unknown as typeof globalThis.fetch + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: deaf, timeoutMs: 30 }) + const started = performance.now() + expect(((await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe('timeout') + expect(performance.now() - started).toBeLessThan(1000) }) - test('returns the default card on an error or a timeout, and reports why', async () => { - const seen: SpeedErrorCode[] = [] - const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(14, 'down')).fetch }) - expect(await socialCardOr('https://example.com/og.png', down.getCard(input), (e) => seen.push(e.code))).toBe( - 'https://example.com/og.png', - ) + test("the caller's own signal cancels the call", async () => { const hang = ((_: RequestInfo | URL, init?: RequestInit) => new Promise((_, reject) => init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)), )) as typeof globalThis.fetch - const slow = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang, timeoutMs: 20 }) - expect(await socialCardOr('https://example.com/og.png', slow.getCard(input), (e) => seen.push(e.code))).toBe( - 'https://example.com/og.png', - ) - expect(seen).toEqual(['unavailable', 'timeout']) + const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang }) + const controller = new AbortController() + const call = cards.getCard({ locale: 'en', page: { title: 'Home' } }, { signal: controller.signal }).catch((e: unknown) => e) + controller.abort() + expect(((await call) as SpeedError).code).toBe('canceled') + }) + + test('without SPEED_URL or SPEED_TOKEN, getCard says so', async () => { + for (const settings of [{}, { url: URL_BASE }, { token: TOKEN }, { url: '', token: '' }]) { + const cards = createSocialCardsClient(settings) + expect(((await cards.getCard({ locale: 'en', page: { title: 'Home' } }).catch((e: unknown) => e)) as SpeedError).code).toBe( + 'not_configured', + ) + } }) +}) + +describe('getCardOr: the failover', () => { + const input = { locale: 'en', page: { title: 'Home' } } as const + const hang = ((_: RequestInfo | URL, init?: RequestInit) => + new Promise((_, reject) => + init?.signal?.addEventListener('abort', () => reject(init.signal?.reason)), + )) as typeof globalThis.fetch - test('never throws, even when the logger does or the input was refused', async () => { - expect( - await socialCardOr('/og.png', Promise.reject(new Error('boom')), () => { - throw new Error('logger down') - }), - ).toBe('/og.png') + test("Speed's card, marked as from Speed", async () => { const cards = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => card()).fetch }) + expect(await cards.getCardOr(input, { url: 'https://example.com/og.png' })).toEqual({ + url: 'https://cards.example.com/app/socialcards/link/en/abc.png', + width: 1200, + height: 630, + fromSpeed: true, + }) + }) + + test("the app's image, sized to the format, on an error or a timeout; and why", async () => { + const reasons: FallbackReason[] = [] + const onFallback = (reason: FallbackReason) => reasons.push(reason) + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(14, 'down')).fetch, onFallback }) + expect(await down.getCardOr({ ...input, format: 'square' }, { url: 'https://example.com/logo-on-brand.png' })).toEqual({ + url: 'https://example.com/logo-on-brand.png', + width: 1080, + height: 1080, + fromSpeed: false, + }) + const slow = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: hang, timeoutMs: 20, onFallback }) + const started = performance.now() + expect((await slow.getCardOr(input, { url: 'https://example.com/og.png', width: 600, height: 315 })).width).toBe(600) + expect(performance.now() - started).toBeLessThan(1000) + expect(reasons).toEqual(['error', 'timeout']) + }) + + test('a colour becomes an inline image of the format', async () => { + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(13, 'oops')).fetch }) + const image = await down.getCardOr({ ...input, format: 'story' }, { color: '#1f6feb' }) + expect(image).toMatchObject({ width: 1080, height: 1920, fromSpeed: false }) + expect(decodeURIComponent(image.url)).toBe( + 'data:image/svg+xml,', + ) + }) + + test('not set up yet: the fallback at once, without a call', async () => { + const reasons: FallbackReason[] = [] + const cards = createSocialCardsClient({ url: undefined, token: undefined, onFallback: (reason) => reasons.push(reason) }) + expect((await cards.getCardOr(input, { url: '/og.png' })).url).toBe('/og.png') + expect(reasons).toEqual(['not-configured']) + }) + + test('never throws: a refused input, a throwing counter, a bad colour', async () => { + const cards = createSocialCardsClient({ + url: URL_BASE, + token: TOKEN, + fetch: fakeSpeed(() => card()).fetch, + onFallback: () => { + throw new Error('counter down') + }, + }) // @ts-expect-error: a locale Speed doesn't have - expect(await socialCardOr('/og.png', cards.getCard({ locale: 'de', page: { title: 'Start' } }))).toBe('/og.png') + expect((await cards.getCardOr({ locale: 'de', page: { title: 'Start' } }, { url: '/og.png' })).url).toBe('/og.png') + const down = createSocialCardsClient({ url: URL_BASE, token: TOKEN, fetch: fakeSpeed(() => failure(14, 'down')).fetch }) + expect((await down.getCardOr(input, { color: 'red"/>