agentleFS
golid-aigolid-ai/golid/.cursor/rules/dynamic-image-endpoints.mdc

golid / rules

Cursor rule40 starsChanged 6 months agoMITView on GitHub

How to build dynamic image endpoints (OG previews, badges, PDFs) that are fast, deterministic, and cache-correct — use when adding any backend endpoint that returns dynamically rendered image bytes

The file

We split this dynamic-image-endpoints.mdc into the rules it gives an agent

3 rules. About 0 are common, 2 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Does NOT apply to:

    line 27
  2. Distinctive:

    Cache-stable: No external network calls means no dependence on GCS/S3 availability for the render path.

    line 68
  3. Very specific:

    If pure Go can't hit the visual bar, prefer a tiny library (oksvg, rasterx, golang.org/x/image/font/opentype) over a second runtime.

    line 71

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
dynamic-image-endpoints.mdc
---
description: How to build dynamic image endpoints (OG previews, badges, PDFs) that are fast, deterministic, and cache-correct — use when adding any backend endpoint that returns dynamically rendered image bytes
alwaysApply: false
---

# Dynamic Image Endpoints

> **Thesis:** Dynamic image endpoints must be (1) pure deterministic
> renderers — same input always produces identical bytes — and (2)
> include a renderer version constant in their ETag hash so visual
> changes invalidate downstream caches on deploy. Without (1), the
> render is slow, untestable, and depends on external runtimes;
> without (2), browser/CDN/conditional-GET caches keep serving the
> old bytes for the full max-age window after every renderer change.
>
> **Refrain:** `Pure function in → deterministic bytes out → version
> the renderer in the ETag`

## When this applies

- OG/social-card preview images (`/api/v1/profiles/:slug/og-image`)
- Badge/credential PNGs (e.g. Labs certifications)
- QR code endpoints with branded chrome
- Invoice/receipt PDF generation
- Any endpoint that returns image bytes computed from request input

Does NOT apply to:

- Static image assets served from `frontend/public/images/` (Vite
  hashes filenames; no dynamic rendering)
- User-uploaded images (no rendering; just storage proxy)
- Avatar/thumbnail resizing (use a dedicated image-proxy library)

## Rule 1: Pure renderer functions

The renderer must be a pure Go function: input struct → `[]byte` PNG
output, no I/O, no network, no browser, no embedded language runtime.

**BAD: Node/browser/screenshot pipeline**

```go
// Headless Chrome screenshot: second runtime, non-deterministic pixels.
func RenderOGImage(profile *Profile) ([]byte, error) {
    return chromiumScreenshot("https://localhost/render-og?slug=" + profile.Slug)
}
```

**GOOD: Pure Go renderer**

```go
// Pure function: same input → same bytes; testable in 50ms via `go test`.
func RenderPublicProfileOGImage(ctx context.Context, profile *PublicStudentProfile) (*PublicProfileOGImage, error) {
    img := image.NewRGBA(...)
    drawProofCardSurface(img, ...)
    drawText(img, name, ...)
    // ... pure draw calls only
    return &PublicProfileOGImage{PNG: bytes, ETag: computeETag(profile)}, nil
}
```

**Why this matters:**

- **Testable & deterministic.** Pure functions test in 50ms with
  stable golden files; Chrome screenshot tests need the binary and
  take seconds with non-deterministic pixels.
- **Fast.** Go's `image/draw` runs in 50-200ms per render; Chrome
  screenshot is 2-5s.
- **Cache-stable.** No external network calls means no dependence
  on GCS/S3 availability for the render path.

If pure Go can't hit the visual bar, prefer a tiny library (`oksvg`,
`rasterx`, `golang.org/x/image/font/opentype`) over a second runtime.

## Rule 2: Renderer version in the ETag hash

Mix a `<renderer>RendererVersion` constant into the ETag hash so
renderer-only changes invalidate downstream caches even when the
input data is unchanged.

**BAD: ETag computed from input data only**

```go
// Renderer change → bytes change → but ETag stays the same because
// the input is unchanged. Cached clients keep showing the old image
// for the full max-age window (5+ min).
func computeETag(profile *PublicStudentProfile) string {
    h := sha256.New()
    fmt.Fprintf(h, "%s\x00", profile.ProfileSlug)
    fmt.Fprintf(h, "%s\x00", profile.FirstName)
    // ... profile fields
    return `W/"og-` + hex.EncodeToString(h.Sum(nil))[:24] + `"`
}
```

**GOOD: Renderer version mixed into the hash**

```go
// Bump this constant whenever the renderer produces visually
// different bytes for the same input. Renderer-only changes
// invalidate every previously-cached ETag on first request
// after deploy.
//
// Bump log:
//   - v1  initial portrait-card render
//   - v2  landscape redesign with retina 2x and neon teal border
const ogRendererVersion = "v2"

func computeETag(profile *PublicStudentProfile) string {
    h := sha256.New()
    fmt.Fprintf(h, "%s\x00", ogRendererVersion)  // FIRST
    fmt.Fprintf(h, "%s\x00", profile.ProfileSlug)
    // ... profile fields
    return `W/"og-` + hex.EncodeToString(h.Sum(nil))[:24] + `"`
}
```

**Bump the constant when:** layout, colors, fonts, borders/gradients,
or image dimensions change.

**Do NOT bump when:** profile data changes (field hash handles that),
refactors with identical output, or edge-case handling that doesn't
change output for existing inputs.

**Lock the contract with a test:**

```go
func TestETag_VersionBumpInvalidatesCache(t *testing.T) {
    profile := &Profile{...}
    bumped := hashFields([]string{"v-test-bump", profile.Slug, ...})
    if computeETag(profile) == bumped {
        t.Fatal("ETag did not change when renderer version differed")
    }
}
```

## Related Rules

- HTTP cache headers, render budget, max bytes — see `dynamic-image-http`.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.