api

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 48 Imported by: ? modules, 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 api serves the relay proxy HTTP API, its OpenAPI document and its server lifecycle.

Index

Constants

View Source
const DefaultUnixSocketMode fs.FileMode = 0o660

DefaultUnixSocketMode is the mode of the socket file when the settings give none: read and write for the owner and the group.

Variables

View Source
var ErrCut = errors.New("the server was closed hard, the requests in flight were cut")

ErrCut is wrapped by the error of Server.Shutdown when the context ended before the servers stopped: they were closed hard and the requests still in flight were cut.

View Source
var ErrNotASocket = errors.New("the path exists and is not a socket")

ErrNotASocket is wrapped by the error of ListenUnix when the path exists and is not a socket. The file is left alone: the relay never removes a regular file or a directory.

Functions

func ListenUnix added in v0.2.0

func ListenUnix(ctx context.Context, path string, mode fs.FileMode) (net.Listener, error)

ListenUnix binds a unix socket at path with the permission bits mode and returns its listener.

A stale socket at path (a socket file left by a process that did not clean up) is removed first. Anything else at path, a regular file or a directory, is not touched and ErrNotASocket is returned.

The mode is applied before the socket can be reached under path: the socket is bound inside a private directory (0700) next to path, given its mode there, and then renamed to path, so no client ever sees it with the mode that the umask of the process would give. The listener removes the file at path when it is closed, if it is still a socket.

func OpenAPI added in v0.2.0

func OpenAPI() *huma.OpenAPI

OpenAPI returns the OpenAPI document of the relay proxy, generated from the operations it registers.

func OpenAPIJSON added in v0.2.0

func OpenAPIJSON() ([]byte, error)

OpenAPIJSON returns the OpenAPI document as it is committed in the golden file: indented JSON, with a newline at the end.

Types

type AuthMiddlewareType

type AuthMiddlewareType = string

AuthMiddlewareType is the kind of authentication middleware of the API.

const (
	// UserAuth is the authentication middleware that checks user API keys.
	UserAuth AuthMiddlewareType = "USER"
	// AdminAuth is the authentication middleware that checks the admin API key.
	AdminAuth AuthMiddlewareType = "ADMIN"
)

type ListenFunc added in v0.2.0

type ListenFunc func(ctx context.Context, network, address string) (net.Listener, error)

ListenFunc binds an address; the default binds with net.ListenConfig.

type Option

type Option func(*Server)

Option customizes the Server that New creates.

func WithExit added in v0.2.0

func WithExit(exit func()) Option

WithExit sets what the server does after it logged a fatal error (a failed bind, ...). The default does nothing more: the server stops serving and the caller decides. The relay proxy exits the process with the status 1, a test ends the goroutine of the server only.

func WithFlagSetResolver added in v0.2.0

func WithFlagSetResolver(resolver service.FlagSetResolver) Option

WithFlagSetResolver makes the server find the flag set of an API key with the resolver: this is how the evaluation API is served from the config v2 core. The monitoring service and the metrics come from the services.

func WithGlobalTelemetry

func WithGlobalTelemetry() Option

WithGlobalTelemetry makes the server install its OpenTelemetry tracer provider, error handler and propagator as the process-wide ones when it starts. Only the startup wiring (main) asks for it: the OpenTelemetry API has no other way to give a provider to the instrumented libraries.

func WithListenFunc added in v0.2.0

func WithListenFunc(listen ListenFunc) Option

WithListenFunc replaces the binding of the configured addresses. A test that checks the address the server binds gives it a function that records the address and returns a listener that is already bound.

func WithListener

func WithListener(l net.Listener) Option

WithListener makes the HTTP server serve on an already bound listener instead of binding the configured address. A caller that needs a free port keeps it bound until the server uses it, instead of closing it and hoping that nothing else takes the port before the server binds it. The server owns the listener: it closes it when it stops, or when it is stopped before it started.

func WithMeterProvider added in v0.2.0

func WithMeterProvider(provider metric.MeterProvider) Option

WithMeterProvider sets the meter provider of the HTTP server metrics of the requests (the metrics that the tracing middleware reports). Without it the server uses the one of its OpenTelemetry service.

func WithMonitoringListener

func WithMonitoringListener(l net.Listener) Option

WithMonitoringListener is WithListener for the monitoring server: it serves on the given bound listener instead of binding the configured monitoring port. The monitoring port must still be configured (it decides whether a monitoring server exists). The server owns the listener.

func WithReadTimeout added in v0.2.0

func WithReadTimeout(d time.Duration) Option

WithReadTimeout sets how long a request may take to be read, its body included: the servers close the connection of a client that is slower. The default is 30 seconds, the uploads (data collector, flag configuration) are bound by the same duration. A duration of zero or less means no bound at all, for the servers and for the uploads: it is for an embedder that bounds the reads elsewhere (a proxy in front, a test), the relay proxy itself never sets it.

func WithStartupStep added in v0.2.0

func WithStartupStep(step func(ctx context.Context)) Option

WithStartupStep adds a step that Server.StartWithContext runs after the tracing initialisation and before the servers serve; ctx ends when a stop is requested. A test uses it to hold the start.

func WithTracing added in v0.2.0

func WithTracing(provider trace.TracerProvider, propagator propagation.TextMapPropagator) Option

WithTracing sets the tracer provider and the propagator of the spans of the requests. Without it the server uses the global ones of OpenTelemetry (the ones the telemetry installed at startup).

type Server

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

Server is the struct that represents the API server.

func New

func New(settings *Settings,
	keys service.APIKeys,
	services *service.Services,
	logger *slog.Logger,
	opts ...Option,
) Server

New is used to create a new instance of the API server.

func (*Server) Handler added in v0.2.0

func (s *Server) Handler() http.Handler

Handler returns the handler that serves the API listener.

func (*Server) Shutdown added in v0.2.0

func (s *Server) Shutdown(ctx context.Context) error

Shutdown stops the servers gracefully: the listeners close and the requests in flight finish. When ctx ends first the servers close hard, the requests still in flight are cut, and the error says so (it wraps ErrCut).

func (*Server) StartWithContext

func (s *Server) StartWithContext(ctx context.Context)

StartWithContext starts the server and stops it when ctx is done.

func (*Server) Stop

func (s *Server) Stop(ctx context.Context)

Stop shuts the API server down. It waits for StartWithContext to return (servers drained) or for ctx to be done; a ctx without a deadline is bounded by [gracefulShutdownTimeout], so that a caller that passes context.Background does not wait for ever.

type ServerMode added in v0.2.0

type ServerMode = string

ServerMode is the mode the server runs in.

const (
	// ServerModeHTTP is the HTTP server mode, the default.
	ServerModeHTTP ServerMode = "http"
	// ServerModeUnixSocket is the Unix Socket server mode.
	ServerModeUnixSocket ServerMode = "unixsocket"
)

type Settings added in v0.2.0

type Settings struct {
	// Version is the version of the relay proxy, reported by the version header, the logs and the OpenAPI document.
	Version string
	// Mode is the server mode: http or unixsocket.
	Mode ServerMode
	// Host is the host the API and the monitoring listeners bind.
	Host string
	// MonitoringHost is the host the monitoring (ops) listener binds, empty for every interface; nil means Host, the
	// way it was before the ops listener had an address of its own.
	MonitoringHost *string
	// UnixSocketMode is the permission bits of the socket file, applied before the socket can be reached; nil means
	// [DefaultUnixSocketMode], and a pointer to 0 is a socket nobody but root can open.
	UnixSocketMode *fs.FileMode
	// UnixSocketPath is the path of the socket in the unix socket mode.
	UnixSocketPath string
	// TLS makes the API listener serve TLS, nil for cleartext. The unix socket never does.
	TLS *TLS
	// MonitoringTLS is the same for the monitoring listener.
	MonitoringTLS *TLS
	// OfrepEventStream is what the OFREP bulk evaluation advertises of the stream of flag changes.
	OfrepEventStream ofrep.EventStream
	// Telemetry is the OpenTelemetry configuration.
	Telemetry opentelemetry.Settings
	// ValidateFlags are the body size limits of the validate flags endpoint.
	ValidateFlags controller.ValidateFlagsLimits
	// Port is the port of the API listener.
	Port int
	// MonitoringPort is the port of the dedicated monitoring listener, 0 when the API listener serves the
	// monitoring endpoints.
	MonitoringPort int
	// EnableH2C makes the API listener accept HTTP/2 over cleartext.
	EnableH2C bool
	// Debug is the debug log level: the errors of the requests carry their details.
	Debug bool
	// Swagger serves the Swagger UI and the OpenAPI document.
	Swagger bool
	// Pprof serves the pprof endpoints on the monitoring listener, never on the API listener: it has no effect
	// without a monitoring port.
	Pprof bool
	// ExposeLegacyMetrics exposes the metrics under their legacy names too.
	ExposeLegacyMetrics bool
	// DisableVersionHeader removes the version headers of the responses.
	DisableVersionHeader bool
	// DisableSemaphoreMetadata keeps the Semaphore keys out of the metadata of the OFREP evaluations.
	DisableSemaphoreMetadata bool
}

Settings is what the HTTP layer reads of the configuration of the relay proxy: the listeners, the optional endpoints, the toggles of the middleware and the telemetry. It is built once at startup, its values are final (the defaults and the deprecated aliases are resolved), and the server never changes it. What changes at reload, the API keys, is not here: see service.APIKeys.

type TLS added in v0.2.0

type TLS struct {
	// Now is the clock of the reload interval, [clock.Now] when nil.
	Now func() time.Time
	// CertFile and KeyFile are the PEM files of the certificate chain and of the key.
	CertFile, KeyFile string
	// MinVersion is the lowest TLS version accepted (a crypto/tls constant), TLS 1.2 when zero.
	MinVersion uint16
	// HTTP2 serves HTTP/2 over TLS next to HTTP/1.1 (the protocol h2); without it the listener is HTTPS with HTTP/1.1.
	HTTP2 bool
}

TLS is the certificate of a listener. The server reads the files at start (a failure stops the start) and looks at them again when a handshake finds tlscert.DefaultInterval over since the last look.

Directories

Path Synopsis
Package middleware holds the HTTP middleware of the relay proxy, as plain http.Handler wrappers.
Package middleware holds the HTTP middleware of the relay proxy, as plain http.Handler wrappers.
Package opentelemetry sets up the OpenTelemetry metrics and tracing of the relay proxy.
Package opentelemetry sets up the OpenTelemetry metrics and tracing of the relay proxy.

Jump to

Keyboard shortcuts

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