httpapi

package
v0.30.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package httpapi holds the HTTP layer for both Relay planes.

  • app/httpapi/inference — data plane: /v1/*, /healthz
  • app/httpapi/control — admin plane: /auth/*, CRUD, /version, etc.

Each subpackage exposes a typed Deps and a Mount(chi.Router, Deps) huma.API entrypoint. The top-level package owns shared concerns: the relay error envelope used by both planes, the huma↔chi middleware adapter, and the build/version string.

Index

Constants

View Source
const (
	ShedStageEarly  = "early"   // refused at the route, before the body is read
	ShedStageLate   = "late"    // refused by PreFlight, after the body was read
	ShedStageKVPool = "kv_pool" // refused at the route, before the body is read, while the kv pool's wait queue is full
)

Shed stages, the values of requests_shed_total's stage label.

View Source
const DefaultMaxInflight = 2048

DefaultMaxInflight is the hard cap when no memory limit is set, and the floor of the cap derived from one. It is not a per-core multiple: the hard cap bounds memory, which does not scale with core count; CPU is the adaptive limit's job.

View Source
const OverloadMessage = "relay is at capacity; retry shortly"

OverloadMessage is the error message of a request refused as overloaded.

View Source
const RetryAfterShed = "1"

RetryAfterShed is the Retry-After header value (seconds) sent when relay refuses a request as overloaded. One second is far longer than the ~20ms a healthy request path takes, so the transient saturation has cleared by the time a well-behaved client retries.

Variables

View Source
var ErrShed = errors.New("in-flight capacity reached")

ErrShed is returned by PreFlight when the in-flight cap is reached. The inference dispatch maps it to the route's retriable overload answer; any other pre-flight error stays a 500.

View Source
var Version = "dev"

Version is the human-facing build version surfaced in the OpenAPI Info block, /version, and /config.json. Stamped at build time via

-ldflags "-X github.com/wyolet/relay/app/httpapi.Version=<tag>"

(the image build threads the release tag through docker-bake.hcl → Dockerfile). Unstamped builds report "dev".

Functions

func HumaAuth

func HumaAuth(mw func(http.Handler) http.Handler) func(huma.Context, func(huma.Context))

HumaAuth adapts a net/http middleware into a huma per-operation middleware. Used by both planes to attach auth (or any http.Handler-shaped middleware) to specific huma operations rather than the whole chi router.

Pattern: pass any `func(http.Handler) http.Handler` and it composes onto a huma.Operation via Middlewares = huma.Middlewares{HumaAuth(mw), ...}.

func Install

func Install()

Install installs the process-global huma overrides: relay's error envelope, and a schema namer that prefixes type names with their package's last segment (e.g. provider_Spec vs host_Spec) so the catalog kinds' uniform Spec sub-structs don't collide in the OpenAPI schema registry.

Idempotent — safe to call from every Mount entrypoint.

func InstallErrorRewriter

func InstallErrorRewriter()

InstallErrorRewriter is the legacy alias for Install(). Retained until callers migrate.

func NewRegistry

func NewRegistry() huma.Registry

NewRegistry returns a huma schema Registry whose namer produces clean PascalCase schema ids in the generated OpenAPI:

  • The entity types Provider / Host / Model / HostKey / RateLimit / Policy / Pricing / Key / ServiceAccount / Group keep their bare names.
  • Sub-types defined inside an entity package get the entity name prepended so the 8 colliding `Spec` types become `ProviderSpec`, `HostSpec`, `ModelSpec`, etc. without renaming the Go types.
  • Types in non-entity packages (meta.Metadata, meta.Owner, adapter.Name, …) keep their bare names — they don't collide.

Plane Mount() functions install the returned registry on their huma.Config.

func RecordShed added in v0.11.7

func RecordShed(stage string)

RecordShed counts one shed request at stage (a ShedStage* value) and logs at most one WARN per shedLogInterval process-wide, carrying the sheds since the previous line.

func ScalarHandler

func ScalarHandler(title, specURL string) http.HandlerFunc

ScalarHandler returns an HTML page that renders the OpenAPI spec at specURL using Scalar API Reference. Use it to replace huma's default Stoplight Elements docs UI: set cfg.DocsPath = "" before humachi.New(...) and register this handler on the chi router instead.

Types

type APIError added in v0.10.0

type APIError struct {
	Err        APIErrorBody `json:"error" doc:"The error."`
	HTTPStatus int          `json:"-"`
}

APIError implements huma.StatusError with relay's error envelope:

{ "error": { "type": "...", "code": "...", "message": "..." } }

The shape is compatible with what LLM client libraries already parse.

func (*APIError) ContentType added in v0.10.0

func (e *APIError) ContentType(_ string) string

func (*APIError) Error added in v0.10.0

func (e *APIError) Error() string

func (*APIError) GetStatus added in v0.10.0

func (e *APIError) GetStatus() int

type APIErrorBody added in v0.10.0

type APIErrorBody struct {
	Type    string `` /* 143-byte string literal not displayed */
	Code    string `` /* 172-byte string literal not displayed */
	Refusal string `` /* 562-byte string literal not displayed */
	Message string `json:"message"        doc:"Human-readable explanation."`
	// Details carries huma's per-field validation errors, which the flat
	// OpenAI shape has no other place for.
	Details []*huma.ErrorDetail `json:"details,omitempty" doc:"Per-field failures of a 422 schema validation."`
}

