api

package
v0.13.0 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: Apache-2.0 Imports: 26 Imported by: 0

Documentation

Overview

Package api provides a chi+Huma REST API server for scafctl. It mirrors all major CLI features with authentication, metrics, tracing, and audit logging.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BuildHumaConfig

func BuildHumaConfig(apiVersion string, appCfg *config.Config) huma.Config

BuildHumaConfig creates a Huma config with OpenAPI info, servers, security schemes, and documentation paths. It is exported so that standalone spec generators (CLI openapi command, MCP tools) produce an identical spec to the live server, including all security scheme definitions. appCfg is optional; when non-nil, OpenAPI server entries are derived from the active APIServer configuration (host, port, TLS) instead of hard-coded defaults.

func FilterItems

func FilterItems[T any](ctx context.Context, items []T, filter string) ([]T, error)

FilterItems applies a CEL filter expression to a slice of items. Each item is passed as the activation variable "item". Struct items are normalized to map[string]any (keyed by JSON tag names) so that CEL expressions like item.name work consistently. A cost limit is enforced to prevent DoS via expensive user-supplied expressions. Returns the filtered slice and any error from expression evaluation.

func HandleError

func HandleError(ctx context.Context, err error, operation string, statusCode int, userMessage string) error

HandleError logs the error and returns a Huma error with the given status code. For 5xx status codes the raw error is never included in the response body to prevent leaking internal implementation details, stack traces, or file paths.

func HandleValidationError

func HandleValidationError(_ context.Context, fieldName, message string) error

HandleValidationError returns a 422 Unprocessable Entity for validation failures.

func InternalError

func InternalError(ctx context.Context, err error, operation string) error

InternalError returns a 500 Internal Server Error.

func NotFoundError

func NotFoundError(resource, identifier string) error

NotFoundError returns a 404 Not Found error.

func Paginate

func Paginate[T any](items []T, page, perPage int) []T

Paginate returns a slice of items for the given page and per-page size.

func SetLastModified

func SetLastModified(w http.ResponseWriter, t time.Time)

SetLastModified sets the Last-Modified header on the response.

func SetupMiddleware

func SetupMiddleware(ctx context.Context, router *chi.Mux, cfg *config.APIServerConfig, lgr logr.Logger) (chi.Router, error)

SetupMiddleware configures the middleware stack on the root router.

Global middleware (logging, recovery, request ID, strip-slashes) runs for every request, including health probes and the /metrics endpoint.

API-specific middleware (authentication, rate limiting, security headers, compression, metrics instrumentation, etc.) is scoped to versioned paths (e.g. /v1/*) via makeVersionedOnly so that health probes and /metrics are never blocked or instrumented by the per-request Metrics() middleware.

Because Huma is backed by the same root router, every route registered with huma.Register runs through the full middleware chain assembled here. Returns the root router for API-router compatibility with callers.

Types

type ComponentStatus

type ComponentStatus struct {
	Name    string `json:"name" maxLength:"100" doc:"Component name"`
	Status  string `json:"status" maxLength:"20" doc:"Component status"`
	Message string `json:"message,omitempty" maxLength:"500" doc:"Status message"`
}

ComponentStatus describes the health of a single component.

type FilterParam

type FilterParam struct {
	Filter string `query:"filter" maxLength:"2000" doc:"CEL filter expression"`
}

FilterParam provides an optional CEL filter expression.

type HandlerContext

type HandlerContext struct {
	Config           *config.Config
	ProviderRegistry *provider.Registry
	AuthRegistry     *auth.Registry
	Logger           logr.Logger
	IsShuttingDown   *int32
	StartTime        time.Time
}

HandlerContext provides shared dependencies to all API handlers. All handlers access scafctl domain packages through this struct.

func NewHandlerContext

func NewHandlerContext(
	cfg *config.Config,
	providerReg *provider.Registry,
	authReg *auth.Registry,
	logger logr.Logger,
	isShuttingDown *int32,
	startTime time.Time,
) *HandlerContext

NewHandlerContext creates a new HandlerContext with the given dependencies.

func (*HandlerContext) ShuttingDown

func (hc *HandlerContext) ShuttingDown() bool

ShuttingDown returns true if the server is in graceful shutdown. Returns false when IsShuttingDown is nil (e.g., for export/spec contexts).

type HealthResponse

type HealthResponse struct {
	Body HealthResponseBody
}

HealthResponse wraps the health response for Huma.

type HealthResponseBody

type HealthResponseBody struct {
	Status     string            `json:"status" maxLength:"20" example:"healthy" doc:"Overall health status"`
	Version    string            `json:"version" maxLength:"50" doc:"Server version"`
	Uptime     string            `json:"uptime" maxLength:"50" doc:"Server uptime"`
	Components []ComponentStatus `json:"components,omitempty" maxItems:"50" doc:"Component health statuses"`
}

HealthResponseBody is the response body for the /health endpoint.

type Link struct {
	Href string `json:"href" maxLength:"2048" doc:"Link URL"`
	Rel  string `json:"rel" maxLength:"100" doc:"Link relation"`
}

Link represents a HATEOAS-style link.

type PaginationInfo

type PaginationInfo struct {
	Page       int  `json:"page" minimum:"1" maximum:"10000" example:"1" doc:"Current page number (1-indexed)"`
	PerPage    int  `json:"per_page" minimum:"1" maximum:"1000" example:"100" doc:"Items per page"`
	TotalItems int  `json:"total_items" doc:"Total number of items"`
	TotalPages int  `json:"total_pages" doc:"Total number of pages"`
	HasMore    bool `json:"has_more" doc:"Whether more pages exist"`
}

PaginationInfo describes the pagination state in a list response.

func NewPaginationInfo

func NewPaginationInfo(totalItems, page, perPage int) PaginationInfo

NewPaginationInfo creates a PaginationInfo from total count and params.

type PaginationParams

type PaginationParams struct {
	Page    int `query:"page" minimum:"1" maximum:"10000" example:"1" doc:"Page number (1-indexed)"`
	PerPage int `query:"per_page" minimum:"1" maximum:"1000" example:"100" doc:"Items per page"`
}

PaginationParams are the standard query parameters for paginated list endpoints.

type RootResponse

type RootResponse struct {
	Body RootResponseBody
}

RootResponse wraps the root response for Huma.

type RootResponseBody

type RootResponseBody struct {
	Name    string `json:"name" maxLength:"100" doc:"API name"`
	Version string `json:"version" maxLength:"50" doc:"API version"`
	Links   []Link `json:"links,omitempty" maxItems:"50" doc:"Available endpoints"`
}

RootResponseBody is the response body for the API root endpoint.

type Server

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

Server is the REST API server backed by chi and Huma.

func NewServer

func NewServer(opts ...ServerOption) (*Server, error)

NewServer creates a new API server with the given options.

func (*Server) API

func (s *Server) API() huma.API

API returns the Huma API instance for endpoint registration. Panics if called before InitAPI().

func (*Server) APIRouter

func (s *Server) APIRouter() chi.Router

APIRouter returns the API route group. Falls back to the root router if unset.

func (*Server) Config

func (s *Server) Config() *config.Config

Config returns the server's application config.

func (*Server) Context

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

Context returns the server's cancellable context. It is cancelled when the server shuts down (Shutdown is called or Start exits). Middleware that launches background goroutines should use this context rather than the outer cobra command context so goroutines are stopped as part of server shutdown.

func (*Server) HandlerCtx

func (s *Server) HandlerCtx() *HandlerContext

HandlerCtx returns the handler context for endpoint registration.

func (*Server) InitAPI

func (s *Server) InitAPI()

InitAPI initialises the Huma API on the server's router. It must be called after SetupMiddleware so the router is ready.

func (*Server) IsShuttingDown

func (s *Server) IsShuttingDown() bool

IsShuttingDown returns true if the server is in graceful shutdown.

func (*Server) Router

func (s *Server) Router() *chi.Mux

Router returns the root chi router for global middleware setup.

func (*Server) SetAPIRouter

func (s *Server) SetAPIRouter(r chi.Router)

SetAPIRouter sets the API route group (returned by SetupMiddleware).

func (*Server) Shutdown

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

Shutdown gracefully shuts down the server.

func (*Server) Start

func (s *Server) Start() error

Start starts the HTTP server and blocks until shutdown.

func (*Server) StartTime

func (s *Server) StartTime() time.Time

StartTime returns when the server started.

func (*Server) Version

func (s *Server) Version() string

Version returns the server version string.

type ServerOption

type ServerOption func(*serverConfig)

ServerOption configures the API server.

func WithServerAuthRegistry

func WithServerAuthRegistry(reg *auth.Registry) ServerOption

WithServerAuthRegistry sets the auth registry.

func WithServerConfig

func WithServerConfig(cfg *config.Config) ServerOption

WithServerConfig sets the application config.

func WithServerContext

func WithServerContext(ctx context.Context) ServerOption

WithServerContext sets the base context for the server.

func WithServerLogger

func WithServerLogger(lgr logr.Logger) ServerOption

WithServerLogger sets the logger for the API server.

func WithServerRegistry

func WithServerRegistry(reg *provider.Registry) ServerOption

WithServerRegistry sets the provider registry.

func WithServerVersion

func WithServerVersion(version string) ServerOption

WithServerVersion sets the server version string.

type StatusResponse

type StatusResponse struct {
	Body struct {
		Status string `json:"status" maxLength:"20" example:"ok" doc:"Status"`
	}
}

StatusResponse is a minimal status response (e.g., for liveness).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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