Documentation
¶
Overview ¶
Package render implements the chromedp-backed SVG resize, the pure-Go svg.Hash, the SVG decoration pipeline (octicon / CSS purge / XML format), and the small Renderer interface that engine.Compute consumes. Chromedp imports live behind a build tag so the default `go test ./...` run stays usable without a chromium binary.
See specs/003-chromedp-rendering-pipeline/ for the full contract.
Index ¶
- func Apply(stages []PipelineStage, in string) (string, []error)
- func FormatXML(in string) (string, error)
- func Hash(rendered string) (string, error)
- func OptimizeCSS(in string) (string, error)
- func ReplaceOcticons(in string) (string, error)
- type Browser
- type BrowserOpts
- type FakeRenderer
- type PipelineStage
- type Renderer
- type ResizeOpts
- type ResizeResult
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Apply ¶
func Apply(stages []PipelineStage, in string) (string, []error)
Apply runs the stages in order. The returned string is the final SVG after all (successful) stages. Errors are returned alongside in registration order, each wrapped with the offending stage's name. Apply never panics on stage errors and never short-circuits on a failure: the caller decides whether to treat collected errors as fatal.
func FormatXML ¶
FormatXML returns a re-indented copy of the input XML/SVG payload. The output uses two-space indentation, a single `\n` line separator, and emits empty elements as self-closing `<foo/>` tokens (matching the upstream xml-formatter `collapseContent=true` knob).
Whitespace-only text nodes are discarded; non-empty text content inside an element ends up on its own line. CDATA, processing instructions, comments, and numeric character references survive the round trip via encoding/xml's standard tokenizer.
The function is intentionally permissive: malformed input bubbles up as an error so the engine dispatch can append it to res.Errors (FR-018) and fall back to the prior pipeline stage's output.
func Hash ¶
Hash returns the MD5 hex digest (32 lowercase chars) of the SVG's outer HTML after the first <footer> element is removed. The hash is the comparison key that backs `output_condition=data-changed` (M6 T-114): two SVGs whose DOM differs only in the footer (timezone / version / generated time) MUST hash identically.
Contract (specs/003-chromedp-rendering-pipeline/contracts/svg-hash.md):
- Whitespace-only or empty input → ("", nil)
- Document without an <svg> root → ("", *xerrors.InputError)
- Multiple <footer> nodes → only the first one is removed
The implementation is pure Go (goquery / crypto/md5); no chromedp dependency lands on the hash path.
func OptimizeCSS ¶
OptimizeCSS walks the embedded `<style data-optimizable="true">` nodes, drops selectors that no element in the document matches, and minifies the result. Selectors that contain an ID component (`#metrics-end`, `#header`, etc.) are kept unconditionally so the svg.Resize anchor / template scaffold stays addressable even if no CSS targets it in the body (FR-015 + SC-006).
CSS embedded in `<style>` tags without the `data-optimizable="true"` attribute is left as-is — that's the upstream contract for opting out per template.
func ReplaceOcticons ¶
ReplaceOcticons swaps every `:octicon-<name>(-<size>)?:` placeholder in `in` for the matching SVG fragment from assets/octicons/data.json, injecting `class="octicon"` so downstream CSS targets it. Unknown (name, size) combinations pass through verbatim.
The function is idempotent: ReplaceOcticons(ReplaceOcticons(in)) equals ReplaceOcticons(in) because the rendered `<svg class="octicon">` fragments no longer contain the source placeholder pattern.
Types ¶
type Browser ¶
type Browser struct {
// contains filtered or unexported fields
}
Browser owns a single chromedp ExecAllocator plus the parent context it spawns tabs from. A Browser is safe for concurrent use; NewTab serializes against the internal recycle mutex.
Upstream-compatible defaults:
- --no-sandbox, --disable-extensions, --disable-dev-shm-usage, --disable-gpu, --single-process (see contracts/svg-resize.md §1 / FR-002).
- METRICS_CHROME_PATH env var resolves the chromium executable when BrowserOpts.ExecPath is empty.
- Recycle counter trips at BrowserOpts.RecycleEvery (defaults to 200, upstream `svg.resize.browser` parity).
func New ¶
func New(opts BrowserOpts) (*Browser, error)
New constructs a Browser. The returned instance owns chromedp resources; callers MUST call Close when done.
When BrowserOpts.ExecPath is non-empty, the file is stat-checked up front so a missing chromium binary fails fast instead of producing a confusing chromedp.WaitProcess error several seconds later.
func (*Browser) Close ¶
Close cancels the allocator and waits for cleanup. Idempotent. Subsequent NewTab calls return an *InputError.
func (*Browser) NewTab ¶
NewTab returns a child context bound to a fresh chromedp tab. Callers MUST call the returned cancel func (typically via defer) when finished with the tab. The supplied parent ctx provides the cancellation / deadline plumbing for the caller; chromedp tabs are spawned from b.parentCtx so they survive the parent ctx going out of scope until cancel runs.
NewTab transparently recycles the underlying allocator after every `RecycleEvery` invocations to avoid long-lived chromium memory growth. Concurrent NewTab calls block during a recycle.
func (*Browser) RecycledCount ¶
RecycledCount returns how many allocator re-inits have occurred since construction. Exposed for tests so we can assert that the recycle-every-N counter trips at the expected moment without reaching into private fields.
func (*Browser) Resize ¶
func (b *Browser) Resize(ctx context.Context, in string, opts ResizeOpts) (ResizeResult, error)
Resize implements Renderer. It opens a fresh chromedp tab, injects the rendered SVG into about:blank, runs the upstream-derived measurement JS, optionally rasterizes to PNG/JPEG, and returns the final bytes plus the post-padding dimensions.
Chromedp errors (start failure, evaluate failure, tab teardown) are wrapped as *xerrors.RetryableError so the engine dispatch can surface them via Result.Errors while preserving the typed shape callers match on with errors.As.
type BrowserOpts ¶
type BrowserOpts struct {
// ExecPath, when non-empty, overrides chromedp's auto-detect path
// for the chromium / chrome binary. Falls back to the
// METRICS_CHROME_PATH env var when empty.
ExecPath string
// RecycleEvery sets how many NewTab calls trigger an allocator
// re-init. Zero falls back to the default (200).
RecycleEvery int
// Headless toggles the --headless flag. Default true. Set false
// only for local debugging via --puppeteer-disable-headless.
Headless bool
// ExtraFlags are appended to the chromedp ExecAllocator option
// set after the upstream-compatible defaults are applied.
ExtraFlags []chromedp.ExecAllocatorOption
// Logger is used for debug / warn events. nil falls back to
// slog.Default().
Logger *slog.Logger
}
BrowserOpts captures the construction-time configuration. Zero values map to upstream-compatible defaults.
type FakeRenderer ¶
type FakeRenderer struct {
// Width / Height override the returned ResizeResult dimensions.
// Zero falls back to 1 so image.Decode-style callers still see a
// valid bounding box.
Width, Height int
// ErrOnConvert, when non-nil, maps a Convert value to the error
// Resize should return for that branch. e.g. {"png": sentinel}.
ErrOnConvert map[string]error
}
FakeRenderer returns deterministic, minimal bytes for tests. Use only in _test.go files or build-tagged fixtures: production code always uses *Browser. The fake never starts chromium and never touches the network.
func NewFakeRenderer ¶
func NewFakeRenderer() *FakeRenderer
NewFakeRenderer constructs a zero-value FakeRenderer for callers that prefer a constructor over a struct literal.
func (*FakeRenderer) Resize ¶
func (f *FakeRenderer) Resize(_ context.Context, in string, opts ResizeOpts) (ResizeResult, error)
Resize implements Renderer. SVG / "" passes the input through as bytes; PNG / JPEG returns a hard-coded minimal valid image.
type PipelineStage ¶
type PipelineStage struct {
// Name labels the stage in error wrapping and debug logs.
Name string
// Run takes the current SVG and returns the next SVG. Any error
// is surfaced via Apply's []error return; the input string is
// forwarded to the next stage unchanged (best-effort chain).
Run func(in string) (string, error)
}
PipelineStage is the function signature each decoration / optimization step exposes. Stages are composed by Apply.
type Renderer ¶
type Renderer interface {
Resize(ctx context.Context, in string, opts ResizeOpts) (ResizeResult, error)
}
Renderer is the abstraction engine.Compute uses to convert a rendered SVG string into final SVG/PNG/JPEG bytes. It exists so the engine package never imports chromedp directly: production code injects a *Browser via Deps.Render, tests inject a *FakeRenderer.
type ResizeOpts ¶
type ResizeOpts struct {
// Convert ∈ {"", "svg", "png", "jpeg"}. Empty is normalized to
// "svg". Anything else is reported as *UnsupportedFormatError by
// normalize.
Convert string
// Padding mirrors the upstream `config.padding` input format:
// either a single string "<abs> + <rel>%" or two strings
// [width-padding, height-padding] / one comma-separated string.
Padding []string
// Scripts is the list of user JS bodies to evaluate before
// measuring. Each entry is wrapped into `(async () => { ... })()`
// by the resize JS template (see contracts/svg-resize.md §2.1).
Scripts []string
// ViewportWidth / ViewportHeight default to 980/980 when zero.
ViewportWidth, ViewportHeight int
// SettleDelay overrides the post-script sleep. Zero falls back to
// 2.4 seconds (upstream parity).
SettleDelay time.Duration
}
ResizeOpts captures the per-call parameters of Resize. Slices are read-only after construction.
type ResizeResult ¶
type ResizeResult struct {
// Body holds the serialized payload — SVG bytes for ""/"svg",
// raw PNG bytes for "png", raw JPEG bytes for "jpeg".
Body []byte
// Width / Height are the post-padding integer dimensions written
// back into the <svg> root (Height only) and recorded for
// diagnostics.
Width, Height int
// MIME is the IANA type matching Body, one of
// "image/svg+xml" | "image/png" | "image/jpeg".
MIME string
}
ResizeResult is the value Resize returns on success.