APIErrorBody is the inner object of relay's error envelope:

{ "error": { "type": "...", "code": "...", "message": "..." } }

LLM client libraries already parse this shape.

type Admission added in v0.9.8

type Admission struct {
	// contains filtered or unexported fields
}

Admission bounds concurrent in-flight inference requests via a buffered channel used as a counting semaphore.

func NewAdmission added in v0.9.8

func NewAdmission(max int) *Admission

NewAdmission returns an Admission capped at max concurrent in-flight requests. max <= 0 uses DefaultMaxInflight.

func (*Admission) AdaptLimit added in v0.20.0

func (a *Admission) AdaptLimit(ctx context.Context, target time.Duration, load LoadSource)

AdaptLimit adjusts the effective in-flight limit every adaptiveInterval until ctx ends: down while load reports the process CPU-saturated or a scheduler p99 above target, back up toward the hard cap while it doesn't.

func (*Admission) Cap added in v0.9.8

func (a *Admission) Cap() int

Cap reports the hard in-flight cap.

func (*Admission) Collect added in v0.9.8

func (a *Admission) Collect(lc *lifecycle.Context)

Collect is a lifecycle.Collector: it releases the slot this request holds. Runs on every Finalize (which fires at response-body close), so a streamed request holds its slot for the whole stream. Gated on the admit mark so a shed request is a no-op; the non-blocking receive is a belt-and-suspenders guard against ever draining below zero.

func (*Admission) Full added in v0.11.7

func (a *Admission) Full() bool

Full reports whether the requests in flight have reached the effective limit. A lock-free snapshot that takes no slot: a request it lets through can still be shed by PreFlight. Nil-safe (never full).

func (*Admission) Limit added in v0.20.0

func (a *Admission) Limit() int

Limit reports the effective in-flight limit.

func (*Admission) PreFlight added in v0.9.8

PreFlight is a lifecycle.PreFlightMiddleware: it acquires a slot without blocking. On success it marks lc so the Collector knows to release; when the effective limit or the hard cap is reached it counts the shed and returns ErrShed for the dispatch to map to the route's overload answer. A request whose Context can't carry the release mark is admitted rather than held (never take a slot we can't return).

The effective-limit check and the acquire are two steps, so concurrent requests can overshoot the effective limit by a few; the hard cap is exact.

type Load added in v0.20.0

type Load struct {
	CPUShare float64 // process CPU time over the window as a share of GOMAXPROCS
	SchedP99 time.Duration
	Samples  uint64 // scheduler latency samples behind SchedP99
}

Load is one window's CPU-saturation signals.

type LoadSource added in v0.20.0

type LoadSource func() Load

LoadSource returns the Load since its previous call.

func RuntimeLoad added in v0.20.0

func RuntimeLoad() LoadSource

RuntimeLoad reads the process's CPU time and the Go runtime's scheduler latency, counting from the call that creates it.

type SchedLatency added in v0.20.0

type SchedLatency func() (p99 time.Duration, samples uint64)

SchedLatency returns the p99 scheduler latency since its previous call and how many samples it covers.

func RuntimeSchedLatency added in v0.20.0

func RuntimeSchedLatency() SchedLatency

RuntimeSchedLatency reads the Go runtime's scheduler latency histogram, counting from the call that creates it.

Directories

Path Synopsis
Package control is the admin-plane HTTP API: /auth/*, CRUD across the catalog and tenancy kinds, /version, /master-key/*, /secret-keys, /reload.
Package control is the admin-plane HTTP API: /auth/*, CRUD across the catalog and tenancy kinds, /version, /master-key/*, /secret-keys, /reload.
Package inference is the data-plane HTTP API: /v1/* and /healthz.
Package inference is the data-plane HTTP API: /v1/* and /healthz.
Package openapitest checks a published OpenAPI document for what clients generated from it need: every operation identified, summarised, described and tagged, and every parameter and schema property described.
Package openapitest checks a published OpenAPI document for what clients generated from it need: every operation identified, summarised, described and tagged, and every parameter and schema property described.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL