shared

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const CacheKey = "forge.cache"
View Source
const CacheManagerKey = "forge.cache.manager"
View Source
const CacheServiceKey = "forge.cache.service"
View Source
const CacheWarmer = "forge.cache.warmer"
View Source
const ConfigKey = "forge.config.manager"
View Source
const ContainerKey = "forge.container"
View Source
const DatabaseConnectionKey = "forge.database.connection"
View Source
const DatabaseKey = "forge.database"
View Source
const DatabaseManagerKey = "forge.database.manager"
View Source
const DatabaseRedisClientKey = "forge.database.redis.client"
View Source
const ErrorHandlerKey = "forge.error.handler"
View Source
const EventBusKey = "forge.event.bus"
View Source
const HealthCheckerKey = "forge.health.checker"
View Source
const HealthServiceKey = "forge.health.service"
View Source
const LifecycleManagerKey = "forge.lifecycle.manager"
View Source
const LoggerKey = "forge.logger"
View Source
const MetricsCollectorKey = MetricsKey
View Source
const MetricsKey = "forge.metrics.service"
View Source
const MiddlewareManagerKey = "forge.middleware.manager"
View Source
const PluginManagerKey = "forge.plugin.manager"
View Source
const StreamManagerKey = "forge.stream.manager"
View Source
const StreamingServiceKey = "forge.stream.service"

Variables

This section is empty.

Functions

func ErrContainerError

func ErrContainerError(operation string, cause error) *ferrors.ForgeError

ErrContainerError preserves compatibility for code expecting common.ErrContainerError in v0. There is no direct equivalent code in v2 errors; we map it to a lifecycle error for now.

func ErrContextCancelled

func ErrContextCancelled(operation string) *ferrors.ForgeError

func ErrHealthCheckFailed

func ErrHealthCheckFailed(serviceName string, cause error) *ferrors.ForgeError

func ErrInvalidConfig

func ErrInvalidConfig(configKey string, cause error) *ferrors.ForgeError

func ErrLifecycleError

func ErrLifecycleError(phase string, cause error) *ferrors.ForgeError

func ErrServiceAlreadyExists

func ErrServiceAlreadyExists(serviceName string) *ferrors.ForgeError

func ErrServiceNotFound

func ErrServiceNotFound(serviceName string) *ferrors.ForgeError

func ErrServiceStartFailed

func ErrServiceStartFailed(serviceName string, cause error) *ferrors.ForgeError

func ErrServiceStopFailed

func ErrServiceStopFailed(serviceName string, cause error) *ferrors.ForgeError

ErrServiceStopFailed preserves compatibility; map to lifecycle stop error

func ErrTimeoutError

func ErrTimeoutError(operation string, timeout time.Duration) *ferrors.ForgeError

func ErrValidationError

func ErrValidationError(field string, cause error) *ferrors.ForgeError

Types

type AsyncAPIChannel

type AsyncAPIChannel struct {
	Address      string                        `json:"address,omitempty"` // Channel address (can include params)
	Messages     map[string]*AsyncAPIMessage   `json:"messages,omitempty"`
	Title        string                        `json:"title,omitempty"`
	Summary      string                        `json:"summary,omitempty"`
	Description  string                        `json:"description,omitempty"`
	Servers      []AsyncAPIServerReference     `json:"servers,omitempty"`
	Parameters   map[string]*AsyncAPIParameter `json:"parameters,omitempty"`
	Tags         []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings     *AsyncAPIChannelBindings      `json:"bindings,omitempty"`
}

AsyncAPIChannel represents a channel in the AsyncAPI spec

type AsyncAPIChannelBindings

type AsyncAPIChannelBindings struct {
	WS   *WebSocketChannelBinding `json:"ws,omitempty"`
	HTTP *HTTPChannelBinding      `json:"http,omitempty"`
}

AsyncAPIChannelBindings contains protocol-specific channel bindings

type AsyncAPIChannelReference

type AsyncAPIChannelReference struct {
	Ref string `json:"$ref" yaml:"$ref"` // #/channels/channelName
}

AsyncAPIChannelReference references a channel

type AsyncAPIComponents

type AsyncAPIComponents struct {
	Schemas           map[string]*Schema                    `json:"schemas,omitempty"`
	Servers           map[string]*AsyncAPIServer            `json:"servers,omitempty"`
	Channels          map[string]*AsyncAPIChannel           `json:"channels,omitempty"`
	Operations        map[string]*AsyncAPIOperation         `json:"operations,omitempty"`
	Messages          map[string]*AsyncAPIMessage           `json:"messages,omitempty"`
	SecuritySchemes   map[string]*AsyncAPISecurityScheme    `json:"securitySchemes,omitempty"`
	Parameters        map[string]*AsyncAPIParameter         `json:"parameters,omitempty"`
	CorrelationIDs    map[string]*AsyncAPICorrelationID     `json:"correlationIds,omitempty"`
	OperationTraits   map[string]*AsyncAPIOperationTrait    `json:"operationTraits,omitempty"`
	MessageTraits     map[string]*AsyncAPIMessageTrait      `json:"messageTraits,omitempty"`
	ServerBindings    map[string]*AsyncAPIServerBindings    `json:"serverBindings,omitempty"`
	ChannelBindings   map[string]*AsyncAPIChannelBindings   `json:"channelBindings,omitempty"`
	OperationBindings map[string]*AsyncAPIOperationBindings `json:"operationBindings,omitempty"`
	MessageBindings   map[string]*AsyncAPIMessageBindings   `json:"messageBindings,omitempty"`
}

AsyncAPIComponents holds reusable objects for the API spec

type AsyncAPIConfig

type AsyncAPIConfig struct {
	// Basic info
	Title       string
	Description string
	Version     string

	// AsyncAPI version (default: "3.0.0")
	AsyncAPIVersion string

	// Server configuration
	Servers map[string]*AsyncAPIServer

	// Default content type for messages
	DefaultContentType string // Default: "application/json"

	// External docs, contact, license (reuse OpenAPI types)
	ExternalDocs *ExternalDocs
	Contact      *Contact
	License      *License

	// UI configuration
	UIPath      string // Default: "/asyncapi"
	SpecPath    string // Default: "/asyncapi.json"
	UIEnabled   bool   // Default: true
	SpecEnabled bool   // Default: true

	// Generation options
	PrettyJSON          bool
	IncludeExamples     bool
	IncludeDescriptions bool
}

AsyncAPIConfig configures AsyncAPI 3.0.0 generation

type AsyncAPICorrelationID

type AsyncAPICorrelationID struct {
	Description string `json:"description,omitempty"`
	Location    string `json:"location"` // Runtime expression like $message.header#/correlationId
}

AsyncAPICorrelationID specifies a correlation ID for request-reply patterns

type AsyncAPIInfo

type AsyncAPIInfo struct {
	Title          string        `json:"title"`
	Description    string        `json:"description,omitempty"`
	Version        string        `json:"version"`
	TermsOfService string        `json:"termsOfService,omitempty"`
	Contact        *Contact      `json:"contact,omitempty"`
	License        *License      `json:"license,omitempty"`
	Tags           []AsyncAPITag `json:"tags,omitempty"`
	ExternalDocs   *ExternalDocs `json:"externalDocs,omitempty"`
}

AsyncAPIInfo provides metadata about the API

type AsyncAPIMessage

type AsyncAPIMessage struct {
	MessageID     string                   `json:"messageId,omitempty"`
	Headers       *Schema                  `json:"headers,omitempty"`
	Payload       *Schema                  `json:"payload,omitempty"`
	CorrelationID *AsyncAPICorrelationID   `json:"correlationId,omitempty"`
	ContentType   string                   `json:"contentType,omitempty"`
	Name          string                   `json:"name,omitempty"`
	Title         string                   `json:"title,omitempty"`
	Summary       string                   `json:"summary,omitempty"`
	Description   string                   `json:"description,omitempty"`
	Tags          []AsyncAPITag            `json:"tags,omitempty"`
	ExternalDocs  *ExternalDocs            `json:"externalDocs,omitempty"`
	Bindings      *AsyncAPIMessageBindings `json:"bindings,omitempty"`
	Examples      []AsyncAPIMessageExample `json:"examples,omitempty"`
	Traits        []AsyncAPIMessageTrait   `json:"traits,omitempty"`
}

AsyncAPIMessage represents a message in the AsyncAPI spec

type AsyncAPIMessageBindings

type AsyncAPIMessageBindings struct {
	WS   *WebSocketMessageBinding `json:"ws,omitempty"`
	HTTP *HTTPMessageBinding      `json:"http,omitempty"`
}

AsyncAPIMessageBindings contains protocol-specific message bindings

type AsyncAPIMessageExample

type AsyncAPIMessageExample struct {
	Name    string                 `json:"name,omitempty"`
	Summary string                 `json:"summary,omitempty"`
	Headers map[string]interface{} `json:"headers,omitempty"`
	Payload interface{}            `json:"payload,omitempty"`
}

AsyncAPIMessageExample represents an example of a message

type AsyncAPIMessageReference

type AsyncAPIMessageReference struct {
	Ref string `json:"$ref" yaml:"$ref"` // #/components/messages/messageName or #/channels/channelName/messages/messageName
}

AsyncAPIMessageReference references a message

type AsyncAPIMessageTrait

type AsyncAPIMessageTrait struct {
	MessageID     string                   `json:"messageId,omitempty"`
	Headers       *Schema                  `json:"headers,omitempty"`
	CorrelationID *AsyncAPICorrelationID   `json:"correlationId,omitempty"`
	ContentType   string                   `json:"contentType,omitempty"`
	Name          string                   `json:"name,omitempty"`
	Title         string                   `json:"title,omitempty"`
	Summary       string                   `json:"summary,omitempty"`
	Description   string                   `json:"description,omitempty"`
	Tags          []AsyncAPITag            `json:"tags,omitempty"`
	ExternalDocs  *ExternalDocs            `json:"externalDocs,omitempty"`
	Bindings      *AsyncAPIMessageBindings `json:"bindings,omitempty"`
	Examples      []AsyncAPIMessageExample `json:"examples,omitempty"`
}

AsyncAPIMessageTrait represents reusable message characteristics

type AsyncAPIOAuthFlows

type AsyncAPIOAuthFlows struct {
	Implicit          *OAuthFlow `json:"implicit,omitempty"`
	Password          *OAuthFlow `json:"password,omitempty"`
	ClientCredentials *OAuthFlow `json:"clientCredentials,omitempty"`
	AuthorizationCode *OAuthFlow `json:"authorizationCode,omitempty"`
}

AsyncAPIOAuthFlows defines OAuth 2.0 flows (compatible with OpenAPI OAuthFlows)

type AsyncAPIOperation

type AsyncAPIOperation struct {
	Action       string                        `json:"action"` // send, receive
	Channel      *AsyncAPIChannelReference     `json:"channel"`
	Title        string                        `json:"title,omitempty"`
	Summary      string                        `json:"summary,omitempty"`
	Description  string                        `json:"description,omitempty"`
	Security     []AsyncAPISecurityRequirement `json:"security,omitempty"`
	Tags         []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings     *AsyncAPIOperationBindings    `json:"bindings,omitempty"`
	Traits       []AsyncAPIOperationTrait      `json:"traits,omitempty"`
	Messages     []AsyncAPIMessageReference    `json:"messages,omitempty"`
	Reply        *AsyncAPIOperationReply       `json:"reply,omitempty"`
}

AsyncAPIOperation represents an operation in the AsyncAPI spec

type AsyncAPIOperationBindings

type AsyncAPIOperationBindings struct {
	WS   *WebSocketOperationBinding `json:"ws,omitempty"`
	HTTP *HTTPOperationBinding      `json:"http,omitempty"`
}

AsyncAPIOperationBindings contains protocol-specific operation bindings

type AsyncAPIOperationReply

type AsyncAPIOperationReply struct {
	Address  *AsyncAPIOperationReplyAddress `json:"address,omitempty"`
	Channel  *AsyncAPIChannelReference      `json:"channel,omitempty"`
	Messages []AsyncAPIMessageReference     `json:"messages,omitempty"`
}

AsyncAPIOperationReply represents the reply configuration for an operation

type AsyncAPIOperationReplyAddress

type AsyncAPIOperationReplyAddress struct {
	Description string `json:"description,omitempty"`
	Location    string `json:"location,omitempty"` // Runtime expression like $message.header#/replyTo
}

AsyncAPIOperationReplyAddress represents the reply address

type AsyncAPIOperationTrait

type AsyncAPIOperationTrait struct {
	Title        string                        `json:"title,omitempty"`
	Summary      string                        `json:"summary,omitempty"`
	Description  string                        `json:"description,omitempty"`
	Security     []AsyncAPISecurityRequirement `json:"security,omitempty"`
	Tags         []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings     *AsyncAPIOperationBindings    `json:"bindings,omitempty"`
}

AsyncAPIOperationTrait represents reusable operation characteristics

type AsyncAPIParameter

type AsyncAPIParameter struct {
	Description string   `json:"description,omitempty"`
	Enum        []string `json:"enum,omitempty"`
	Default     string   `json:"default,omitempty"`
	Examples    []string `json:"examples,omitempty"`
	Location    string   `json:"location,omitempty"` // $message.header, $message.payload
	Schema      *Schema  `json:"schema,omitempty"`
}

AsyncAPIParameter represents a parameter in channel address

type AsyncAPISecurityRequirement

type AsyncAPISecurityRequirement map[string][]string

AsyncAPISecurityRequirement lists required security schemes

type AsyncAPISecurityScheme

type AsyncAPISecurityScheme struct {
	Type             string              `json:"type"` // userPassword, apiKey, X509, symmetricEncryption, asymmetricEncryption, httpApiKey, http, oauth2, openIdConnect
	Description      string              `json:"description,omitempty"`
	Name             string              `json:"name,omitempty"`             // For apiKey and httpApiKey
	In               string              `json:"in,omitempty"`               // For apiKey and httpApiKey: user, password, query, header, cookie
	Scheme           string              `json:"scheme,omitempty"`           // For http: bearer, basic, etc.
	BearerFormat     string              `json:"bearerFormat,omitempty"`     // For http bearer
	Flows            *AsyncAPIOAuthFlows `json:"flows,omitempty"`            // For oauth2
	OpenIdConnectUrl string              `json:"openIdConnectUrl,omitempty"` // For openIdConnect
	Scopes           []string            `json:"scopes,omitempty"`
}

AsyncAPISecurityScheme defines a security scheme

type AsyncAPIServer

type AsyncAPIServer struct {
	Host            string                        `json:"host,omitempty"`
	Protocol        string                        `json:"protocol"` // ws, wss, sse, http, https
	ProtocolVersion string                        `json:"protocolVersion,omitempty"`
	Pathname        string                        `json:"pathname,omitempty"`
	Description     string                        `json:"description,omitempty"`
	Title           string                        `json:"title,omitempty"`
	Summary         string                        `json:"summary,omitempty"`
	Variables       map[string]*ServerVariable    `json:"variables,omitempty"`
	Security        []AsyncAPISecurityRequirement `json:"security,omitempty"`
	Tags            []AsyncAPITag                 `json:"tags,omitempty"`
	ExternalDocs    *ExternalDocs                 `json:"externalDocs,omitempty"`
	Bindings        *AsyncAPIServerBindings       `json:"bindings,omitempty"`
}

AsyncAPIServer represents a server in the AsyncAPI spec

type AsyncAPIServerBindings

type AsyncAPIServerBindings struct {
	WS   *WebSocketServerBinding `json:"ws,omitempty"`
	HTTP *HTTPServerBinding      `json:"http,omitempty"`
}

AsyncAPIServerBindings contains protocol-specific server bindings

type AsyncAPIServerReference

type AsyncAPIServerReference struct {
	Ref string `json:"$ref" yaml:"$ref"` // #/servers/serverName
}

AsyncAPIServerReference references a server

type AsyncAPISpec

type AsyncAPISpec struct {
	AsyncAPI   string                        `json:"asyncapi"` // "3.0.0"
	ID         string                        `json:"id,omitempty"`
	Info       AsyncAPIInfo                  `json:"info"`
	Servers    map[string]*AsyncAPIServer    `json:"servers,omitempty"`
	Channels   map[string]*AsyncAPIChannel   `json:"channels"`
	Operations map[string]*AsyncAPIOperation `json:"operations"`
	Components *AsyncAPIComponents           `json:"components,omitempty"`
	Tags       []AsyncAPITag                 `json:"tags,omitempty"`
	Extensions map[string]interface{}        `json:"-"` // x-* extensions
}

AsyncAPISpec represents the complete AsyncAPI 3.0.0 specification

type AsyncAPITag

type AsyncAPITag struct {
	Name         string        `json:"name"`
	Description  string        `json:"description,omitempty"`
	ExternalDocs *ExternalDocs `json:"externalDocs,omitempty"`
}

AsyncAPITag represents a tag in the AsyncAPI spec

type CollectorStats

type CollectorStats struct {
	Name               string                 `json:"name"`
	Started            bool                   `json:"started"`
	StartTime          time.Time              `json:"start_time"`
	Uptime             time.Duration          `json:"uptime"`
	MetricsCreated     int64                  `json:"metrics_created"`
	MetricsCollected   int64                  `json:"metrics_collected"`
	CustomCollectors   int                    `json:"custom_collectors"`
	ActiveMetrics      int                    `json:"active_metrics"`
	LastCollectionTime time.Time              `json:"last_collection_time"`
	Errors             []string               `json:"errors"`
	ExporterStats      map[string]interface{} `json:"exporter_stats"`
}

CollectorStats contains statistics about the metrics collector

type Components

type Components struct {
	Schemas         map[string]*Schema        `json:"schemas,omitempty" yaml:"schemas,omitempty"`
	Responses       map[string]*Response      `json:"responses,omitempty" yaml:"responses,omitempty"`
	Parameters      map[string]*Parameter     `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	Examples        map[string]*Example       `json:"examples,omitempty" yaml:"examples,omitempty"`
	RequestBodies   map[string]*RequestBody   `json:"requestBodies,omitempty" yaml:"requestBodies,omitempty"`
	Headers         map[string]*Header        `json:"headers,omitempty" yaml:"headers,omitempty"`
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty" yaml:"securitySchemes,omitempty"`
	Links           map[string]*Link          `json:"links,omitempty" yaml:"links,omitempty"`
	Callbacks       map[string]interface{}    `json:"callbacks,omitempty" yaml:"callbacks,omitempty"`
}

Components holds reusable objects for the API spec

type Configurable

type Configurable interface {
	Configure(config any) error
}

Configurable is optional for services that need configuration

type ConfigurableExtension

type ConfigurableExtension interface {
	Extension
	// Configure configures the extension with the provided config object
	Configure(config any) error
}

ConfigurableExtension is an optional interface for extensions that support configuration.

type Contact

type Contact struct {
	Name  string
	Email string
	URL   string
}

Contact represents contact information

type Container

type Container interface {
	// Register adds a service factory to the container
	// Returns error if name already registered or factory is invalid
	Register(name string, factory Factory, opts ...RegisterOption) error

	// Resolve returns a service by name
	// Returns error if not found or instantiation fails
	Resolve(name string) (any, error)

	// Has checks if a service is registered
	Has(name string) bool

	// Services returns all registered service names
	Services() []string

	// BeginScope creates a new scope for request-scoped services
	// Scopes must be ended with scope.End() to clean up resources
	BeginScope() Scope

	// Start initializes all services in dependency order
	Start(ctx context.Context) error

	// Stop shuts down all services in reverse order
	Stop(ctx context.Context) error

	// Health checks all services
	Health(ctx context.Context) error

	// Inspect returns diagnostic information about a service
	Inspect(name string) ServiceInfo
}

Container provides dependency injection with lifecycle management

type Context

type Context interface {

	// Request access
	Request() *http.Request
	Response() http.ResponseWriter

	// Path parameters
	Param(name string) string
	Params() map[string]string

	// Query parameters
	Query(name string) string
	QueryDefault(name, defaultValue string) string

	// Request body
	Bind(v any) error
	BindJSON(v any) error
	BindXML(v any) error

	// Multipart form data
	FormFile(name string) (multipart.File, *multipart.FileHeader, error)
	FormFiles(name string) ([]*multipart.FileHeader, error)
	FormValue(name string) string
	FormValues(name string) []string
	ParseMultipartForm(maxMemory int64) error

	// Response helpers
	JSON(code int, v any) error
	XML(code int, v any) error
	String(code int, s string) error
	Bytes(code int, data []byte) error
	NoContent(code int) error
	Redirect(code int, url string) error

	// Fluent response builder
	Status(code int) ResponseBuilder

	// Headers
	Header(key string) string
	SetHeader(key, value string)

	// Context values
	Set(key string, value any)
	Get(key string) any
	MustGet(key string) any

	// Request context
	Context() context.Context
	WithContext(ctx context.Context)

	// DI integration
	Container() Container
	Scope() Scope
	Resolve(name string) (any, error)
	Must(name string) any
}

Context wraps http.Request with convenience methods

type Counter

type Counter interface {
	Inc()
	Add(delta float64)
	Get() float64
	WithLabels(labels map[string]string) Counter
	Reset() error
}

Counter tracks monotonically increasing values

type CustomCollector

type CustomCollector interface {
	Name() string
	Collect() map[string]interface{}
	// WithLabels(labels map[string]string) CustomCollector
	// Get() map[string]interface{}
	Reset() error
	IsEnabled() bool
}

CustomCollector defines interface for custom metrics collectors

type DefaultErrorHandler

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

DefaultErrorHandler is the default error handler

func (*DefaultErrorHandler) GetRetryDelay

func (h *DefaultErrorHandler) GetRetryDelay(attempt int, err error) time.Duration

GetRetryDelay returns the delay before retrying

func (*DefaultErrorHandler) HandleError

func (h *DefaultErrorHandler) HandleError(ctx context.Context, err error) error

HandleError handles an error

func (*DefaultErrorHandler) ShouldRetry

func (h *DefaultErrorHandler) ShouldRetry(err error) bool

ShouldRetry determines if an operation should be retried

type Discriminator

type Discriminator struct {
	PropertyName string            `json:"propertyName"`
	Mapping      map[string]string `json:"mapping,omitempty"`
}

Discriminator supports polymorphism

type Disposable

type Disposable interface {
	Dispose() error
}

Disposable is optional for scoped services that need cleanup

type Encoding

type Encoding struct {
	ContentType   string             `json:"contentType,omitempty"`
	Headers       map[string]*Header `json:"headers,omitempty"`
	Style         string             `json:"style,omitempty"`
	Explode       bool               `json:"explode,omitempty"`
	AllowReserved bool               `json:"allowReserved,omitempty"`
}

Encoding defines encoding for a property

type ErrorHandler

type ErrorHandler interface {
	HandleError(ctx context.Context, err error) error
	ShouldRetry(err error) bool
	GetRetryDelay(attempt int, err error) time.Duration
}

ErrorHandler defines how errors should be handled

func NewDefaultErrorHandler

func NewDefaultErrorHandler(l logger.Logger) ErrorHandler

NewDefaultErrorHandler creates a new default error handler

type Example

type Example struct {
	Summary       string      `json:"summary,omitempty"`
	Description   string      `json:"description,omitempty"`
	Value         interface{} `json:"value,omitempty"`
	ExternalValue string      `json:"externalValue,omitempty"`
}

Example provides an example value

type ExportFormat

type ExportFormat string

ExportFormat represents the format for metrics export

const (
	ExportFormatPrometheus ExportFormat = "prometheus"
	ExportFormatJSON       ExportFormat = "json"
	ExportFormatInflux     ExportFormat = "influx"
	ExportFormatStatsD     ExportFormat = "statsd"
)

type Exporter

type Exporter interface {
	// Export exports metrics in the specific format
	Export(metrics map[string]interface{}) ([]byte, error)

	// Format returns the export format identifier
	Format() string

	// Stats returns exporter statistics
	Stats() interface{}
}

Exporter defines the interface for metrics export

type Extension

type Extension interface {
	// Name returns the unique name of the extension
	Name() string

	// Version returns the semantic version of the extension
	Version() string

	// Description returns a human-readable description
	Description() string

	// Start starts the extension.
	// This is called after all extensions have been registered and the DI container has started.
	Start(ctx context.Context) error

	// Stop stops the extension gracefully.
	// Extensions are stopped in reverse dependency order.
	Stop(ctx context.Context) error

	// Health checks if the extension is healthy.
	// This is called periodically by the health check system.
	// Return nil if healthy, error otherwise.
	Health(ctx context.Context) error

	// Dependencies returns the names of extensions this extension depends on.
	// The app will ensure dependencies are started before this extension.
	Dependencies() []string
}

Extension represents an official Forge extension that can be registered with an App. Extensions have full access to the framework and are first-party, trusted components.

Extensions follow a standard lifecycle:

  1. Register(app) - Register services with DI container
  2. Start(ctx) - Start the extension
  3. Health(ctx) - Check extension health (called periodically)
  4. Stop(ctx) - Stop the extension (called during graceful shutdown)

type ExtensionInfo

type ExtensionInfo struct {
	Name         string   `json:"name"`
	Version      string   `json:"version"`
	Description  string   `json:"description"`
	Dependencies []string `json:"dependencies"`
	Status       string   `json:"status"` // "registered", "started", "stopped", "error"
}

ExtensionInfo contains information about a registered extension

type ExternalDocs

type ExternalDocs struct {
	Description string
	URL         string
}

ExternalDocs points to external documentation

type Factory

type Factory func(c Container) (any, error)

Factory creates a service instance

type ForgeError

type ForgeError = ferrors.ForgeError

ForgeError type alias to preserve references via common.ForgeError Allows type assertions like err.(*common.ForgeError)

type Gauge

type Gauge interface {
	Set(value float64)
	Inc()
	Dec()
	Add(delta float64)
	Get() float64
	WithLabels(labels map[string]string) Gauge
	Reset() error
}

Gauge tracks values that can go up or down

type GroupConfig

type GroupConfig struct {
	Middleware []Middleware
	Tags       []string
	Metadata   map[string]any
}

GroupConfig holds route group configuration

type GroupOption

type GroupOption interface {
	Apply(*GroupConfig)
}

GroupOption configures a route group

type HTTPChannelBinding

type HTTPChannelBinding struct {
	Method         string `json:"method,omitempty"` // GET, POST, etc.
	BindingVersion string `json:"bindingVersion,omitempty"`
}

HTTPChannelBinding represents HTTP-specific channel configuration

type HTTPMessageBinding

type HTTPMessageBinding struct {
	Headers        *Schema `json:"headers,omitempty"`
	StatusCode     int     `json:"statusCode,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

HTTPMessageBinding represents HTTP-specific message configuration

type HTTPOperationBinding

type HTTPOperationBinding struct {
	Method         string  `json:"method,omitempty"`
	Query          *Schema `json:"query,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

HTTPOperationBinding represents HTTP-specific operation configuration

type HTTPServerBinding

type HTTPServerBinding struct {
	BindingVersion string `json:"bindingVersion,omitempty"`
}

HTTPServerBinding represents HTTP-specific server configuration

type Header struct {
	Description string      `json:"description,omitempty"`
	Required    bool        `json:"required,omitempty"`
	Deprecated  bool        `json:"deprecated,omitempty"`
	Schema      *Schema     `json:"schema,omitempty"`
	Example     interface{} `json:"example,omitempty"`
}

Header describes a single header parameter

type HealthCallback

type HealthCallback func(result *HealthResult)

HealthCallback is a callback function for health status changes

type HealthCheck

type HealthCheck interface {
	// Name returns the name of the health check implementation.
	Name() string

	// Check performs the health check and returns the result as a HealthResult.
	Check(ctx context.Context) *HealthResult

	// Timeout returns the maximum duration allowed for the health check to complete before timing out.
	Timeout() time.Duration

	// Critical returns true if the health check is considered critical, meaning its failure impacts the overall system health.
	Critical() bool

	// Dependencies returns a slice of strings representing the dependencies for the health check.
	Dependencies() []string
}

HealthCheck defines the interface for health checks

type HealthCheckFn

type HealthCheckFn func(ctx context.Context) *HealthResult

HealthCheckFn represents a single health check

type HealthChecker

type HealthChecker interface {
	Health(ctx context.Context) error
}

HealthChecker is optional for services that provide health checks

type HealthCheckerStats

type HealthCheckerStats struct {
	RegisteredChecks int           `json:"registered_checks"`
	Subscribers      int           `json:"subscribers"`
	Started          bool          `json:"started"`
	Uptime           time.Duration `json:"uptime"`
	LastReportTime   time.Time     `json:"last_report_time"`
	OverallStatus    HealthStatus  `json:"overall_status"`
	LastReport       *HealthReport `json:"last_report,omitempty"`
}

HealthCheckerStats contains statistics about the health checker

type HealthConfig

type HealthConfig struct {
	Enabled                bool              `yaml:"enabled" json:"enabled"`
	CheckInterval          time.Duration     `yaml:"check_interval" json:"check_interval"`
	ReportInterval         time.Duration     `yaml:"report_interval" json:"report_interval"`
	EnableAutoDiscovery    bool              `yaml:"enable_auto_discovery" json:"enable_auto_discovery"`
	EnablePersistence      bool              `yaml:"enable_persistence" json:"enable_persistence"`
	EnableAlerting         bool              `yaml:"enable_alerting" json:"enable_alerting"`
	MaxConcurrentChecks    int               `yaml:"max_concurrent_checks" json:"max_concurrent_checks"`
	DefaultTimeout         time.Duration     `yaml:"default_timeout" json:"default_timeout"`
	CriticalServices       []string          `yaml:"critical_services" json:"critical_services"`
	DegradedThreshold      float64           `yaml:"degraded_threshold" json:"degraded_threshold"`
	UnhealthyThreshold     float64           `yaml:"unhealthy_threshold" json:"unhealthy_threshold"`
	EnableSmartAggregation bool              `yaml:"enable_smart_aggregation" json:"enable_smart_aggregation"`
	EnablePrediction       bool              `yaml:"enable_prediction" json:"enable_prediction"`
	EnableEndpoints        bool              `yaml:"enable_endpoints" json:"enable_endpoints"`
	EndpointPrefix         string            `yaml:"endpoint_prefix" json:"endpoint_prefix"`
	HistorySize            int               `yaml:"history_size" json:"history_size"`
	Tags                   map[string]string `yaml:"tags" json:"tags"`

	// Service specific configuration
	AutoRegister    bool `yaml:"auto_register" json:"auto_register"`
	ExposeEndpoints bool `yaml:"expose_endpoints" json:"expose_endpoints"`
	EnableMetrics   bool `yaml:"enable_metrics" json:"enable_metrics"`

	// Environment information
	Version     string `yaml:"version" json:"version"`
	Environment string `yaml:"environment" json:"environment"`
}

HealthConfig configures health checks

func DefaultHealthConfig

func DefaultHealthConfig() HealthConfig

DefaultHealthConfig returns default health configuration

type HealthManager

type HealthManager interface {
	// Name returns the name or identifier associated with the implementation.
	Name() string

	// Start initializes and starts the health manager, performing necessary setup like auto-registering checks and endpoints.
	Start(ctx context.Context) error

	// Stop gracefully stops the health manager and releases resources. It requires a context for controlled shutdown.
	Stop(ctx context.Context) error

	// OnHealthCheck performs health checks for the service and returns an error if any check fails.
	OnHealthCheck(ctx context.Context) error

	// Register registers a health check. Returns an error if the check name is already registered or invalid.
	Register(check HealthCheck) error

	// RegisterFn registers a function-based health check under a provided name. Returns an error if the name is already registered or invalid.
	RegisterFn(name string, check HealthCheckFn) error

	// Unregister removes a health check associated with the specified name. Returns an error if the operation fails.
	Unregister(name string) error

	// Check executes health checks for all registered services and returns a comprehensive health report.
	Check(ctx context.Context) *HealthReport

	// CheckOne initiates a health check for the specified check by name and returns its health result.
	CheckOne(ctx context.Context, name string) *HealthResult

	// GetStatus returns the current overall health status of the system or service.
	GetStatus() HealthStatus

	// Subscribe registers a callback function that triggers when health status changes.
	Subscribe(callback HealthCallback) error

	// GetLastReport retrieves the most recent health report generated by the health manager.
	GetLastReport() *HealthReport

	// GetChecks retrieves a map of all registered health checks with their corresponding names as keys.
	GetChecks() map[string]HealthCheck

	// GetStats retrieves statistics about the health checker, including registered checks, subscribers, uptime, and overall status.
	GetStats() *HealthCheckerStats

	// SetEnvironment sets the environment name for the health manager.
	SetEnvironment(name string)

	// SetVersion sets the version information for the health manager implementation.
	SetVersion(version string)

	// SetHostname sets the hostname for the health manager instance.
	SetHostname(hostname string)

	// Environment returns the name of the deployment environment as a string.
	Environment() string

	// Hostname returns the hostname of the system or service being monitored.
	Hostname() string

	// Version returns the version information of the health manager as a string.
	Version() string

	// StartTime returns the time when the health manager was initialized or started.
	StartTime() time.Time

	// Reload reloads the health configuration at runtime
	Reload(config *HealthConfig) error
}

HealthManager defines the interface for health checking

type HealthReport

type HealthReport struct {
	Overall     HealthStatus             `json:"overall"`
	Services    map[string]*HealthResult `json:"services"`
	Timestamp   time.Time                `json:"timestamp"`
	Duration    time.Duration            `json:"duration"`
	Version     string                   `json:"version"`
	Environment string                   `json:"environment"`
	Hostname    string                   `json:"hostname"`
	Uptime      time.Duration            `json:"uptime"`
	Metadata    map[string]interface{}   `json:"metadata,omitempty"`
}

HealthReport represents a comprehensive health report

func FromJSON

func FromJSON(data []byte) (*HealthReport, error)

FromJSON creates a health report from JSON

func NewHealthReport

func NewHealthReport() *HealthReport

NewHealthReport creates a new health report

func (*HealthReport) AddResult

func (hr *HealthReport) AddResult(result *HealthResult)

AddResult adds a health result to the report

func (*HealthReport) AddResults

func (hr *HealthReport) AddResults(results []*HealthResult)

AddResults adds multiple health results to the report

func (*HealthReport) GetCriticalCount

func (hr *HealthReport) GetCriticalCount() int

GetCriticalCount returns the number of critical services

func (*HealthReport) GetCriticalServices

func (hr *HealthReport) GetCriticalServices() []*HealthResult

GetCriticalServices returns all critical services

func (*HealthReport) GetDegradedCount

func (hr *HealthReport) GetDegradedCount() int

GetDegradedCount returns the number of degraded services

func (*HealthReport) GetFailedCriticalCount

func (hr *HealthReport) GetFailedCriticalCount() int

GetFailedCriticalCount returns the number of failed critical services

func (*HealthReport) GetHealthyCount

func (hr *HealthReport) GetHealthyCount() int

GetHealthyCount returns the number of healthy services

func (*HealthReport) GetServicesByStatus

func (hr *HealthReport) GetServicesByStatus(status HealthStatus) []*HealthResult

GetServicesByStatus returns services filtered by status

func (*HealthReport) GetUnhealthyCount

func (hr *HealthReport) GetUnhealthyCount() int

GetUnhealthyCount returns the number of unhealthy services

func (*HealthReport) IsDegraded

func (hr *HealthReport) IsDegraded() bool

IsDegraded returns true if the overall health is degraded

func (*HealthReport) IsHealthy

func (hr *HealthReport) IsHealthy() bool

IsHealthy returns true if the overall health is healthy

func (*HealthReport) IsUnhealthy

func (hr *HealthReport) IsUnhealthy() bool

IsUnhealthy returns true if the overall health is unhealthy

func (*HealthReport) Summary

func (hr *HealthReport) Summary() map[string]interface{}

Summary returns a summary of the health report

func (*HealthReport) ToJSON

func (hr *HealthReport) ToJSON() ([]byte, error)

ToJSON converts the health report to JSON

func (*HealthReport) WithDuration

func (hr *HealthReport) WithDuration(duration time.Duration) *HealthReport

WithDuration sets the duration of the health check

func (*HealthReport) WithEnvironment

func (hr *HealthReport) WithEnvironment(environment string) *HealthReport

WithEnvironment sets the environment information

func (*HealthReport) WithHostname

func (hr *HealthReport) WithHostname(hostname string) *HealthReport

WithHostname sets the hostname information

func (*HealthReport) WithMetadata

func (hr *HealthReport) WithMetadata(metadata map[string]interface{}) *HealthReport

WithMetadata adds metadata to the health report

func (*HealthReport) WithUptime

func (hr *HealthReport) WithUptime(uptime time.Duration) *HealthReport

WithUptime sets the application uptime

func (*HealthReport) WithVersion

func (hr *HealthReport) WithVersion(version string) *HealthReport

WithVersion sets the version information

type HealthReportCallback

type HealthReportCallback func(report *HealthReport)

HealthReportCallback is a callback function for health report changes

type HealthResult

type HealthResult struct {
	Name      string                 `json:"name"`
	Status    HealthStatus           `json:"status"`
	Message   string                 `json:"message"`
	Details   map[string]interface{} `json:"details"`
	Timestamp time.Time              `json:"timestamp"`
	Duration  time.Duration          `json:"duration"`
	Error     string                 `json:"error,omitempty"`
	Critical  bool                   `json:"critical"`
	Tags      map[string]string      `json:"tags,omitempty"`
}

HealthResult represents the result of a health check

func NewHealthResult

func NewHealthResult(name string, status HealthStatus, message string) *HealthResult

NewHealthResult creates a new health result

func (*HealthResult) IsCritical

func (hr *HealthResult) IsCritical() bool

IsCritical returns true if the health check is critical

func (*HealthResult) IsDegraded

func (hr *HealthResult) IsDegraded() bool

IsDegraded returns true if the health result is degraded

func (*HealthResult) IsHealthy

func (hr *HealthResult) IsHealthy() bool

IsHealthy returns true if the health result is healthy

func (*HealthResult) IsUnhealthy

func (hr *HealthResult) IsUnhealthy() bool

IsUnhealthy returns true if the health result is unhealthy

func (*HealthResult) String

func (hr *HealthResult) String() string

func (*HealthResult) WithCritical

func (hr *HealthResult) WithCritical(critical bool) *HealthResult

WithCritical marks the health check as critical

func (*HealthResult) WithDetail

func (hr *HealthResult) WithDetail(key string, value interface{}) *HealthResult

WithDetail adds a single detail to the health result

func (*HealthResult) WithDetails

func (hr *HealthResult) WithDetails(details map[string]interface{}) *HealthResult

WithDetails adds details to the health result

func (*HealthResult) WithDuration

func (hr *HealthResult) WithDuration(duration time.Duration) *HealthResult

WithDuration sets the duration of the health check

func (*HealthResult) WithError

func (hr *HealthResult) WithError(err error) *HealthResult

WithError adds an error to the health result

func (*HealthResult) WithMessage

func (hr *HealthResult) WithMessage(message string) *HealthResult

func (*HealthResult) WithStatus

func (hr *HealthResult) WithStatus(status HealthStatus) *HealthResult

func (*HealthResult) WithTag

func (hr *HealthResult) WithTag(key, value string) *HealthResult

WithTag adds a single tag to the health result

func (*HealthResult) WithTags

func (hr *HealthResult) WithTags(tags map[string]string) *HealthResult

WithTags adds tags to the health result

func (*HealthResult) WithTimestamp

func (hr *HealthResult) WithTimestamp(timestamp time.Time) *HealthResult

func (*HealthResult) WithTimestampNow

func (hr *HealthResult) WithTimestampNow() *HealthResult

type HealthStatus

type HealthStatus string

HealthStatus represents the health status of a service or component

const (
	HealthStatusHealthy   HealthStatus = "healthy"
	HealthStatusDegraded  HealthStatus = "degraded"
	HealthStatusUnhealthy HealthStatus = "unhealthy"
	HealthStatusUnknown   HealthStatus = "unknown"
)

func (HealthStatus) IsDegraded

func (hs HealthStatus) IsDegraded() bool

IsDegraded returns true if the status is degraded

func (HealthStatus) IsHealthy

func (hs HealthStatus) IsHealthy() bool

IsHealthy returns true if the status is healthy

func (HealthStatus) IsUnhealthy

func (hs HealthStatus) IsUnhealthy() bool

IsUnhealthy returns true if the status is unhealthy

func (HealthStatus) IsUnknown

func (hs HealthStatus) IsUnknown() bool

IsUnknown returns true if the status is unknown

func (HealthStatus) Severity

func (hs HealthStatus) Severity() int

Severity returns a numeric severity level for comparison

func (HealthStatus) String

func (hs HealthStatus) String() string

String returns the string representation of the health status

type Histogram

type Histogram interface {
	Observe(value float64)
	ObserveDuration(start time.Time)
	GetBuckets() map[float64]uint64
	GetCount() uint64
	GetSum() float64
	GetMean() float64
	GetPercentile(percentile float64) float64
	WithLabels(labels map[string]string) Histogram
	Reset() error
}

Histogram tracks distributions of values

type HotReloadableExtension

type HotReloadableExtension interface {
	Extension
	// Reload reloads the extension's configuration or state without restarting
	Reload(ctx context.Context) error
}

HotReloadableExtension is an optional interface for extensions that support hot reload.

type Info

type Info struct {
	Title          string   `json:"title"`
	Description    string   `json:"description,omitempty"`
	Version        string   `json:"version"`
	TermsOfService string   `json:"termsOfService,omitempty"`
	Contact        *Contact `json:"contact,omitempty"`
	License        *License `json:"license,omitempty"`
}

Info provides metadata about the API

type License

type License struct {
	Name string
	URL  string
}

License represents license information

type Link struct {
	OperationRef string                 `json:"operationRef,omitempty"`
	OperationID  string                 `json:"operationId,omitempty"`
	Parameters   map[string]interface{} `json:"parameters,omitempty"`
	RequestBody  interface{}            `json:"requestBody,omitempty"`
	Description  string                 `json:"description,omitempty"`
	Server       *OpenAPIServer         `json:"server,omitempty"`
}

Link represents a possible design-time link for a response

type Logger

type Logger = logger.Logger

Logger is an alias to the centralized logger interface in v2/internal/logger. This preserves backward compatibility for components that used common.Logger.

type MediaType

type MediaType struct {
	Schema   *Schema              `json:"schema,omitempty"`
	Example  interface{}          `json:"example,omitempty"`
	Examples map[string]*Example  `json:"examples,omitempty"`
	Encoding map[string]*Encoding `json:"encoding,omitempty"`
}

MediaType provides schema and examples for a media type

type MetricType

type MetricType string

MetricType represents the type of metric

const (
	MetricTypeCounter   MetricType = "counter"
	MetricTypeGauge     MetricType = "gauge"
	MetricTypeHistogram MetricType = "histogram"
	MetricTypeTimer     MetricType = "timer"
)

type Metrics

type Metrics interface {
	Service
	HealthChecker

	// Counter metrics (monotonically increasing)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Counter(name string, labels ...string) Counter

	// Gauge metrics (can go up or down)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Gauge(name string, labels ...string) Gauge

	// Histogram metrics (distributions)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Histogram(name string, labels ...string) Histogram

	// Timer metrics (time taken to complete an operation)
	// Labels should be provided as key-value pairs: "key1", "value1", "key2", "value2"
	Timer(name string, labels ...string) Timer

	// Export metrics (Prometheus format by default)
	Export(format ExportFormat) ([]byte, error)

	// Export to file
	ExportToFile(format ExportFormat, filename string) error

	// Register a custom collector
	RegisterCollector(collector CustomCollector) error

	// Unregister a custom collector
	UnregisterCollector(name string) error

	// Get all custom collectors
	GetCollectors() []CustomCollector

	// Reset metrics
	Reset() error

	// Reset metric
	ResetMetric(name string) error

	// Get metrics
	GetMetrics() map[string]interface{}

	// Get metrics by type
	GetMetricsByType(metricType MetricType) map[string]interface{}

	// Get metrics by tag
	GetMetricsByTag(tagKey, tagValue string) map[string]interface{}

	// Get stats
	GetStats() CollectorStats

	// Reload reloads the metrics configuration at runtime
	Reload(config *MetricsConfig) error
}

Metrics provides telemetry collection

type MetricsConfig

type MetricsConfig struct {
	Enabled     bool
	MetricsPath string
	Namespace   string

	EnableSystemMetrics  bool                                                     `yaml:"enable_system_metrics" json:"enable_system_metrics"`
	EnableRuntimeMetrics bool                                                     `yaml:"enable_runtime_metrics" json:"enable_runtime_metrics"`
	EnableHTTPMetrics    bool                                                     `yaml:"enable_http_metrics" json:"enable_http_metrics"`
	CollectionInterval   time.Duration                                            `yaml:"collection_interval" json:"collection_interval"`
	StorageConfig        *MetricsStorageConfig[map[string]interface{}]            `yaml:"storage" json:"storage"`
	Exporters            map[string]MetricsExporterConfig[map[string]interface{}] `yaml:"exporters" json:"exporters"`
	DefaultTags          map[string]string                                        `yaml:"default_tags" json:"default_tags"`
	MaxMetrics           int                                                      `yaml:"max_metrics" json:"max_metrics"`
	BufferSize           int                                                      `yaml:"buffer_size" json:"buffer_size"`
}

MetricsConfig configures metrics collection

type MetricsExporterConfig

type MetricsExporterConfig[T any] struct {
	Enabled  bool          `yaml:"enabled" json:"enabled"`
	Interval time.Duration `yaml:"interval" json:"interval"`
	Config   T             `yaml:"config" json:"config"`
}

ExporterConfig contains configuration for exporters

type MetricsStorageConfig

type MetricsStorageConfig[T any] struct {
	Type   string `yaml:"type" json:"type"`
	Config T      `yaml:"config" json:"config"`
}

StorageConfig contains storage configuration

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware wraps HTTP handlers

type OAuthFlow

type OAuthFlow struct {
	AuthorizationURL string
	TokenURL         string
	RefreshURL       string
	Scopes           map[string]string
}

OAuthFlow defines a single OAuth 2.0 flow

type OAuthFlows

type OAuthFlows struct {
	Implicit          *OAuthFlow
	Password          *OAuthFlow
	ClientCredentials *OAuthFlow
	AuthorizationCode *OAuthFlow
}

OAuthFlows defines OAuth 2.0 flows

type ObservableExtension

type ObservableExtension interface {
	Extension
	// Metrics returns a map of metric names to values
	Metrics() map[string]any
}

ObservableExtension is an optional interface for extensions that provide metrics.

type OpenAPIConfig

type OpenAPIConfig struct {
	// Basic info
	Title       string
	Description string
	Version     string

	// OpenAPI version (default: "3.1.0")
	OpenAPIVersion string

	// Server configuration
	Servers []OpenAPIServer

	// Security schemes
	Security map[string]SecurityScheme

	// Global tags
	Tags []OpenAPITag

	// External docs
	ExternalDocs *ExternalDocs

	// Contact info
	Contact *Contact
	License *License

	// UI configuration
	UIPath      string // Default: "/swagger"
	SpecPath    string // Default: "/openapi.json"
	UIEnabled   bool   // Default: true
	SpecEnabled bool   // Default: true

	// Generation options
	PrettyJSON          bool
	IncludeExamples     bool
	IncludeDescriptions bool
	ValidateResponses   bool
}

OpenAPIConfig configures OpenAPI 3.1.0 generation

type OpenAPIServer

type OpenAPIServer struct {
	URL         string
	Description string
	Variables   map[string]ServerVariable
}

OpenAPIServer represents a server in the OpenAPI spec

type OpenAPISpec

type OpenAPISpec struct {
	OpenAPI      string                `json:"openapi"`
	Info         Info                  `json:"info"`
	Servers      []OpenAPIServer       `json:"servers,omitempty"`
	Paths        map[string]*PathItem  `json:"paths"`
	Components   *Components           `json:"components,omitempty"`
	Security     []SecurityRequirement `json:"security,omitempty"`
	Tags         []OpenAPITag          `json:"tags,omitempty"`
	ExternalDocs *ExternalDocs         `json:"externalDocs,omitempty"`
	Webhooks     map[string]*PathItem  `json:"webhooks,omitempty"`
}

OpenAPISpec represents the complete OpenAPI 3.1.0 specification

type OpenAPITag

type OpenAPITag struct {
	Name         string
	Description  string
	ExternalDocs *ExternalDocs
}

OpenAPITag represents a tag in the OpenAPI spec

type Operation

type Operation struct {
	Tags         []string                        `json:"tags,omitempty" yaml:"tags,omitempty"`
	Summary      string                          `json:"summary,omitempty" yaml:"summary,omitempty"`
	Description  string                          `json:"description,omitempty" yaml:"description,omitempty"`
	OperationID  string                          `json:"operationId,omitempty" yaml:"operationId,omitempty"`
	Parameters   []Parameter                     `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	RequestBody  *RequestBody                    `json:"requestBody,omitempty" yaml:"requestBody,omitempty"`
	Responses    map[string]*Response            `json:"responses" yaml:"responses"`
	Callbacks    map[string]map[string]*PathItem `json:"callbacks,omitempty" yaml:"callbacks,omitempty"`
	Deprecated   bool                            `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
	Security     []SecurityRequirement           `json:"security,omitempty" yaml:"security,omitempty"`
	ExternalDocs *ExternalDocs                   `json:"externalDocs,omitempty" yaml:"externalDocs,omitempty"`
}

Operation describes a single API operation on a path

type Parameter

type Parameter struct {
	Name            string              `json:"name" yaml:"name"`
	In              string              `json:"in" yaml:"in"` // "query", "header", "path", "cookie"
	Description     string              `json:"description,omitempty" yaml:"description,omitempty"`
	Required        bool                `json:"required,omitempty" yaml:"required,omitempty"`
	Deprecated      bool                `json:"deprecated,omitempty" yaml:"deprecated,omitempty"`
	AllowEmptyValue bool                `json:"allowEmptyValue,omitempty" yaml:"allowEmptyValue,omitempty"`
	Schema          *Schema             `json:"schema,omitempty" yaml:"schema,omitempty"`
	Example         interface{}         `json:"example,omitempty" yaml:"example,omitempty"`
	Examples        map[string]*Example `json:"examples,omitempty" yaml:"examples,omitempty"`
}

Parameter describes a single operation parameter

type PathItem

type PathItem struct {
	Summary     string      `json:"summary,omitempty"`
	Description string      `json:"description,omitempty"`
	Get         *Operation  `json:"get,omitempty"`
	Put         *Operation  `json:"put,omitempty"`
	Post        *Operation  `json:"post,omitempty"`
	Delete      *Operation  `json:"delete,omitempty"`
	Options     *Operation  `json:"options,omitempty"`
	Head        *Operation  `json:"head,omitempty"`
	Patch       *Operation  `json:"patch,omitempty"`
	Parameters  []Parameter `json:"parameters,omitempty"`
}

PathItem describes operations available on a single path

type RegisterOption

type RegisterOption struct {
	Lifecycle    string // "singleton", "scoped", or "transient"
	Dependencies []string
	Metadata     map[string]string
	Groups       []string
}

RegisterOption is a configuration option for service registration

func MergeOptions

func MergeOptions(opts []RegisterOption) RegisterOption

MergeOptions combines multiple options

func Scoped

func Scoped() RegisterOption

Scoped makes the service live for the duration of a scope

func Singleton

func Singleton() RegisterOption

Singleton makes the service a singleton (default)

func Transient

func Transient() RegisterOption

Transient makes the service created on each resolve

func WithDIMetadata

func WithDIMetadata(key, value string) RegisterOption

WithDIMetadata adds diagnostic metadata to DI service registration

func WithDependencies

func WithDependencies(deps ...string) RegisterOption

WithDependencies declares explicit dependencies

func WithGroup

func WithGroup(group string) RegisterOption

WithGroup adds service to a named group

type RequestBody

type RequestBody struct {
	Description string                `json:"description,omitempty"`
	Content     map[string]*MediaType `json:"content"`
	Required    bool                  `json:"required,omitempty"`
}

RequestBody describes a single request body

type Response

type Response struct {
	Description string                `json:"description"`
	Headers     map[string]*Header    `json:"headers,omitempty"`
	Content     map[string]*MediaType `json:"content,omitempty"`
	Links       map[string]*Link      `json:"links,omitempty"`
}

Response describes a single response from an API operation

type ResponseBuilder

type ResponseBuilder interface {
	JSON(v any) error
	XML(v any) error
	String(s string) error
	Bytes(data []byte) error
	NoContent() error
	Header(key, value string) ResponseBuilder
}

ResponseBuilder provides fluent response building

type RouteConfig

type RouteConfig struct {
	Name        string
	Summary     string
	Description string
	Tags        []string
	Middleware  []Middleware
	Timeout     time.Duration
	Metadata    map[string]any
	Extensions  map[string]Extension

	// OpenAPI metadata
	OperationID string
	Deprecated  bool
}

RouteConfig holds route configuration

type RouteExtension

type RouteExtension interface {
	Name() string
	Validate() error
}

RouteExtension represents a route-level extension (e.g., OpenAPI, custom validation) Note: This is different from app-level Extension which manages app components

type RouteInfo

type RouteInfo struct {
	Name        string
	Method      string
	Path        string
	Pattern     string
	Handler     any
	Middleware  []Middleware
	Tags        []string
	Metadata    map[string]any
	Extensions  map[string]Extension
	Summary     string
	Description string
}

RouteInfo provides route information for inspection

type RouteOption

type RouteOption interface {
	Apply(*RouteConfig)
}

RouteOption configures a route

type Router

type Router interface {
	// HTTP Methods - register routes
	GET(path string, handler any, opts ...RouteOption) error
	POST(path string, handler any, opts ...RouteOption) error
	PUT(path string, handler any, opts ...RouteOption) error
	DELETE(path string, handler any, opts ...RouteOption) error
	PATCH(path string, handler any, opts ...RouteOption) error
	OPTIONS(path string, handler any, opts ...RouteOption) error
	HEAD(path string, handler any, opts ...RouteOption) error

	// Grouping - organize routes
	Group(prefix string, opts ...GroupOption) Router

	// Middleware - wrap handlers
	Use(middleware ...Middleware)

	// Lifecycle
	Start(ctx context.Context) error
	Stop(ctx context.Context) error

	// HTTP serving
	ServeHTTP(w http.ResponseWriter, r *http.Request)
	Handler() http.Handler

	// Inspection
	Routes() []RouteInfo
	RouteByName(name string) (RouteInfo, bool)
	RoutesByTag(tag string) []RouteInfo
	RoutesByMetadata(key string, value any) []RouteInfo
}

Router provides HTTP routing with multiple backend support

type RouterAdapter

type RouterAdapter interface {
	// Handle registers a route
	Handle(method, path string, handler http.Handler)

	// Mount registers a sub-handler
	Mount(path string, handler http.Handler)

	// ServeHTTP dispatches requests
	ServeHTTP(w http.ResponseWriter, r *http.Request)

	// Close cleans up resources
	Close() error
}

RouterAdapter wraps a routing backend

type RouterOption

type RouterOption interface {
	Apply(*routerConfig)
}

RouterOption configures the router

type Schema

type Schema struct {
	Type        string      `json:"type,omitempty"`
	Format      string      `json:"format,omitempty"`
	Title       string      `json:"title,omitempty"`
	Description string      `json:"description,omitempty"`
	Default     interface{} `json:"default,omitempty"`
	Nullable    bool        `json:"nullable,omitempty"`
	ReadOnly    bool        `json:"readOnly,omitempty"`
	WriteOnly   bool        `json:"writeOnly,omitempty"`
	Example     interface{} `json:"example,omitempty"`
	Deprecated  bool        `json:"deprecated,omitempty"`

	// Validation
	MultipleOf       float64       `json:"multipleOf,omitempty"`
	Maximum          float64       `json:"maximum,omitempty"`
	ExclusiveMaximum bool          `json:"exclusiveMaximum,omitempty"`
	Minimum          float64       `json:"minimum,omitempty"`
	ExclusiveMinimum bool          `json:"exclusiveMinimum,omitempty"`
	MaxLength        int           `json:"maxLength,omitempty"`
	MinLength        int           `json:"minLength,omitempty"`
	Pattern          string        `json:"pattern,omitempty"`
	MaxItems         int           `json:"maxItems,omitempty"`
	MinItems         int           `json:"minItems,omitempty"`
	UniqueItems      bool          `json:"uniqueItems,omitempty"`
	MaxProperties    int           `json:"maxProperties,omitempty"`
	MinProperties    int           `json:"minProperties,omitempty"`
	Required         []string      `json:"required,omitempty"`
	Enum             []interface{} `json:"enum,omitempty"`

	// Object/Array properties
	Properties           map[string]*Schema `json:"properties,omitempty"`
	AdditionalProperties interface{}        `json:"additionalProperties,omitempty"`
	Items                *Schema            `json:"items,omitempty"`

	// Composition
	AllOf []Schema `json:"allOf,omitempty"`
	AnyOf []Schema `json:"anyOf,omitempty"`
	OneOf []Schema `json:"oneOf,omitempty"`
	Not   *Schema  `json:"not,omitempty"`

	// Discriminator (OpenAPI 3.1.0)
	Discriminator *Discriminator `json:"discriminator,omitempty"`

	// Reference
	Ref string `json:"$ref,omitempty"`
}

Schema represents a JSON Schema (OpenAPI 3.1.0 uses JSON Schema 2020-12)

type Scope

type Scope interface {
	// Resolve returns a service by name from this scope
	// Scoped services are cached within the scope
	// Singleton services are resolved from parent container
	Resolve(name string) (any, error)

	// End cleans up all scoped services in this scope
	// Must be called when scope is no longer needed (typically in defer)
	End() error
}

Scope represents a lifetime scope for scoped services Typically used for HTTP requests or other bounded operations

type SecurityRequirement

type SecurityRequirement map[string][]string

SecurityRequirement lists required security schemes

type SecurityScheme

type SecurityScheme struct {
	Type             string      `json:"type" yaml:"type"` // "apiKey", "http", "oauth2", "openIdConnect"
	Description      string      `json:"description,omitempty" yaml:"description,omitempty"`
	Name             string      `json:"name,omitempty" yaml:"name,omitempty"`                 // For apiKey
	In               string      `json:"in,omitempty" yaml:"in,omitempty"`                     // For apiKey: "query", "header", "cookie"
	Scheme           string      `json:"scheme,omitempty" yaml:"scheme,omitempty"`             // For http: "bearer", "basic"
	BearerFormat     string      `json:"bearerFormat,omitempty" yaml:"bearerFormat,omitempty"` // For http bearer
	Flows            *OAuthFlows `json:"flows,omitempty" yaml:"flows,omitempty"`
	OpenIdConnectUrl string      `json:"openIdConnectUrl,omitempty" yaml:"openIdConnectUrl,omitempty"`
}

SecurityScheme defines a security scheme

type ServerVariable

type ServerVariable struct {
	Default     string
	Enum        []string
	Description string
}

ServerVariable represents a variable in a server URL

type Service

type Service interface {
	Name() string
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

Service is the standard interface for managed services Container auto-detects and calls these methods

type ServiceInfo

type ServiceInfo struct {
	Name         string
	Type         string
	Lifecycle    string
	Dependencies []string
	Started      bool
	Healthy      bool
	Metadata     map[string]string
}

ServiceInfo contains diagnostic information

type Timer

type Timer interface {
	Record(duration time.Duration)
	Time() func()
	GetCount() uint64
	GetMean() time.Duration
	GetPercentile(percentile float64) time.Duration
	GetMin() time.Duration
	GetMax() time.Duration
	Get() time.Duration
	Reset()
}

Timer represents a timer metric

type WebSocketChannelBinding

type WebSocketChannelBinding struct {
	Method         string  `json:"method,omitempty"` // GET, POST
	Query          *Schema `json:"query,omitempty"`
	Headers        *Schema `json:"headers,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

WebSocketChannelBinding represents WebSocket-specific channel configuration

type WebSocketMessageBinding

type WebSocketMessageBinding struct {
	BindingVersion string `json:"bindingVersion,omitempty"`
}

WebSocketMessageBinding represents WebSocket-specific message configuration

type WebSocketOperationBinding

type WebSocketOperationBinding struct {
	BindingVersion string `json:"bindingVersion,omitempty"`
}

WebSocketOperationBinding represents WebSocket-specific operation configuration

type WebSocketServerBinding

type WebSocketServerBinding struct {
	Headers        *Schema `json:"headers,omitempty"`
	Query          *Schema `json:"query,omitempty"`
	BindingVersion string  `json:"bindingVersion,omitempty"`
}

WebSocketServerBinding represents WebSocket-specific server configuration

Jump to

Keyboard shortcuts

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