adapter

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: 22 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 adapter provides the generic adapter framework: a Spec type that bundles wire-shape metadata (inbound URL paths, upstream URL path, auth strategy, canonical translator, token extractor), a generic pipeline.Adapter implementation parameterised by path and auth strategy, a Registry of Specs, and a generic route mounter that iterates registered specs.

This package is the composition root's extension point: to add a new wire shape, add one Spec to internal/adapterspecs. No branching in dispatch; no per-shape packages inside app/.

Deliberately out of scope:

  • Provider-catalog data (lives in wyolet/relay-catalog)
  • The canonical v1.Translator interface (lives in pkg/relay/v1)
  • The OLD app/adapters.Translator interface (deleted in PR 5)

Index

Constants

View Source
const MaxCountBody = 8 << 10

MaxCountBody bounds the counting endpoint's response read. The reply is a single small JSON object, so anything larger is an error page or a hostile upstream and must not be buffered whole.

Variables

View Source
var ErrNoOrgHeader = errors.New("adapter: the upstream's answer names no organization")

ErrNoOrgHeader is a probe the upstream answered without naming an organization, as an upstream serving the same shape for another provider does.

View Source
var ErrNoOrgProbe = errors.New("adapter: the upstream does not name a credential's organization")

ErrNoOrgProbe is a probe of a shape whose upstream names no organization.

Functions

func NewUpstreamTransport added in v0.9.8

func NewUpstreamTransport(http1 bool) http.RoundTripper

NewUpstreamTransport builds the tuned upstream transport. http1 empties TLSNextProto on the same tuned base to disable HTTP/2 negotiation for shapes that trip Go's HTTP/2 client bugs (see Spec.UseHTTP1). Exported for the composition root, which applies the same pooling to the proxy runner's client (its upstreams are just as hot as the pipeline's).

The returned RoundTripper wraps the transport with connection-reuse accounting (relay_upstream_connections_total) — the tripwire for the MaxIdleConnsPerHost-style churn this pooling exists to prevent.

func ParseTokenCount added in v0.10.1

func ParseTokenCount(status int, raw []byte) (int, error)

ParseTokenCount reads the counting endpoint's reply. A non-200 status or a reply without a positive count is an error — never a number the caller would take for a measurement.

func SetUpstreamDialTimeout added in v0.11.7

func SetUpstreamDialTimeout(d time.Duration)

SetUpstreamDialTimeout overrides the upstream connect timeout for every transport built afterwards (the composition root wires RELAY_UPSTREAM_DIAL_TIMEOUT_S here). Values <= 0 are ignored. Not safe to call concurrently with Build — invoke once at boot, before specs are constructed.

func SetUpstreamMaxIdleConnsPerHost added in v0.9.8

func SetUpstreamMaxIdleConnsPerHost(n int)

SetUpstreamMaxIdleConnsPerHost overrides the per-host idle-connection cap used by every Spec built afterwards (the composition root wires the RELAY_UPSTREAM_MAX_IDLE_PER_HOST value here). Values < 1 are ignored so a zero config default leaves the built-in 128. Not safe to call concurrently with Build — invoke once at boot, before specs are constructed.

func SetUpstreamStreamIdleTimeout added in v0.9.20

func SetUpstreamStreamIdleTimeout(d time.Duration)

SetUpstreamStreamIdleTimeout overrides the streamed-response idle deadline for every Spec built afterwards (the composition root wires RELAY_STREAM_IDLE_TIMEOUT_S here). Zero disables the deadline; negative values are ignored. Not safe to call concurrently with Build — invoke once at boot, before specs are constructed.

Types

type AuthStrategy

type AuthStrategy struct {
	// Header is the HTTP header to set (e.g. "Authorization", "x-api-key").
	Header string

	// Scheme is prepended to the key with a space if non-empty
	// (e.g. "Bearer" → "Bearer sk-..."). Empty means no prefix.
	Scheme string

	// ExtraHeaders are static header key/value pairs added unconditionally
	// (e.g. {"anthropic-version": "2023-06-01"}). Only applied when the
	// header is not already present in the forwarded request headers.
	ExtraHeaders map[string]string
}

AuthStrategy configures how an adapter authenticates to the upstream.

type ErrorResponse added in v0.11.7

type ErrorResponse struct {
	Status int
	Body   []byte
}

ErrorResponse is a complete error answer, written as is.

type InboundPath

type InboundPath struct {
	// Path is the URL path, e.g. "/v1/chat/completions".
	Path string

	// OperationID is the huma operation ID, e.g. "chat_completions".
	OperationID string

	// Summary is the huma operation summary.
	Summary string
}

InboundPath describes one inbound HTTP route for a spec.

type Org added in v0.20.0

type Org struct {
	ID   string
	Name string
}

Org is the organization an upstream named for a credential.

type OrgProbe added in v0.20.0

type OrgProbe struct {
	// Path is the upstream path of a GET any credential of the shape may make and that costs nothing, such as a models list. Like CountPath it is not overridable per host.
	Path string

	// OrgHeader is the response header carrying the organization's id. The upstream sends it on every response, so live traffic can be read for it too.
	OrgHeader string

	// NameHeader is the response header carrying the organization's display name; empty when the upstream sends none.
	NameHeader string
}

OrgProbe is how a shape's upstream names the organization a credential belongs to: a cheap read to make, and the response headers carrying the organization.

type ProbeStatusError added in v0.20.0

type ProbeStatusError struct {
	Status int
}

ProbeStatusError is a probe the upstream answered with a status other than 2xx.

func (*ProbeStatusError) Error added in v0.20.0

func (e *ProbeStatusError) Error() string

type Registry

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

Registry holds all registered adapter specs. Built once at boot in cmd/relay via NewRegistry over internal/adapterspecs. Read-only after construction.

func NewRegistry

func NewRegistry(specs ...*Spec) *Registry

NewRegistry constructs a Registry from the given specs. Each spec must have had Build() called. Panics if two specs share the same Name.

func (*Registry) AdapterMap

func (r *Registry) AdapterMap() map[adapters.Name]pipeline.Adapter

AdapterMap returns a map[adapters.Name]pipeline.Adapter for all registered specs. The returned map is a copy; mutation does not affect the registry.

func (*Registry) AssertWired

func (r *Registry) AssertWired() error

AssertWired verifies the composition root registered a coherent set of specs, so the defensive "no spec / no adapter / no translator" 500s in the dispatch path are structurally unreachable. The composition root calls this at boot and fails fast on a violation — a wiring bug must crash the binary, never surface as a runtime request error.

It enforces two invariants:

  • Every upstream-binding adapter (the allow-set HostBinding.Adapter is validated against) has a registered spec with a non-nil pipeline adapter to dispatch to.
  • Every inbound, non-byte-pass spec has a canonical Translator, so a cross-shape route can always translate.

func (*Registry) PipelineAdapter

func (r *Registry) PipelineAdapter(name adapters.Name) pipeline.Adapter

PipelineAdapter returns the pipeline.Adapter for the given name, or nil.

func (*Registry) Spec

func (r *Registry) Spec(name adapters.Name) *Spec

Spec returns the Spec for the given name, or nil if unregistered.

func (*Registry) Specs

func (r *Registry) Specs() []*Spec

Specs returns all registered specs in registration order.

func (*Registry) TranslatorMap

func (r *Registry) TranslatorMap() v1.Registry

TranslatorMap returns a v1.Registry (map[v1.Name]v1.Translator) for all specs that have a non-nil Translator. Specs with BytePass=true and nil Translator are omitted — they have no canonical translator.

type Spec

type Spec struct {
	// Name is the wire-protocol identifier, matching adapters.Name values.
	// Used as the key in the Registry and as the DispatchInput.Inbound value.
	Name adapters.Name

	// InboundPaths is the set of inbound HTTP paths this spec owns.
	// Each entry is registered as a POST route via the generic mounter.
	// Example: ["/v1/chat/completions", "/openai/v1/chat/completions"].
	InboundPaths []InboundPath

	// DefaultPath is the shape-canonical upstream path, used when the host
	// doesn't set its own (Host.Spec.Path, which wins verbatim — including
	// an explicit ""). Example: "/v1/chat/completions", "/v1/responses".
	// Ignored when UpstreamPathFn is set.
	DefaultPath string

	// UpstreamPathFn resolves the upstream path per request from the upstream
	// model name and the sync/stream choice. Set only for shapes that encode
	// the model and/or stream selection in the URL rather than the body —
	// Gemini's "/v1beta/models/{model}:generateContent" vs
	// ":streamGenerateContent". When nil, DefaultPath is used verbatim.
	// upstreamModel arrives escaped as a single path segment.
	UpstreamPathFn func(upstreamModel string, stream bool) string

	// CountPath is the upstream path that counts a request's input tokens without generating, e.g. "/v1/messages/count_tokens". Set only for vendors that expose one: it is what makes this spec's pipeline.Adapter a TokenCounter, and an empty value means relay must estimate instead.
	//
	// Unlike DefaultPath it is not overridable per host — Host.Spec.Path rewrites the generation path only — so on a host that relocates the whole API the count request still goes to the shape's own location, and the mismatch surfaces as an upstream error rather than as a wrong number.
	CountPath string

	// Org is how this shape's upstream names the organization a credential belongs to. Nil when the upstream names none.
	Org *OrgProbe

	// Auth configures how the upstream is authenticated with an API-key
	// credential (the default).
	Auth AuthStrategy

	// OAuthAuth is the alternate auth used when the resolved credential is an
	// OAuth token (HostKey value-kind "oauth") rather than an API key — e.g.
	// Anthropic subscription tokens go out as `Authorization: Bearer …` + the
	// oauth beta header instead of `x-api-key`. A zero value (empty Header)
	// means the spec has no OAuth variant and Auth is used for every credential.
	// Selecting it keeps the binding on the same wire shape (so same-shape
	// byte-pass still applies); only the upstream auth headers differ.
	OAuthAuth AuthStrategy

	// Translator is the canonical v1.Translator for this shape. Used by
	// the standard dispatch chain (inbound→canonical→upstream and back).
	// Nil means this shape has no canonical translator (e.g. byte-pass-only).
	Translator v1.Translator

	// BytePass signals that this shape is always byte-equivalent with its
	// upstream (no cross-shape translation is ever needed). Embeddings is
	// the canonical example: it's a direct passthrough to any OpenAI-compat
	// host and there is no canonical embeddings type.
	//
	// When true, Translator is unused even if set.
	BytePass bool

	// ExtractTokens extracts usage tokens from the upstream response body.
	// If nil, the adapter returns nil tokens (no usage tracking).
	ExtractTokens func(body []byte) pkgusage.Tokens

	// StreamUsage is set for shapes whose streams report token usage only
	// when the request asks for it. Nil when the stream always carries usage.
	StreamUsage *StreamUsageOptIn

	// UseHTTP1 disables HTTP/2 negotiation on the upstream transport.
	// Necessary for endpoints that trigger Go's HTTP/2 client bugs (e.g.
	// OpenAI /v1/responses sends GOAWAY mid-request over HTTP/2).
	UseHTTP1 bool

	// ParamPaths maps canonical sampling-param names ("temperature",
	// "top_p", "top_k") to their dot-separated location in this shape's
	// request JSON (e.g. "temperature" top-level for the OpenAI/Anthropic
	// shapes, "generationConfig.temperature" for Gemini). Used by the
	// byte-pass dispatch to strip params a routed model declares
	// unsupported without invoking the translator; params absent from the
	// map cannot be stripped on the byte-pass path. Wire-shape knowledge,
	// so it lives here on the Spec literal (composition root), not in
	// dispatch code.
	ParamPaths map[string]string

	// IsNativePath reports whether a route hop's binding and host imply that the
	// upstream host natively speaks this inbound shape — making byte-pass to
	// this spec's UpstreamPath the correct strategy, regardless of whether
	// the host's HostBinding.Adapter matches the inbound shape Name.
	//
	// The canonical use case: OpenAIResponses inbound. The spec's Name is
	// "openai_responses" but the host's HostBinding.Adapter is "openai".
	// OpenAI-proper hosts speak the Responses API natively, so when this
	// predicate returns true (host Name == "openai") the dispatch byte-passes
	// to /v1/responses via this spec's adapter. Non-openai hosts return false
	// and dispatch falls through to the canonical cross-shape chain.
	//
	// For shapes where the inbound Name equals the binding Adapter (CC, Anthropic,
	// Embeddings), this field is nil — the standard Name-equality check handles it.
	IsNativePath func(b *binding.Binding, h *host.Host) bool

	// Overloaded is how this shape's callers expect to be told the server is overloaded, sent when relay refuses a request for its own lack of capacity (the in-flight cap, an unreachable state store). Nil means 503 in relay's error envelope.
	Overloaded *ErrorResponse
	// contains filtered or unexported fields
}

Spec describes one inbound wire shape and its upstream call semantics. One Spec registration = one inbound URL surface + one upstream path.

The three OpenAI shapes (CC, Responses, Embeddings) are three Specs. The Anthropic shape is one Spec. A future Gemini shape would be one Spec.

func (*Spec) Build

func (s *Spec) Build() *Spec

Build finalises the Spec by constructing its shared HTTP client and snapshotting the per-call deadlines. The client pools upstream connections via a tuned transport (per-host idle ceiling from SetUpstreamMaxIdleConnsPerHost).

It carries no Client.Timeout: that is a whole-request cap, which would kill any generation streamed for longer than it — the header wait is bounded by the transport instead, and streamed bodies by the idle deadline.

Must be called once after all fields are set, before the spec is added to a Registry. Returns s for chaining.

func (*Spec) PipelineAdapter

func (s *Spec) PipelineAdapter() pipeline.Adapter

PipelineAdapter returns a pipeline.Adapter backed by this spec's upstream path and auth strategy. The returned value is safe for concurrent use.

A spec declaring a CountPath gets the variant that also satisfies TokenCounter, so a caller's type assertion answers "does this upstream count tokens for us" without consulting the spec.

func (*Spec) ProbeOrg added in v0.20.0

func (s *Spec) ProbeOrg(ctx context.Context, baseURL, apiKey string, oauth bool) (Org, error)

ProbeOrg asks the upstream at baseURL which organization apiKey belongs to: one GET of Org.Path, authenticated as a generation is and capped by the same sync timeout.

func (*Spec) RequestKeys added in v0.11.7

func (s *Spec) RequestKeys() v1.RequestKeys

RequestKeys returns the top-level request members the shape's translator names, zero for a shape without one.

type StreamUsageOptIn added in v0.10.1

type StreamUsageOptIn struct {
	// Request returns the top-level member to set for the opt-in, reading the
	// request's members through member (nil when absent); ok is false when the
	// caller already asked or the request is not streamed.
	Request func(member func(key string) []byte) (key string, value []byte, ok bool)

	// IsUsageFrame reports whether an SSE frame (separator stripped) is the
	// extra usage-only frame the opt-in adds.
	IsUsageFrame func(frame []byte) bool
}

StreamUsageOptIn is how byte-pass asks a stream for its usage on the caller's behalf and hides the answer from a caller that did not ask.

type TokenCounter added in v0.9.20

type TokenCounter interface {
	// CountAdapter returns the pipeline.Adapter whose Call posts to the upstream's counting endpoint, so a count runs through Pipeline.Run and is reserved, key-selected and failed over exactly like a generation.
	CountAdapter() pipeline.Adapter
}

TokenCounter is the optional capability of a pipeline.Adapter whose upstream counts a request's input tokens exactly. Callers type-assert for it and fall back to their own estimate when the assertion fails — so it stays off pipeline.Adapter itself, which every shape must implement.

Jump to

Keyboard shortcuts

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