Documentation
¶
Index ¶
- Constants
- Variables
- func GatewayMiddleware(config Config, next http.Handler) http.Handler
- func IsExtensionPathExcluded(upstreamPath string, filter *ExtensionPathFilter) bool
- func New(opts ...ConfigOption) forge.Extension
- func RewritePath(path string, route *Route) string
- func ValidateConfig(c *Config) error
- func ValidateTLSConfig(config TLSConfig) error
- type APIKeyAuthProvider
- type APIKeyEntry
- type AccessLogConfig
- type AccessLogWriter
- type AccessLoggerdeprecated
- type AdminAuthConfig
- type AdminAuthMiddleware
- type AsyncAPIAggregator
- type AsyncAPIConfig
- type AuditAction
- type AuditConfig
- type AuditEvent
- type AuditLoggerdeprecated
- type AuditSink
- type AuthConfig
- type AuthError
- type AuthProvider
- type AuthRegistry
- type Authenticator
- type BackoffStrategy
- type BasePlugin
- type BearerTokenAuthProvider
- type Breaker
- type BufferPoolConfig
- type CBConfig
- type CORSConfig
- type CacheStats
- type CacheStatsReader
- type CacheStore
- type CachedResponse
- type CachingConfig
- type CircuitBreakHook
- type CircuitBreakerConfig
- type CircuitBreakerSnapshot
- type CircuitBreakerStore
- type CircuitControl
- type CircuitState
- type CompressionConfig
- type CompressionMiddleware
- type Config
- type ConfigOption
- func WithAccessLog(al AccessLogConfig) ConfigOption
- func WithAdminMiddleware(mw ...forge.Middleware) ConfigOption
- func WithAdminToken(token string) ConfigOption
- func WithAllowUnauthenticatedAdmin(allow bool) ConfigOption
- func WithAsyncAPI(a AsyncAPIConfig) ConfigOption
- func WithAsyncAPIEnabled(enabled bool) ConfigOption
- func WithAuth(auth AuthConfig) ConfigOption
- func WithBasePath(path string) ConfigOption
- func WithCORS(cors CORSConfig) ConfigOption
- func WithCaching(caching CachingConfig) ConfigOption
- func WithCircuitBreaker(cb CircuitBreakerConfig) ConfigOption
- func WithConfig(config Config) ConfigOption
- func WithDashboard(d DashboardConfig) ConfigOption
- func WithDashboardEnabled(enabled bool) ConfigOption
- func WithDiscovery(disc DiscoveryConfig) ConfigOption
- func WithDiscoveryAutoPrefix(enabled bool) ConfigOption
- func WithDiscoveryEnabled(enabled bool) ConfigOption
- func WithDiscoveryPollInterval(d time.Duration) ConfigOption
- func WithDiscoveryPrefixOverrides(overrides map[string]string) ConfigOption
- func WithDiscoveryPrefixTemplate(tmpl string) ConfigOption
- func WithDiscoveryPushInstanceTTL(ttl time.Duration) ConfigOption
- func WithDiscoveryServiceFilters(filters ...ServiceFilter) ConfigOption
- func WithDiscoveryStripPrefix(strip bool) ConfigOption
- func WithDiscoveryWatchMode(enabled bool) ConfigOption
- func WithEnabled(enabled bool) ConfigOption
- func WithExtensionFilter(filter ExtensionPathFilter) ConfigOption
- func WithHealthCheck(hc HealthCheckConfig) ConfigOption
- func WithIPFilter(ipf IPFilterConfig) ConfigOption
- func WithLoadBalancing(lb LoadBalancingConfig) ConfigOption
- func WithMetrics(m MetricsConfig) ConfigOption
- func WithOctopusConfig(oc OctopusConfig) ConfigOption
- func WithOctopusConfigFile(path string) ConfigOption
- func WithOpenAPI(o OpenAPIConfig) ConfigOption
- func WithOpenAPIDisableServiceTags(disabled bool) ConfigOption
- func WithOpenAPIEnabled(enabled bool) ConfigOption
- func WithOpenAPIGatewayDocs(enabled bool) ConfigOption
- func WithOpenAPIRootDocs(enabled bool) ConfigOption
- func WithOpenAPIServiceTagOnly(enabled bool) ConfigOption
- func WithRateLimiting(rl RateLimitConfig) ConfigOption
- func WithRetry(retry RetryConfig) ConfigOption
- func WithRoute(route RouteConfig) ConfigOption
- func WithRoutes(routes []RouteConfig) ConfigOption
- func WithSSE(sse SSEConfig) ConfigOption
- func WithServiceRoute(serviceName, path, targetURL, openapiSpecURL string) ConfigOption
- func WithTLS(tls TLSConfig) ConfigOption
- func WithTimeouts(timeouts TimeoutConfig) ConfigOption
- func WithTracing(t TracingConfig) ConfigOption
- func WithWebSocket(ws WebSocketConfig) ConfigOption
- type ConfigWatcher
- type DashboardConfig
- type DiscoveredService
- type DiscoveryConfig
- type DiscoveryService
- type DistributedRateLimiter
- type ErrorHook
- type ExtensionPathFilter
- type ForwardAuthProvider
- type Gateway
- func (e *Gateway) AccessLog() *AccessLogger
- func (e *Gateway) App() forge.App
- func (e *Gateway) AsyncAPI() *AsyncAPIAggregator
- func (e *Gateway) Auth() *GatewayAuth
- func (e *Gateway) Cache() *ResponseCache
- func (e *Gateway) Circuits() []CircuitBreakerSnapshot
- func (e *Gateway) Config() Config
- func (e *Gateway) Dependencies() []string
- func (e *Gateway) Discovery() *ServiceDiscovery
- func (e *Gateway) GatewayMetrics() *GatewayMetrics
- func (e *Gateway) Health(ctx context.Context) error
- func (e *Gateway) HealthMonitor() *health.Monitor
- func (e *Gateway) Hooks() *HookEngine
- func (e *Gateway) Hub() WSBroadcaster
- func (e *Gateway) OpenAPI() *OpenAPIAggregator
- func (e *Gateway) RateLimiter() *RateLimiter
- func (e *Gateway) Register(app forge.App) error
- func (e *Gateway) ResetCircuit(targetID string) error
- func (e *Gateway) RouteManager() RouteRegistry
- func (e *Gateway) RoutesPersisted() bool
- func (e *Gateway) SetAdminHandlerSetup(fn func(gw *Gateway, router forge.Router))
- func (e *Gateway) SetCacheStore(store CacheStore)
- func (e *Gateway) SetCircuitControl(cb CircuitControl)
- func (e *Gateway) SetDiscoveryService(svc DiscoveryService)
- func (e *Gateway) SetProxyHandler(h http.Handler)
- func (e *Gateway) SetRetryPolicy(r RetryPolicy)
- func (e *Gateway) SetRouteRegistry(rm RouteRegistry)
- func (e *Gateway) SetStatsRecorder(s StatsRecorder)
- func (e *Gateway) SetStore(s any)
- func (e *Gateway) SetTrafficRouter(t TrafficRouter)
- func (e *Gateway) SetWSBroadcaster(h WSBroadcaster)
- func (e *Gateway) Snapshot() *GatewayStats
- func (e *Gateway) Start(ctx context.Context) error
- func (e *Gateway) Stats() StatsRecorder
- func (e *Gateway) Stop(ctx context.Context) error
- func (e *Gateway) TLS() *TLSManager
- type GatewayAuth
- type GatewayAuthContext
- type GatewayMetricsdeprecated
- type GatewayPlugin
- type GatewayStats
- type HeaderPolicy
- type HealthCheckConfig
- type HealthCheckResult
- type HealthChecker
- type HealthHistory
- type HealthMonitor
- type HealthStore
- type HealthSummary
- type HookEngine
- func (he *HookEngine) OnCircuitBreak(fn CircuitBreakHook)
- func (he *HookEngine) OnError(fn ErrorHook)
- func (he *HookEngine) OnRequest(fn RequestHook)
- func (he *HookEngine) OnResponse(fn ResponseHook)
- func (he *HookEngine) OnRouteChange(fn RouteChangeHook)
- func (he *HookEngine) OnUpstreamHealth(fn UpstreamHealthHook)
- func (he *HookEngine) RunOnCircuitBreak(targetID string, from, to CircuitState)
- func (he *HookEngine) RunOnError(err error, route *Route, w http.ResponseWriter)
- func (he *HookEngine) RunOnRequest(r *http.Request, route *Route) error
- func (he *HookEngine) RunOnResponse(resp *http.Response, route *Route)
- func (he *HookEngine) RunOnRouteChange(event RouteEvent)
- func (he *HookEngine) RunOnUpstreamHealth(event UpstreamHealthEvent)
- type IPFilterConfig
- type InMemoryCacheStore
- type InMemoryRateLimitStore
- type JWTAuthConfig
- type JWTAuthProvider
- type LoadBalanceStrategy
- type LoadBalancer
- type LoadBalancingConfig
- type LogAuditSinkdeprecated
- type MetricsConfig
- type OctopusAPIKeyEntry
- type OctopusAdminConfig
- type OctopusAuthConfig
- type OctopusAuthProviderConfig
- type OctopusCBConfig
- type OctopusCORSConfig
- type OctopusCompressionConfig
- type OctopusConfig
- type OctopusDiscoveryBackend
- type OctopusFARPConfig
- type OctopusFARPDiscoveryConfig
- type OctopusGRPCConfig
- type OctopusGatewayConfig
- type OctopusHealthCheckConfig
- type OctopusInstanceConfig
- type OctopusLoggingConfig
- type OctopusMetricsConfig
- type OctopusObservabilityConfig
- type OctopusPluginConfig
- type OctopusRouteCORSConfig
- type OctopusRouteConfig
- type OctopusRouteRateLimitConfig
- type OctopusTLSConfig
- type OctopusTracingConfig
- type OctopusUpstreamConfig
- type OpenAPIAggregator
- type OpenAPIConfig
- type OpenAPIService
- type PathRewriter
- type RateLimitConfig
- type RateLimitStore
- type RateLimiter
- type RequestHook
- type RequestLimiter
- type ResponseCache
- func (rc *ResponseCache) Get(r *http.Request, route *Route) *CachedResponse
- func (rc *ResponseCache) Invalidate(ctx context.Context, method, path string) error
- func (rc *ResponseCache) Set(r *http.Request, route *Route, statusCode int, headers http.Header, ...)
- func (rc *ResponseCache) Stats() *CacheStats
- func (rc *ResponseCache) WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)
- type ResponseCacher
- type ResponseHook
- type RetryConfig
- type RetryPolicy
- type Route
- type RouteAuthConfig
- type RouteCacheConfig
- type RouteChangeHook
- type RouteConfig
- type RouteDTO
- type RouteEvent
- type RouteEventType
- type RouteProtocol
- type RouteRegistry
- type RouteSource
- type RouteStats
- type RouteStore
- type SSEConfig
- type ServiceDiscoverer
- type ServiceDiscovery
- type ServiceFilter
- type ServiceInstanceInfo
- type ServiceOpenAPISpec
- type StatsRecorder
- type TLSConfig
- type TLSManager
- type TLSProvider
- type Target
- func (t *Target) DecrConns()
- func (t *Target) GetID() string
- func (t *Target) GetTLS() *TargetTLSConfig
- func (t *Target) GetURL() string
- func (t *Target) HealthPath() string
- func (t *Target) IncrConns()
- func (t *Target) IsDraining() bool
- func (t *Target) IsHealthy() bool
- func (t *Target) RecordRequest(latency time.Duration, isError bool)
- func (t *Target) SetDraining(v bool)
- func (t *Target) SetHealthy(healthy bool)
- func (t *Target) Snapshot()
- func (t *Target) Stats() TargetStats
- type TargetConfig
- type TargetDTO
- type TargetStats
- type TargetTLSConfig
- type TimeoutConfig
- type TracingConfig
- type TrafficMatch
- type TrafficMatchType
- type TrafficPolicy
- type TrafficRouter
- type TrafficRule
- type TrafficSplitConfig
- type TrafficSplitType
- type TransformConfig
- type UpstreamHealthEvent
- type UpstreamHealthHook
- type ValidationError
- type ValidationErrors
- type WAF
- type WAFConfig
- type WAFPlugin
- type WAFRule
- type WAFViolation
- type WSBroadcaster
- type WebSocketConfig
Constants ¶
const (
// ServiceKey is the DI key for the gateway service.
ServiceKey = "bastion"
)
DI container keys for the gateway extension.
Variables ¶
var ErrCircuitNotFound = errors.New("bastion: no circuit breaker for target")
ErrCircuitNotFound is returned by ResetCircuit for a target id with no breaker. Breakers are created on a target's first proxied request, so a target that has never served traffic has none.
Functions ¶
func GatewayMiddleware ¶
GatewayMiddleware wraps http.Handler with gateway-level middleware.
func IsExtensionPathExcluded ¶
func IsExtensionPathExcluded(upstreamPath string, filter *ExtensionPathFilter) bool
IsExtensionPathExcluded checks whether an upstream path should be excluded based on the given extension path filter.
Filtering logic (in priority order):
- If the path starts with any IncludePrefixes entry → include (highest priority).
- If the path starts with any ExcludePrefixes entry → exclude.
- If any path segment matches a KnownExtensions name that is NOT in AllowedExtensions → exclude.
- Otherwise → include (native service path).
This handles both direct mounts (/{ext}/...) and nested mounts (/api/{ext}/v1/...) because it checks ALL path segments, not just the first.
func New ¶
func New(opts ...ConfigOption) forge.Extension
New creates the core bastion gateway.
On its own it proxies nothing. The proxy engine, route manager and admin API are built in subpackages that import this one, so they have to be injected (SetProxyHandler and friends) before Start, or no catch-all route is registered. gateway.New does that for you and keeps the store packages out of your build; extension.New does the same and adds grove-backed persistence.
func RewritePath ¶
RewritePath returns the path to send upstream for a request on route. It applies the route's rules in this order: StripPrefix removes the route's path prefix, AddPrefix is put in front, and then RewritePath, a "pattern:replacement" regex rule, runs on the result. The rule splits at the first colon, so the pattern can't contain one. An invalid rule leaves the path as it is.
func ValidateConfig ¶
ValidateConfig validates the gateway configuration and returns all errors found.
func ValidateTLSConfig ¶
ValidateTLSConfig checks that the TLS configuration is valid. Deprecated: Use security.ValidateTLSConfig directly.
Types ¶
type APIKeyAuthProvider ¶
type APIKeyAuthProvider = security.APIKeyAuthProvider
APIKeyAuthProvider is a backward-compatible alias for security.APIKeyAuthProvider.
func NewAPIKeyAuthProvider ¶
func NewAPIKeyAuthProvider(name, header, queryParam string, keys []*APIKeyEntry) *APIKeyAuthProvider
NewAPIKeyAuthProvider creates an API key auth provider. Deprecated: Use security.NewAPIKeyAuthProvider directly.
type APIKeyEntry ¶
type APIKeyEntry = security.APIKeyEntry
APIKeyEntry is a backward-compatible alias for security.APIKeyEntry.
type AccessLogConfig ¶
type AccessLogConfig = observability.AccessLogConfig
AccessLogConfig holds access logging settings. The canonical definition lives in the observability subpackage.
type AccessLogWriter ¶
type AccessLogWriter interface {
Log(r *http.Request, statusCode int, latency time.Duration, route *Route, target *Target)
LogAdminAction(action, resource, result string, r *http.Request)
}
AccessLogWriter logs HTTP request/response access entries.
type AccessLogger
deprecated
type AccessLogger = observability.AccessLogger
AccessLogger is an alias for observability.AccessLogger.
Deprecated: Use observability.AccessLogger directly.
func NewAccessLogger
deprecated
func NewAccessLogger(config AccessLogConfig, logger forge.Logger) *AccessLogger
NewAccessLogger creates a new access logger.
Deprecated: Use observability.NewAccessLogger directly.
type AdminAuthConfig ¶
type AdminAuthConfig = security.AdminAuthConfig
AdminAuthConfig is a backward-compatible alias for security.AdminAuthConfig.
type AdminAuthMiddleware ¶
type AdminAuthMiddleware = security.AdminAuthMiddleware
AdminAuthMiddleware is a backward-compatible alias for security.AdminAuthMiddleware.
func NewAdminAuthMiddleware ¶
func NewAdminAuthMiddleware(config AdminAuthConfig) *AdminAuthMiddleware
NewAdminAuthMiddleware creates a new admin auth middleware. Deprecated: Use security.NewAdminAuthMiddleware directly.
type AsyncAPIAggregator ¶
type AsyncAPIAggregator = disc.AsyncAPIAggregator
AsyncAPIAggregator is a backward-compatible alias for discovery.AsyncAPIAggregator.
func NewAsyncAPIAggregator ¶
func NewAsyncAPIAggregator(config AsyncAPIConfig, logger forge.Logger, sd *ServiceDiscovery) *AsyncAPIAggregator
NewAsyncAPIAggregator creates a new AsyncAPI aggregator.
type AsyncAPIConfig ¶
type AsyncAPIConfig = disc.AsyncAPIConfig
AsyncAPIConfig holds AsyncAPI aggregation settings.
Canonical definition: discovery.AsyncAPIConfig
func DefaultAsyncAPIConfig ¶
func DefaultAsyncAPIConfig() AsyncAPIConfig
DefaultAsyncAPIConfig returns defaults for AsyncAPI aggregation.
type AuditAction ¶
type AuditAction = observability.AuditAction
AuditAction represents the type of admin action taken.
Canonical definition: observability.AuditAction
const ( AuditRouteCreated AuditAction = observability.AuditRouteCreated AuditRouteUpdated AuditAction = observability.AuditRouteUpdated AuditRouteDeleted AuditAction = observability.AuditRouteDeleted AuditRouteToggled AuditAction = observability.AuditRouteToggled AuditConfigChanged AuditAction = observability.AuditConfigChanged AuditDiscoveryForced AuditAction = observability.AuditDiscoveryForced AuditCircuitReset AuditAction = observability.AuditCircuitReset AuditCacheCleared AuditAction = observability.AuditCacheCleared )
type AuditConfig ¶
type AuditConfig = observability.AuditConfig
AuditConfig configures audit logging.
Canonical definition: observability.AuditConfig
type AuditEvent ¶
type AuditEvent = observability.AuditEvent
AuditEvent represents an auditable action in the gateway.
Canonical definition: observability.AuditEvent
type AuditLogger
deprecated
type AuditLogger = observability.AuditLogger
AuditLogger is an alias for observability.AuditLogger.
Deprecated: Use observability.AuditLogger directly.
func NewAuditLogger
deprecated
func NewAuditLogger(config AuditConfig, logger forge.Logger) *AuditLogger
NewAuditLogger creates a new audit logger.
Deprecated: Use observability.NewAuditLogger directly.
type AuditSink ¶
type AuditSink = observability.AuditSink
AuditSink is the interface for consuming audit events.
Canonical definition: observability.AuditSink
type AuthConfig ¶
type AuthConfig = security.AuthConfig
AuthConfig holds gateway-level auth settings.
Canonical definition: security.AuthConfig
type AuthError ¶
AuthError represents an authentication failure.
Canonical definition: security.AuthError
type AuthProvider ¶
type AuthProvider = security.AuthProvider
AuthProvider is the gateway's interface for authentication providers.
Canonical definition: security.AuthProvider
type AuthRegistry ¶
type AuthRegistry = security.AuthRegistry
AuthRegistry manages authentication providers for the gateway.
Canonical definition: security.AuthRegistry
type Authenticator ¶
type Authenticator interface {
SetForgeAuth(registry AuthRegistry)
RegisterProvider(provider AuthProvider)
Authenticate(r *http.Request, route *Route) (*GatewayAuthContext, error)
ForwardAuthHeaders(r *http.Request, authCtx *GatewayAuthContext)
}
Authenticator handles gateway-level authentication.
type BackoffStrategy ¶
type BackoffStrategy string
BackoffStrategy defines retry backoff algorithms.
const ( // BackoffExponential uses exponential backoff. BackoffExponential BackoffStrategy = "exponential" // BackoffLinear uses linear backoff. BackoffLinear BackoffStrategy = "linear" // BackoffFixed uses a fixed delay. BackoffFixed BackoffStrategy = "fixed" )
type BasePlugin ¶
type BasePlugin struct {
PluginName string
}
BasePlugin provides no-op defaults for the GatewayPlugin interface, allowing plugins to override only the methods they care about.
func (*BasePlugin) Name ¶
func (bp *BasePlugin) Name() string
func (*BasePlugin) OnError ¶
func (bp *BasePlugin) OnError(_ error, _ *Route, _ http.ResponseWriter)
func (*BasePlugin) OnResponse ¶
func (bp *BasePlugin) OnResponse(_ *http.Response, _ *Route)
type BearerTokenAuthProvider ¶
type BearerTokenAuthProvider = security.BearerTokenAuthProvider
BearerTokenAuthProvider is a backward-compatible alias for security.BearerTokenAuthProvider.
func NewBearerTokenAuthProvider ¶
func NewBearerTokenAuthProvider(name string, validate func(ctx context.Context, token string) (*GatewayAuthContext, error)) *BearerTokenAuthProvider
NewBearerTokenAuthProvider creates a bearer token auth provider with a custom validator. Deprecated: Use security.NewBearerTokenAuthProvider directly.
type Breaker ¶
type Breaker interface {
Allow() bool
RecordSuccess()
RecordFailure()
// ReleaseProbe returns a half-open probe slot for a request that
// neither succeeded nor failed.
ReleaseProbe()
State() CircuitState
Reset()
}
Breaker represents a single circuit breaker for an upstream target.
type BufferPoolConfig ¶
type BufferPoolConfig struct {
MaxRequestBodySize int `json:"maxRequestBodySize" yaml:"max_request_body_size"`
MaxResponseBodySize int `json:"maxResponseBodySize" yaml:"max_response_body_size"`
}
BufferPoolConfig holds buffer pool settings.
type CBConfig ¶
type CBConfig struct {
FailureThreshold int `json:"failureThreshold"`
ResetTimeout time.Duration `json:"resetTimeout"`
HalfOpenMax int `json:"halfOpenMax"`
}
CBConfig is a per-route circuit breaker override.
type CORSConfig ¶
type CORSConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
AllowOrigins []string `json:"allowOrigins,omitempty" yaml:"allow_origins"`
AllowMethods []string `json:"allowMethods,omitempty" yaml:"allow_methods"`
AllowHeaders []string `json:"allowHeaders,omitempty" yaml:"allow_headers"`
ExposeHeaders []string `json:"exposeHeaders,omitempty" yaml:"expose_headers"`
AllowCreds bool `json:"allowCredentials" yaml:"allow_credentials"`
MaxAge int `json:"maxAge" yaml:"max_age"`
}
CORSConfig holds CORS settings.
type CacheStats ¶
type CacheStats = middleware.CacheStats
CacheStats tracks cache hit/miss metrics.
Canonical definition: middleware.CacheStats
type CacheStatsReader ¶
CacheStatsReader provides read access to cache statistics.
type CacheStore ¶
type CacheStore = middleware.CacheStore
CacheStore is the gateway's interface for a cache backend.
Canonical definition: middleware.CacheStore
type CachedResponse ¶
type CachedResponse = middleware.CachedResponse
CachedResponse represents a cached HTTP response.
Canonical definition: middleware.CachedResponse
type CachingConfig ¶
type CachingConfig = middleware.CachingConfig
CachingConfig holds response caching settings.
Canonical definition: middleware.CachingConfig
type CircuitBreakHook ¶
type CircuitBreakHook func(targetID string, from, to CircuitState)
CircuitBreakHook is called when a circuit breaker state changes.
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
FailureThreshold int `json:"failureThreshold" yaml:"failure_threshold"`
FailureWindow time.Duration `json:"failureWindow" yaml:"failure_window"`
ResetTimeout time.Duration `json:"resetTimeout" yaml:"reset_timeout"`
HalfOpenMax int `json:"halfOpenMax" yaml:"half_open_max"`
}
CircuitBreakerConfig holds circuit breaker settings.
type CircuitBreakerSnapshot ¶
type CircuitBreakerSnapshot struct {
TargetID string `json:"targetId"`
State CircuitState `json:"state"`
FailureCount int `json:"failureCount"`
SuccessCount int `json:"successCount"`
LastFailure time.Time `json:"lastFailure"`
LastStateChange time.Time `json:"lastStateChange"`
UpdatedAt time.Time `json:"updatedAt"`
}
CircuitBreakerSnapshot is the persistable state of a circuit breaker.
type CircuitBreakerStore ¶
type CircuitBreakerStore interface {
// GetState returns the persisted state for a target.
GetState(ctx context.Context, targetID string) (*CircuitBreakerSnapshot, error)
// SaveState persists the current circuit breaker state for a target.
SaveState(ctx context.Context, snap *CircuitBreakerSnapshot) error
// ListStates returns all persisted circuit breaker states.
ListStates(ctx context.Context) ([]*CircuitBreakerSnapshot, error)
// DeleteState removes the persisted state for a target.
DeleteState(ctx context.Context, targetID string) error
}
CircuitBreakerStore persists circuit breaker state snapshots.
type CircuitControl ¶
type CircuitControl interface {
Get(targetID string) Breaker
GetWithConfig(targetID string, cfg *CBConfig) Breaker
Remove(targetID string)
SetOnStateChange(fn func(targetID string, from, to CircuitState))
Snapshots() []CircuitBreakerSnapshot
Reset(targetID string) bool
}
CircuitControl manages circuit breakers across all upstream targets.
type CircuitState ¶
type CircuitState = observability.CircuitState
CircuitState represents the circuit breaker state. The canonical definition lives in the observability subpackage.
const ( // CircuitClosed allows requests through (normal operation). CircuitClosed CircuitState = observability.CircuitClosed // CircuitOpen rejects requests (fail-fast). CircuitOpen CircuitState = observability.CircuitOpen // CircuitHalfOpen allows limited probe requests. CircuitHalfOpen CircuitState = observability.CircuitHalfOpen )
type CompressionConfig ¶
type CompressionConfig = middleware.CompressionConfig
CompressionConfig configures response compression.
Canonical definition: middleware.CompressionConfig
type CompressionMiddleware ¶
type CompressionMiddleware = middleware.CompressionMiddleware
CompressionMiddleware wraps an http.Handler with gzip compression.
Canonical definition: middleware.CompressionMiddleware
func NewCompressionMiddleware ¶
func NewCompressionMiddleware(config CompressionConfig) *CompressionMiddleware
NewCompressionMiddleware creates a new compression middleware.
type Config ¶
type Config struct {
// Enabled determines if the gateway is active
Enabled bool `json:"enabled" yaml:"enabled"`
// BasePath is the prefix for all proxied routes (e.g., "/gw")
BasePath string `json:"basePath" yaml:"base_path"`
// Routes are manually defined upstream routes
Routes []RouteConfig `json:"routes" yaml:"routes"`
// Timeouts for upstream connections
Timeouts TimeoutConfig `json:"timeouts" yaml:"timeouts"`
// Retry is the global retry policy
Retry RetryConfig `json:"retry" yaml:"retry"`
// BufferPool configures request/response buffer sizes
BufferPool BufferPoolConfig `json:"bufferPool" yaml:"buffer_pool"`
// CircuitBreaker is the global circuit breaker config
CircuitBreaker CircuitBreakerConfig `json:"circuitBreaker" yaml:"circuit_breaker"`
// RateLimiting is the global rate limiting config
RateLimiting RateLimitConfig `json:"rateLimiting" yaml:"rate_limiting"`
// HealthCheck configures upstream health checking
HealthCheck HealthCheckConfig `json:"healthCheck" yaml:"health_check"`
// LoadBalancing configures the load balancing strategy
LoadBalancing LoadBalancingConfig `json:"loadBalancing" yaml:"load_balancing"`
// TrafficSplit configures global traffic splitting
TrafficSplit TrafficSplitConfig `json:"trafficSplit" yaml:"traffic_split"`
// Auth configures gateway-level authentication
Auth AuthConfig `json:"auth" yaml:"auth"`
// TLS configures upstream TLS/mTLS
TLS TLSConfig `json:"tls" yaml:"tls"`
// IPFilter configures IP allow/deny lists
IPFilter IPFilterConfig `json:"ipFilter" yaml:"ip_filter"`
// CORS configures gateway-level CORS
CORS CORSConfig `json:"cors" yaml:"cors"`
// Caching configures response caching
Caching CachingConfig `json:"caching" yaml:"caching"`
// Discovery configures FARP-based auto-discovery
Discovery DiscoveryConfig `json:"discovery" yaml:"discovery"`
// Metrics configures Prometheus metrics
Metrics MetricsConfig `json:"metrics" yaml:"metrics"`
// Tracing is accepted but not read. Bastion's spans follow the Forge
// app's tracing config; the field stays so existing config parses.
Tracing TracingConfig `json:"tracing" yaml:"tracing"`
// AccessLog configures structured access logging
AccessLog AccessLogConfig `json:"accessLog" yaml:"access_log"`
// OpenAPI configures the aggregated OpenAPI spec from all upstream services
OpenAPI OpenAPIConfig `json:"openapi" yaml:"openapi"`
// AsyncAPI configures the aggregated AsyncAPI spec from all upstream services
AsyncAPI AsyncAPIConfig `json:"asyncapi" yaml:"asyncapi"`
// Dashboard configures the admin UI
Dashboard DashboardConfig `json:"dashboard" yaml:"dashboard"`
// WebSocket configures WebSocket proxy settings
WebSocket WebSocketConfig `json:"webSocket" yaml:"web_socket"`
// SSE configures SSE proxy settings
SSE SSEConfig `json:"sse" yaml:"sse"`
}
Config holds the complete gateway configuration.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns the default gateway configuration.
func FromOctopusConfig ¶
func FromOctopusConfig(oc OctopusConfig) Config
FromOctopusConfig converts an octopus-format config to bastion's native Config.
type ConfigOption ¶
type ConfigOption func(*Config)
ConfigOption configures the gateway extension.
func WithAccessLog ¶
func WithAccessLog(al AccessLogConfig) ConfigOption
WithAccessLog sets the access log configuration.
func WithAdminMiddleware ¶
func WithAdminMiddleware(mw ...forge.Middleware) ConfigOption
WithAdminMiddleware adds middleware in front of every admin API handler, for auth that a static token can't express. Calls accumulate. See DashboardConfig.AdminMiddleware.
func WithAdminToken ¶
func WithAdminToken(token string) ConfigOption
WithAdminToken requires "Authorization: Bearer <token>" on every admin API request. See DashboardConfig.AdminToken.
func WithAllowUnauthenticatedAdmin ¶
func WithAllowUnauthenticatedAdmin(allow bool) ConfigOption
WithAllowUnauthenticatedAdmin acknowledges that the admin API runs with no authentication of its own. See DashboardConfig.AllowUnauthenticatedAdmin.
func WithAsyncAPI ¶
func WithAsyncAPI(a AsyncAPIConfig) ConfigOption
WithAsyncAPI sets the AsyncAPI aggregation configuration.
func WithAsyncAPIEnabled ¶
func WithAsyncAPIEnabled(enabled bool) ConfigOption
WithAsyncAPIEnabled enables/disables AsyncAPI aggregation.
func WithBasePath ¶
func WithBasePath(path string) ConfigOption
WithBasePath sets the base path prefix for all gateway routes.
func WithCaching ¶
func WithCaching(caching CachingConfig) ConfigOption
WithCaching sets the caching configuration.
func WithCircuitBreaker ¶
func WithCircuitBreaker(cb CircuitBreakerConfig) ConfigOption
WithCircuitBreaker sets the circuit breaker configuration.
func WithDashboard ¶
func WithDashboard(d DashboardConfig) ConfigOption
WithDashboard sets the dashboard configuration.
func WithDashboardEnabled ¶
func WithDashboardEnabled(enabled bool) ConfigOption
WithDashboardEnabled enables/disables the admin dashboard.
func WithDiscovery ¶
func WithDiscovery(disc DiscoveryConfig) ConfigOption
WithDiscovery sets the discovery configuration.
func WithDiscoveryAutoPrefix ¶
func WithDiscoveryAutoPrefix(enabled bool) ConfigOption
WithDiscoveryAutoPrefix sets whether discovered services get automatic path prefixes.
func WithDiscoveryEnabled ¶
func WithDiscoveryEnabled(enabled bool) ConfigOption
WithDiscoveryEnabled enables/disables FARP discovery.
func WithDiscoveryPollInterval ¶
func WithDiscoveryPollInterval(d time.Duration) ConfigOption
WithDiscoveryPollInterval sets the service discovery polling interval.
func WithDiscoveryPrefixOverrides ¶
func WithDiscoveryPrefixOverrides(overrides map[string]string) ConfigOption
WithDiscoveryPrefixOverrides sets per-service route prefix overrides. An empty string value mounts the service at root (no prefix).
Example: WithDiscoveryPrefixOverrides(map[string]string{"twinos": ""}) mounts "twinos" at / instead of /twinos.
func WithDiscoveryPrefixTemplate ¶
func WithDiscoveryPrefixTemplate(tmpl string) ConfigOption
WithDiscoveryPrefixTemplate sets the template for auto-generated route prefixes.
func WithDiscoveryPushInstanceTTL ¶
func WithDiscoveryPushInstanceTTL(ttl time.Duration) ConfigOption
WithDiscoveryPushInstanceTTL sets the TTL for push-registered service instances. Instances that do not re-register within this duration are automatically evicted. Set to 0 to disable TTL (default).
func WithDiscoveryServiceFilters ¶
func WithDiscoveryServiceFilters(filters ...ServiceFilter) ConfigOption
WithDiscoveryServiceFilters sets the service filters for discovery.
func WithDiscoveryStripPrefix ¶
func WithDiscoveryStripPrefix(strip bool) ConfigOption
WithDiscoveryStripPrefix sets whether auto-generated prefixes are stripped before proxying.
func WithDiscoveryWatchMode ¶
func WithDiscoveryWatchMode(enabled bool) ConfigOption
WithDiscoveryWatchMode sets whether discovery uses watch mode instead of polling.
func WithEnabled ¶
func WithEnabled(enabled bool) ConfigOption
WithEnabled sets whether the gateway is enabled.
func WithExtensionFilter ¶
func WithExtensionFilter(filter ExtensionPathFilter) ConfigOption
WithExtensionFilter adds an extension path filter for a specific service. Extension paths matching knownExtensions but not in allowedExtensions will be excluded from the OpenAPI spec and optionally blocked at the proxy level.
func WithHealthCheck ¶
func WithHealthCheck(hc HealthCheckConfig) ConfigOption
WithHealthCheck sets the health check configuration.
func WithIPFilter ¶
func WithIPFilter(ipf IPFilterConfig) ConfigOption
WithIPFilter sets the IP filter configuration.
func WithLoadBalancing ¶
func WithLoadBalancing(lb LoadBalancingConfig) ConfigOption
WithLoadBalancing sets the load balancing strategy.
func WithMetrics ¶
func WithMetrics(m MetricsConfig) ConfigOption
WithMetrics sets the metrics configuration.
func WithOctopusConfig ¶
func WithOctopusConfig(oc OctopusConfig) ConfigOption
WithOctopusConfig applies an octopus-format config to the gateway.
func WithOctopusConfigFile ¶
func WithOctopusConfigFile(path string) ConfigOption
WithOctopusConfigFile loads and applies an octopus-format YAML config file.
func WithOpenAPI ¶
func WithOpenAPI(o OpenAPIConfig) ConfigOption
WithOpenAPI sets the OpenAPI aggregation configuration.
func WithOpenAPIDisableServiceTags ¶
func WithOpenAPIDisableServiceTags(disabled bool) ConfigOption
WithOpenAPIDisableServiceTags disables automatic per-service tag creation and per-operation tag injection in the merged OpenAPI spec.
func WithOpenAPIEnabled ¶
func WithOpenAPIEnabled(enabled bool) ConfigOption
WithOpenAPIEnabled enables/disables OpenAPI aggregation.
func WithOpenAPIGatewayDocs ¶
func WithOpenAPIGatewayDocs(enabled bool) ConfigOption
WithOpenAPIGatewayDocs enables serving the gateway's own admin API documentation at the dashboard-prefixed swagger path (e.g., /gateway/swagger). Disabled by default.
func WithOpenAPIRootDocs ¶
func WithOpenAPIRootDocs(enabled bool) ConfigOption
WithOpenAPIRootDocs enables serving the aggregated OpenAPI spec and Swagger UI at root-level paths (/openapi.json and /docs) in addition to the dashboard-prefixed paths.
func WithOpenAPIServiceTagOnly ¶
func WithOpenAPIServiceTagOnly(enabled bool) ConfigOption
WithOpenAPIServiceTagOnly replaces all upstream operation tags with just the service-name tag. Ignored when DisableServiceTags is true.
func WithRateLimiting ¶
func WithRateLimiting(rl RateLimitConfig) ConfigOption
WithRateLimiting sets the rate limiting configuration.
func WithRetry ¶
func WithRetry(retry RetryConfig) ConfigOption
WithRetry sets the retry configuration.
func WithRoute ¶
func WithRoute(route RouteConfig) ConfigOption
WithRoute adds a manual route configuration.
func WithRoutes ¶
func WithRoutes(routes []RouteConfig) ConfigOption
WithRoutes sets all manual route configurations.
func WithServiceRoute ¶
func WithServiceRoute(serviceName, path, targetURL, openapiSpecURL string) ConfigOption
WithServiceRoute adds a manual route associated with a named service and its OpenAPI specification URL. The service's spec will be included in the gateway's aggregated API documentation at /docs.
func WithTimeouts ¶
func WithTimeouts(timeouts TimeoutConfig) ConfigOption
WithTimeouts sets the timeout configuration.
func WithTracing ¶
func WithTracing(t TracingConfig) ConfigOption
WithTracing sets Config.Tracing, which the gateway doesn't read. Configure tracing on the Forge app instead. The option is kept so existing code still compiles.
func WithWebSocket ¶
func WithWebSocket(ws WebSocketConfig) ConfigOption
WithWebSocket sets the WebSocket proxy configuration.
type ConfigWatcher ¶
type ConfigWatcher struct {
// contains filtered or unexported fields
}
ConfigWatcher monitors a config file and triggers a callback when the file changes. It uses polling rather than OS-specific file watchers for portability.
func NewConfigWatcher ¶
func NewConfigWatcher(path string, interval time.Duration, onChange func(Config)) *ConfigWatcher
NewConfigWatcher creates a config file watcher.
func (*ConfigWatcher) SetErrorHandler ¶
func (cw *ConfigWatcher) SetErrorHandler(fn func(error))
SetErrorHandler sets a callback for errors during config reload.
func (*ConfigWatcher) Start ¶
func (cw *ConfigWatcher) Start()
Start begins polling the config file for changes.
func (*ConfigWatcher) Stop ¶
func (cw *ConfigWatcher) Stop()
Stop ends the polling loop and waits for it to finish.
type DashboardConfig ¶
type DashboardConfig struct {
// Enabled gates the admin REST API, the WebSocket hub, and the
// OpenAPI/AsyncAPI endpoints.
Enabled bool `json:"enabled" yaml:"enabled"`
// BasePath prefixes the admin REST API, the WebSocket hub, and the
// OpenAPI/AsyncAPI endpoints.
BasePath string `json:"basePath" yaml:"base_path"`
// Title is unused. It is kept so existing configuration still parses.
Title string `json:"title,omitempty" yaml:"title"`
// Realtime gates the WebSocket hub.
Realtime bool `json:"realtime" yaml:"realtime"`
// AdminToken, when set, is the bearer token every admin API request
// has to carry ("Authorization: Bearer <token>"). It covers the REST
// API under BasePath+"/api" and the WebSocket hub. It is never written
// out as JSON, so the admin config endpoint doesn't hand it back.
AdminToken string `json:"-" yaml:"admin_token"`
// AdminMiddleware runs in front of every admin API handler, after the
// AdminToken check. Use it to plug in your own auth: a session check,
// an mTLS identity, an authsome guard. Set it with WithAdminMiddleware.
AdminMiddleware []forge.Middleware `json:"-" yaml:"-"`
// AllowUnauthenticatedAdmin says you mean to serve the admin API with
// neither AdminToken nor AdminMiddleware, say behind a private network
// or an authenticating proxy. Without it the gateway logs a warning at
// start every time it registers an open admin API.
AllowUnauthenticatedAdmin bool `json:"allowUnauthenticatedAdmin" yaml:"allow_unauthenticated_admin"`
}
DashboardConfig holds admin surface settings. The Go-rendered dashboard has been retired; the React plugin reads the bastion contract contributor.
func (DashboardConfig) AdminAuthenticated ¶
func (d DashboardConfig) AdminAuthenticated() bool
AdminAuthenticated reports whether the admin API has any authentication configured: an AdminToken, AdminMiddleware, or both.
type DiscoveredService ¶
type DiscoveredService = disc.DiscoveredService
DiscoveredService represents a service found via FARP/discovery.
Canonical definition: discovery.DiscoveredService
type DiscoveryConfig ¶
type DiscoveryConfig = disc.DiscoveryConfig
DiscoveryConfig holds FARP auto-discovery settings.
Canonical definition: discovery.DiscoveryConfig
type DiscoveryService ¶
type DiscoveryService interface {
// ListServices lists all registered service names.
ListServices(ctx context.Context) ([]string, error)
// DiscoverHealthy returns healthy instances for a service.
DiscoverHealthy(ctx context.Context, serviceName string) ([]*ServiceInstanceInfo, error)
}
DiscoveryService is the interface that the gateway requires from a discovery provider. This decouples the gateway from the concrete discovery.Service type.
type DistributedRateLimiter ¶
type DistributedRateLimiter = middleware.DistributedRateLimiter
DistributedRateLimiter extends the basic RateLimiter with an external store for multi-instance rate limiting.
Canonical definition: middleware.DistributedRateLimiter
func NewDistributedRateLimiter ¶
func NewDistributedRateLimiter(config RateLimitConfig, store RateLimitStore) *DistributedRateLimiter
NewDistributedRateLimiter creates a rate limiter backed by an external store.
type ErrorHook ¶
type ErrorHook func(err error, route *Route, w http.ResponseWriter)
ErrorHook is called when an upstream error occurs.
type ExtensionPathFilter ¶
type ExtensionPathFilter = disc.ExtensionPathFilter
ExtensionPathFilter defines per-service extension path filtering.
Canonical definition: discovery.ExtensionPathFilter
type ForwardAuthProvider ¶
type ForwardAuthProvider = security.ForwardAuthProvider
ForwardAuthProvider is a backward-compatible alias for security.ForwardAuthProvider.
func NewForwardAuthProvider ¶
func NewForwardAuthProvider(name, endpoint string, headers []string) *ForwardAuthProvider
NewForwardAuthProvider creates a forward auth provider. Deprecated: Use security.NewForwardAuthProvider directly.
type Gateway ¶
type Gateway struct {
*forge.BaseExtension
// contains filtered or unexported fields
}
Gateway implements the Bastion API gateway.
func (*Gateway) AccessLog ¶
func (e *Gateway) AccessLog() *AccessLogger
AccessLog returns the access logger.
func (*Gateway) AsyncAPI ¶
func (e *Gateway) AsyncAPI() *AsyncAPIAggregator
AsyncAPI returns the AsyncAPI aggregator.
func (*Gateway) Circuits ¶
func (e *Gateway) Circuits() []CircuitBreakerSnapshot
Circuits returns a snapshot of every circuit breaker, sorted by target id. It is nil when circuit control is not wired.
func (*Gateway) Dependencies ¶
Dependencies returns extension dependencies.
func (*Gateway) Discovery ¶
func (e *Gateway) Discovery() *ServiceDiscovery
Discovery returns the service discovery integration.
func (*Gateway) GatewayMetrics ¶
func (e *Gateway) GatewayMetrics() *GatewayMetrics
GatewayMetrics returns the gateway's metrics, recorded through the Forge app's metrics. It is nil before Register and when metrics are disabled, and a nil value records nothing.
func (*Gateway) HealthMonitor ¶
HealthMonitor returns the health monitor.
func (*Gateway) Hub ¶
func (e *Gateway) Hub() WSBroadcaster
Hub returns the WebSocket hub for real-time updates.
func (*Gateway) OpenAPI ¶
func (e *Gateway) OpenAPI() *OpenAPIAggregator
OpenAPI returns the OpenAPI aggregator.
func (*Gateway) RateLimiter ¶
func (e *Gateway) RateLimiter() *RateLimiter
RateLimiter returns the rate limiter.
func (*Gateway) ResetCircuit ¶
ResetCircuit closes the breaker for targetID.
func (*Gateway) RouteManager ¶
func (e *Gateway) RouteManager() RouteRegistry
RouteManager returns the route registry.
func (*Gateway) RoutesPersisted ¶
RoutesPersisted reports whether a route store is wired, so a route created through the admin API survives a restart.
func (*Gateway) SetAdminHandlerSetup ¶
SetAdminHandlerSetup sets the callback for registering admin dashboard routes.
func (*Gateway) SetCacheStore ¶
func (e *Gateway) SetCacheStore(store CacheStore)
SetCacheStore sets an external cache store for response caching.
func (*Gateway) SetCircuitControl ¶
func (e *Gateway) SetCircuitControl(cb CircuitControl)
SetCircuitControl sets the circuit breaker manager.
func (*Gateway) SetDiscoveryService ¶
func (e *Gateway) SetDiscoveryService(svc DiscoveryService)
SetDiscoveryService sets the discovery service adapter and initializes the ServiceDiscovery integration. This is called by the extension adapter to inject the concrete discovery.Service dependency.
func (*Gateway) SetProxyHandler ¶
SetProxyHandler sets the HTTP handler for proxying.
func (*Gateway) SetRetryPolicy ¶
func (e *Gateway) SetRetryPolicy(r RetryPolicy)
SetRetryPolicy sets the retry executor.
func (*Gateway) SetRouteRegistry ¶
func (e *Gateway) SetRouteRegistry(rm RouteRegistry)
SetRouteRegistry sets the route manager implementation.
func (*Gateway) SetStatsRecorder ¶
func (e *Gateway) SetStatsRecorder(s StatsRecorder)
SetStatsRecorder sets the stats collector.
func (*Gateway) SetStore ¶
SetStore sets a composite store that provides persistence for all gateway subsystems (routes, circuit breakers, health checks, cache, rate limits, audit). The store is decomposed into subsystem-specific interfaces.
func (*Gateway) SetTrafficRouter ¶
func (e *Gateway) SetTrafficRouter(t TrafficRouter)
SetTrafficRouter sets the traffic splitter.
func (*Gateway) SetWSBroadcaster ¶
func (e *Gateway) SetWSBroadcaster(h WSBroadcaster)
SetWSBroadcaster sets the WebSocket hub for dashboard.
func (*Gateway) Snapshot ¶
func (e *Gateway) Snapshot() *GatewayStats
Snapshot returns current gateway statistics. Uptime counts from the moment Start completed and is zero before it. Cache counters come from the response cache, so they count real lookups only.
func (*Gateway) Start ¶
Start starts the bastion gateway. It is idempotent — calling Start() multiple times (e.g. when forge re-starts extensions after middleware application) is safe and only performs initialization once.
type GatewayAuth ¶
GatewayAuth is a backward-compatible alias for security.Auth.
func NewGatewayAuth ¶
func NewGatewayAuth(config AuthConfig, logger forge.Logger) *GatewayAuth
NewGatewayAuth creates a new gateway auth handler. Deprecated: Use security.NewAuth directly.
type GatewayAuthContext ¶
type GatewayAuthContext = security.AuthContext
GatewayAuthContext holds authenticated subject information for gateway requests.
Canonical definition: security.AuthContext
type GatewayMetrics
deprecated
type GatewayMetrics = observability.Metrics
GatewayMetrics is an alias for observability.Metrics.
Deprecated: Use observability.Metrics directly.
func NewGatewayMetrics
deprecated
func NewGatewayMetrics(metrics forge.Metrics, config MetricsConfig) *GatewayMetrics
NewGatewayMetrics creates a new gateway metrics collector.
Deprecated: Use observability.NewMetrics directly.
type GatewayPlugin ¶
type GatewayPlugin interface {
// Name returns a unique identifier for the plugin.
Name() string
// OnRequest is called before a request is forwarded to the upstream.
// Return a non-nil error to reject the request (short-circuits the pipeline).
OnRequest(r *http.Request, route *Route) error
// OnResponse is called after the upstream response is received.
OnResponse(resp *http.Response, route *Route)
// OnError is called when the upstream returns an error.
OnError(err error, route *Route, w http.ResponseWriter)
}
GatewayPlugin is a composable extension point for the gateway. Plugins are invoked in registration order at the request, response, and error stages of the proxy pipeline.
type GatewayStats ¶
type GatewayStats struct {
TotalRequests int64 `json:"totalRequests"`
TotalErrors int64 `json:"totalErrors"`
ActiveConns int64 `json:"activeConns"`
ActiveWSConns int64 `json:"activeWsConns"`
ActiveSSEConns int64 `json:"activeSseConns"`
// AvgLatencyMs is the mean over every answered upstream request since start.
AvgLatencyMs float64 `json:"avgLatencyMs"`
// P99LatencyMs is the nearest-rank p99 over the most recent LatencySamples responses.
P99LatencyMs float64 `json:"p99LatencyMs"`
// LatencySamples is how many recent responses P99LatencyMs covers.
LatencySamples int `json:"latencySamples"`
RequestsPerSec float64 `json:"requestsPerSec"`
CacheHits int64 `json:"cacheHits"`
CacheMisses int64 `json:"cacheMisses"`
RateLimited int64 `json:"rateLimited"`
CircuitBreaks int64 `json:"circuitBreaks"`
RetryAttempts int64 `json:"retryAttempts"`
// RetryBudgetExhausted counts retries the retry budget refused.
RetryBudgetExhausted int64 `json:"retryBudgetExhausted"`
TotalRoutes int `json:"totalRoutes"`
HealthyUpstreams int `json:"healthyUpstreams"`
TotalUpstreams int `json:"totalUpstreams"`
RouteStats map[string]*RouteStats `json:"routeStats,omitempty"`
Uptime int64 `json:"uptime"`
StartedAt time.Time `json:"startedAt"`
}
GatewayStats holds aggregated gateway traffic statistics.
type HeaderPolicy ¶
type HeaderPolicy struct {
Add map[string]string `json:"add,omitempty"`
Set map[string]string `json:"set,omitempty"`
Remove []string `json:"remove,omitempty"`
}
HeaderPolicy defines header manipulation rules.
type HealthCheckConfig ¶
HealthCheckConfig holds health check settings. This is a backward-compatible alias for health.Config.
type HealthCheckResult ¶
type HealthCheckResult = health.CheckResult
HealthCheckResult records a single health check outcome.
Canonical definition: health.CheckResult
type HealthChecker ¶
type HealthChecker interface {
Register(routeID string, target *Target)
Deregister(targetID string)
RecordPassiveFailure(targetID string)
RecordPassiveSuccess(targetID string)
Start(ctx context.Context)
Stop()
Health(ctx context.Context) error
SetOnHealthChange(fn func(event UpstreamHealthEvent))
}
HealthChecker manages health monitoring for upstream targets.
type HealthHistory ¶
HealthHistory is a backward-compatible alias for health.History.
func NewHealthHistory ¶
func NewHealthHistory(capacity int) *HealthHistory
NewHealthHistory creates a new HealthHistory. Deprecated: Use health.NewHistory directly.
type HealthMonitor ¶
HealthMonitor is a backward-compatible alias for health.Monitor.
func NewHealthMonitor ¶
func NewHealthMonitor(config HealthCheckConfig, logger forge.Logger) *HealthMonitor
NewHealthMonitor creates a new HealthMonitor. Deprecated: Use health.NewMonitor directly.
type HealthStore ¶
type HealthStore interface {
// RecordCheck persists a single health check result.
RecordCheck(ctx context.Context, result *HealthCheckResult) error
// GetHistory returns recent health check results for a target, newest first.
GetHistory(ctx context.Context, targetID string, limit int) ([]HealthCheckResult, error)
// GetLatestState returns the most recent health check for a target.
GetLatestState(ctx context.Context, targetID string) (*HealthCheckResult, error)
}
HealthStore persists health check results for upstream targets.
type HealthSummary ¶
HealthSummary provides a summary of health check history for a target.
Canonical definition: health.Summary
type HookEngine ¶
type HookEngine struct {
// contains filtered or unexported fields
}
HookEngine manages gateway hooks.
func (*HookEngine) OnCircuitBreak ¶
func (he *HookEngine) OnCircuitBreak(fn CircuitBreakHook)
OnCircuitBreak registers a circuit break hook.
func (*HookEngine) OnError ¶
func (he *HookEngine) OnError(fn ErrorHook)
OnError registers an error hook.
func (*HookEngine) OnRequest ¶
func (he *HookEngine) OnRequest(fn RequestHook)
OnRequest registers a request hook.
func (*HookEngine) OnResponse ¶
func (he *HookEngine) OnResponse(fn ResponseHook)
OnResponse registers a response hook.
func (*HookEngine) OnRouteChange ¶
func (he *HookEngine) OnRouteChange(fn RouteChangeHook)
OnRouteChange registers a route change hook.
func (*HookEngine) OnUpstreamHealth ¶
func (he *HookEngine) OnUpstreamHealth(fn UpstreamHealthHook)
OnUpstreamHealth registers an upstream health hook.
func (*HookEngine) RunOnCircuitBreak ¶
func (he *HookEngine) RunOnCircuitBreak(targetID string, from, to CircuitState)
RunOnCircuitBreak runs all circuit break hooks.
func (*HookEngine) RunOnError ¶
func (he *HookEngine) RunOnError(err error, route *Route, w http.ResponseWriter)
RunOnError runs all error hooks.
func (*HookEngine) RunOnRequest ¶
func (he *HookEngine) RunOnRequest(r *http.Request, route *Route) error
RunOnRequest runs all request hooks. Returns first error encountered.
func (*HookEngine) RunOnResponse ¶
func (he *HookEngine) RunOnResponse(resp *http.Response, route *Route)
RunOnResponse runs all response hooks.
func (*HookEngine) RunOnRouteChange ¶
func (he *HookEngine) RunOnRouteChange(event RouteEvent)
RunOnRouteChange runs all route change hooks.
func (*HookEngine) RunOnUpstreamHealth ¶
func (he *HookEngine) RunOnUpstreamHealth(event UpstreamHealthEvent)
RunOnUpstreamHealth runs all upstream health hooks.
type IPFilterConfig ¶
type IPFilterConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
AllowIPs []string `json:"allowIps,omitempty" yaml:"allow_ips"`
DenyIPs []string `json:"denyIps,omitempty" yaml:"deny_ips"`
}
IPFilterConfig holds IP allow/deny list settings.
type InMemoryCacheStore ¶
type InMemoryCacheStore = middleware.InMemoryCacheStore
InMemoryCacheStore provides a simple in-memory LRU cache for the gateway.
Canonical definition: middleware.InMemoryCacheStore
func NewInMemoryCacheStore ¶
func NewInMemoryCacheStore(maxSize int) *InMemoryCacheStore
NewInMemoryCacheStore creates a new in-memory cache store.
type InMemoryRateLimitStore ¶
type InMemoryRateLimitStore = middleware.InMemoryRateLimitStore
InMemoryRateLimitStore is a local implementation of RateLimitStore.
Canonical definition: middleware.InMemoryRateLimitStore
func NewInMemoryRateLimitStore ¶
func NewInMemoryRateLimitStore() *InMemoryRateLimitStore
NewInMemoryRateLimitStore creates a new in-memory rate limit store.
type JWTAuthConfig ¶
type JWTAuthConfig = security.JWTAuthConfig
JWTAuthConfig is a backward-compatible alias for security.JWTAuthConfig.
type JWTAuthProvider ¶
type JWTAuthProvider = security.JWTAuthProvider
JWTAuthProvider is a backward-compatible alias for security.JWTAuthProvider.
func NewJWTAuthProvider ¶
func NewJWTAuthProvider(config JWTAuthConfig) *JWTAuthProvider
NewJWTAuthProvider creates a JWT auth provider. Deprecated: Use security.NewJWTAuthProvider directly.
type LoadBalanceStrategy ¶
type LoadBalanceStrategy string
LoadBalanceStrategy defines load balancing algorithms.
const ( // LBRoundRobin selects targets in round-robin order. LBRoundRobin LoadBalanceStrategy = "roundRobin" // LBWeightedRoundRobin selects targets using smooth weighted round-robin. LBWeightedRoundRobin LoadBalanceStrategy = "weightedRoundRobin" // LBRandom selects a random target. LBRandom LoadBalanceStrategy = "random" // LBLeastConnections selects the target with fewest active connections. LBLeastConnections LoadBalanceStrategy = "leastConnections" // LBConsistentHash uses consistent hashing for sticky routing. LBConsistentHash LoadBalanceStrategy = "consistentHash" )
type LoadBalancer ¶
type LoadBalancer interface {
// Select picks a target from the provided list.
// The key is used for consistent hashing (may be empty for other strategies).
Select(targets []*Target, key string) *Target
}
LoadBalancer selects a target from a list of healthy targets.
type LoadBalancingConfig ¶
type LoadBalancingConfig struct {
Strategy LoadBalanceStrategy `json:"strategy" yaml:"strategy"`
ConsistentKey string `json:"consistentKey,omitempty" yaml:"consistent_key"`
}
LoadBalancingConfig holds load balancing settings.
type LogAuditSink
deprecated
type LogAuditSink = observability.LogAuditSink
LogAuditSink is an alias for observability.LogAuditSink.
Deprecated: Use observability.LogAuditSink directly.
func NewLogAuditSink
deprecated
func NewLogAuditSink(logger forge.Logger) *LogAuditSink
NewLogAuditSink creates a sink that writes audit events to a forge.Logger.
Deprecated: Use observability.NewLogAuditSink directly.
type MetricsConfig ¶
type MetricsConfig = observability.MetricsConfig
MetricsConfig holds metrics settings. The canonical definition lives in the observability subpackage.
type OctopusAPIKeyEntry ¶
type OctopusAPIKeyEntry struct {
Key string `yaml:"key" json:"key"`
Name string `yaml:"name" json:"name"`
Scopes []string `yaml:"scopes" json:"scopes"`
RateLimit *int `yaml:"rate_limit,omitempty" json:"rate_limit,omitempty"`
}
OctopusAPIKeyEntry mirrors octopus API key entries.
type OctopusAdminConfig ¶
type OctopusAdminConfig struct {
AuthProvider string `yaml:"auth_provider" json:"auth_provider"`
AllowedIPs []string `yaml:"allowed_ips" json:"allowed_ips"`
}
OctopusAdminConfig mirrors octopus admin settings.
type OctopusAuthConfig ¶
type OctopusAuthConfig struct {
DefaultProvider string `yaml:"default_provider" json:"default_provider"`
GlobalEnforce bool `yaml:"global_enforce" json:"global_enforce"`
SkipPaths []string `yaml:"skip_paths" json:"skip_paths"`
PrincipalHeader string `yaml:"principal_header" json:"principal_header"`
RolesHeader string `yaml:"roles_header" json:"roles_header"`
ScopesHeader string `yaml:"scopes_header" json:"scopes_header"`
TokenCacheTTL string `yaml:"token_cache_ttl" json:"token_cache_ttl"`
ErrorFormat string `yaml:"error_format" json:"error_format"`
}
OctopusAuthConfig mirrors octopus global auth settings.
type OctopusAuthProviderConfig ¶
type OctopusAuthProviderConfig struct {
Type string `yaml:"type" json:"type"`
// JWT fields
Secret string `yaml:"secret,omitempty" json:"secret,omitempty"`
PublicKey string `yaml:"public_key,omitempty" json:"public_key,omitempty"`
PublicKeyFile string `yaml:"public_key_file,omitempty" json:"public_key_file,omitempty"`
Algorithm string `yaml:"algorithm,omitempty" json:"algorithm,omitempty"`
Issuer string `yaml:"issuer,omitempty" json:"issuer,omitempty"`
Audience string `yaml:"audience,omitempty" json:"audience,omitempty"`
HeaderName string `yaml:"header_name,omitempty" json:"header_name,omitempty"`
TokenPrefix string `yaml:"token_prefix,omitempty" json:"token_prefix,omitempty"`
// OIDC fields
IssuerURL string `yaml:"issuer_url,omitempty" json:"issuer_url,omitempty"`
JWKSRefreshInterval string `yaml:"jwks_refresh_interval,omitempty" json:"jwks_refresh_interval,omitempty"`
RequiredScopes []string `yaml:"required_scopes,omitempty" json:"required_scopes,omitempty"`
FallbackProvider string `yaml:"fallback_provider,omitempty" json:"fallback_provider,omitempty"`
// API Key fields
QueryParam string `yaml:"query_param,omitempty" json:"query_param,omitempty"`
Keys []OctopusAPIKeyEntry `yaml:"keys,omitempty" json:"keys,omitempty"`
ExternalValidator string `yaml:"external_validator,omitempty" json:"external_validator,omitempty"`
// Forward Auth fields
Endpoint string `yaml:"endpoint,omitempty" json:"endpoint,omitempty"`
ForwardHeaders []string `yaml:"forward_headers,omitempty" json:"forward_headers,omitempty"`
ResponseHeaders []string `yaml:"response_headers,omitempty" json:"response_headers,omitempty"`
CacheTTL string `yaml:"cache_ttl,omitempty" json:"cache_ttl,omitempty"`
// mTLS fields
ClientCAFile string `yaml:"client_ca_file,omitempty" json:"client_ca_file,omitempty"`
RequireClientCert bool `yaml:"require_client_cert,omitempty" json:"require_client_cert,omitempty"`
ExtractCNAsPrincipal bool `yaml:"extract_cn_as_principal,omitempty" json:"extract_cn_as_principal,omitempty"`
CNToRoles map[string][]string `yaml:"cn_to_roles,omitempty" json:"cn_to_roles,omitempty"`
// Timeout (shared by forward_auth)
Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}
OctopusAuthProviderConfig mirrors octopus auth provider (tagged enum).
type OctopusCBConfig ¶
type OctopusCBConfig struct {
ErrorThreshold float32 `yaml:"error_threshold" json:"error_threshold"`
MinRequests int `yaml:"min_requests" json:"min_requests"`
Timeout string `yaml:"timeout" json:"timeout"`
}
OctopusCBConfig mirrors octopus circuit breaker settings.
type OctopusCORSConfig ¶
type OctopusCORSConfig struct {
AllowedOrigins []string `yaml:"allowed_origins" json:"allowed_origins"`
AllowedMethods []string `yaml:"allowed_methods" json:"allowed_methods"`
AllowedHeaders []string `yaml:"allowed_headers" json:"allowed_headers"`
ExposedHeaders []string `yaml:"exposed_headers" json:"exposed_headers"`
MaxAge int `yaml:"max_age" json:"max_age"`
AllowCredentials bool `yaml:"allow_credentials" json:"allow_credentials"`
}
OctopusCORSConfig mirrors octopus global CORS settings.
type OctopusCompressionConfig ¶
type OctopusCompressionConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Level int `yaml:"level" json:"level"`
MinSize int `yaml:"min_size" json:"min_size"`
Algorithms []string `yaml:"algorithms" json:"algorithms"`
}
OctopusCompressionConfig mirrors octopus compression settings.
type OctopusConfig ¶
type OctopusConfig struct {
Gateway OctopusGatewayConfig `yaml:"gateway" json:"gateway"`
Upstreams []OctopusUpstreamConfig `yaml:"upstreams" json:"upstreams"`
Routes []OctopusRouteConfig `yaml:"routes" json:"routes"`
Plugins []OctopusPluginConfig `yaml:"plugins" json:"plugins"`
FARP OctopusFARPConfig `yaml:"farp" json:"farp"`
Observability OctopusObservabilityConfig `yaml:"observability" json:"observability"`
AuthProviders map[string]OctopusAuthProviderConfig `yaml:"auth_providers" json:"auth_providers"`
Auth OctopusAuthConfig `yaml:"auth" json:"auth"`
CORS *OctopusCORSConfig `yaml:"cors" json:"cors"`
Admin OctopusAdminConfig `yaml:"admin" json:"admin"`
GRPC OctopusGRPCConfig `yaml:"grpc" json:"grpc"`
}
OctopusConfig mirrors the octopus gateway YAML configuration format. Use FromOctopusConfig to convert to bastion's native Config type.
func LoadOctopusConfig ¶
func LoadOctopusConfig(path string) (OctopusConfig, error)
LoadOctopusConfig reads and parses an octopus-format YAML config file.
type OctopusDiscoveryBackend ¶
type OctopusDiscoveryBackend struct {
Type string `yaml:"type" json:"type"`
Enabled bool `yaml:"enabled" json:"enabled"`
Config map[string]any `yaml:"config" json:"config"`
}
OctopusDiscoveryBackend mirrors an octopus discovery backend entry.
type OctopusFARPConfig ¶
type OctopusFARPConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
WatchInterval string `yaml:"watch_interval" json:"watch_interval"`
SchemaCacheTTL string `yaml:"schema_cache_ttl" json:"schema_cache_ttl"`
Discovery *OctopusFARPDiscoveryConfig `yaml:"discovery" json:"discovery"`
}
OctopusFARPConfig mirrors octopus FARP settings.
type OctopusFARPDiscoveryConfig ¶
type OctopusFARPDiscoveryConfig struct {
Backends []OctopusDiscoveryBackend `yaml:"backends" json:"backends"`
}
OctopusFARPDiscoveryConfig mirrors octopus FARP discovery backend settings.
type OctopusGRPCConfig ¶
type OctopusGRPCConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
MaxMessageSize int `yaml:"max_message_size" json:"max_message_size"`
EnableReflection bool `yaml:"enable_reflection" json:"enable_reflection"`
EnableGRPCWeb bool `yaml:"enable_grpc_web" json:"enable_grpc_web"`
DeadlinePropagation bool `yaml:"deadline_propagation" json:"deadline_propagation"`
Services map[string]string `yaml:"services" json:"services"`
}
OctopusGRPCConfig mirrors octopus gRPC settings.
type OctopusGatewayConfig ¶
type OctopusGatewayConfig struct {
Listen string `yaml:"listen" json:"listen"`
Workers int `yaml:"workers" json:"workers"`
RequestTimeout string `yaml:"request_timeout" json:"request_timeout"`
ShutdownTimeout string `yaml:"shutdown_timeout" json:"shutdown_timeout"`
MaxBodySize int `yaml:"max_body_size" json:"max_body_size"`
TLS *OctopusTLSConfig `yaml:"tls" json:"tls"`
Compression *OctopusCompressionConfig `yaml:"compression" json:"compression"`
InternalRoutePrefix *string `yaml:"internal_route_prefix" json:"internal_route_prefix"`
}
OctopusGatewayConfig mirrors octopus gateway.* settings.
type OctopusHealthCheckConfig ¶
type OctopusHealthCheckConfig struct {
Type string `yaml:"type" json:"type"`
Path string `yaml:"path" json:"path"`
Interval string `yaml:"interval" json:"interval"`
Timeout string `yaml:"timeout" json:"timeout"`
HealthyThreshold int `yaml:"healthy_threshold" json:"healthy_threshold"`
UnhealthyThreshold int `yaml:"unhealthy_threshold" json:"unhealthy_threshold"`
}
OctopusHealthCheckConfig mirrors octopus health check settings.
type OctopusInstanceConfig ¶
type OctopusInstanceConfig struct {
ID string `yaml:"id" json:"id"`
Host string `yaml:"host" json:"host"`
Port int `yaml:"port" json:"port"`
Weight int `yaml:"weight" json:"weight"`
Metadata map[string]string `yaml:"metadata" json:"metadata"`
}
OctopusInstanceConfig mirrors octopus instance definitions.
type OctopusLoggingConfig ¶
type OctopusLoggingConfig struct {
Level string `yaml:"level" json:"level"`
Format string `yaml:"format" json:"format"`
}
OctopusLoggingConfig mirrors octopus logging settings.
type OctopusMetricsConfig ¶
type OctopusMetricsConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
Endpoint string `yaml:"endpoint" json:"endpoint"`
}
OctopusMetricsConfig mirrors octopus metrics settings.
type OctopusObservabilityConfig ¶
type OctopusObservabilityConfig struct {
Logging OctopusLoggingConfig `yaml:"logging" json:"logging"`
Metrics OctopusMetricsConfig `yaml:"metrics" json:"metrics"`
Tracing OctopusTracingConfig `yaml:"tracing" json:"tracing"`
}
OctopusObservabilityConfig mirrors octopus observability settings.
type OctopusPluginConfig ¶
type OctopusPluginConfig struct {
Name string `yaml:"name" json:"name"`
PluginType string `yaml:"plugin_type" json:"plugin_type"`
Enabled bool `yaml:"enabled" json:"enabled"`
Priority int `yaml:"priority" json:"priority"`
Config map[string]any `yaml:"config" json:"config"`
}
OctopusPluginConfig mirrors octopus plugin definitions.
type OctopusRouteCORSConfig ¶
type OctopusRouteCORSConfig struct {
AllowedOrigins []string `yaml:"allowed_origins" json:"allowed_origins"`
AllowedMethods []string `yaml:"allowed_methods" json:"allowed_methods"`
AllowedHeaders []string `yaml:"allowed_headers" json:"allowed_headers"`
AllowCredentials bool `yaml:"allow_credentials" json:"allow_credentials"`
MaxAge int `yaml:"max_age" json:"max_age"`
}
OctopusRouteCORSConfig mirrors octopus per-route CORS override.
type OctopusRouteConfig ¶
type OctopusRouteConfig struct {
Path string `yaml:"path" json:"path"`
Methods []string `yaml:"methods" json:"methods"`
Upstream string `yaml:"upstream" json:"upstream"`
Priority int `yaml:"priority" json:"priority"`
StripPrefix *string `yaml:"strip_prefix" json:"strip_prefix"`
AddPrefix *string `yaml:"add_prefix" json:"add_prefix"`
Metadata map[string]string `yaml:"metadata" json:"metadata"`
AuthProvider *string `yaml:"auth_provider" json:"auth_provider"`
SkipAuth bool `yaml:"skip_auth" json:"skip_auth"`
RequireRoles []string `yaml:"require_roles" json:"require_roles"`
RequireScopes []string `yaml:"require_scopes" json:"require_scopes"`
AuthzRule *string `yaml:"authz_rule" json:"authz_rule"`
Timeout *string `yaml:"timeout" json:"timeout"`
RateLimit *OctopusRouteRateLimitConfig `yaml:"rate_limit" json:"rate_limit"`
CORS *OctopusRouteCORSConfig `yaml:"cors" json:"cors"`
}
OctopusRouteConfig mirrors octopus route definitions.
type OctopusRouteRateLimitConfig ¶
type OctopusRouteRateLimitConfig struct {
RequestsPerWindow int `yaml:"requests_per_window" json:"requests_per_window"`
WindowSize string `yaml:"window_size" json:"window_size"`
}
OctopusRouteRateLimitConfig mirrors octopus per-route rate limiting.
type OctopusTLSConfig ¶
type OctopusTLSConfig struct {
CertFile string `yaml:"cert_file" json:"cert_file"`
KeyFile string `yaml:"key_file" json:"key_file"`
ClientCAFile string `yaml:"client_ca_file" json:"client_ca_file"`
RequireClientCert bool `yaml:"require_client_cert" json:"require_client_cert"`
MinTLSVersion string `yaml:"min_tls_version" json:"min_tls_version"`
EnableCertReload bool `yaml:"enable_cert_reload" json:"enable_cert_reload"`
ReloadIntervalSecs int `yaml:"reload_interval_secs" json:"reload_interval_secs"`
}
OctopusTLSConfig mirrors octopus TLS settings.
type OctopusTracingConfig ¶
type OctopusTracingConfig struct {
Enabled bool `yaml:"enabled" json:"enabled"`
JaegerEndpoint string `yaml:"jaeger_endpoint" json:"jaeger_endpoint"`
}
OctopusTracingConfig mirrors octopus tracing settings.
type OctopusUpstreamConfig ¶
type OctopusUpstreamConfig struct {
Name string `yaml:"name" json:"name"`
Instances []OctopusInstanceConfig `yaml:"instances" json:"instances"`
LBPolicy string `yaml:"lb_policy" json:"lb_policy"`
HealthCheck *OctopusHealthCheckConfig `yaml:"health_check" json:"health_check"`
CircuitBreaker *OctopusCBConfig `yaml:"circuit_breaker" json:"circuit_breaker"`
}
OctopusUpstreamConfig mirrors octopus upstream definitions.
type OpenAPIAggregator ¶
type OpenAPIAggregator = disc.OpenAPIAggregator
OpenAPIAggregator is a backward-compatible alias for discovery.OpenAPIAggregator.
func NewOpenAPIAggregator ¶
func NewOpenAPIAggregator(config OpenAPIConfig, logger forge.Logger, rm RouteRegistry, sd *ServiceDiscovery) *OpenAPIAggregator
NewOpenAPIAggregator creates a new OpenAPI aggregator.
type OpenAPIConfig ¶
type OpenAPIConfig = disc.OpenAPIConfig
OpenAPIConfig holds configuration for the OpenAPI aggregation feature.
Canonical definition: discovery.OpenAPIConfig
func DefaultOpenAPIConfig ¶
func DefaultOpenAPIConfig() OpenAPIConfig
DefaultOpenAPIConfig returns defaults for OpenAPI aggregation.
type OpenAPIService ¶
type OpenAPIService interface {
Start(ctx context.Context)
Refresh(ctx context.Context)
MergedSpec() []byte
MergedSpecMap() map[string]any
ServiceSpec(serviceName string) *ServiceOpenAPISpec
ServiceSpecs() map[string]*ServiceOpenAPISpec
LastRefresh() time.Time
HandleMergedSpec(ctx forge.Context) error
HandleSwaggerUI(ctx forge.Context) error
HandleServiceList(ctx forge.Context) error
HandleServiceSpec(ctx forge.Context) error
HandleRefresh(ctx forge.Context) error
}
OpenAPIService handles OpenAPI spec aggregation and serving.
type PathRewriter ¶
type PathRewriter struct{}
PathRewriter rewrites request paths according to route configuration.
type RateLimitConfig ¶
type RateLimitConfig = middleware.RateLimitConfig
RateLimitConfig holds rate limiting settings.
Canonical definition: middleware.RateLimitConfig
type RateLimitStore ¶
type RateLimitStore = middleware.RateLimitStore
RateLimitStore is the interface for distributed rate limiting backends. Implementations must be safe for concurrent use.
Canonical definition: middleware.RateLimitStore
type RateLimiter ¶
type RateLimiter = middleware.RateLimiter
RateLimiter implements token-bucket rate limiting.
Canonical definition: middleware.RateLimiter
func NewRateLimiter ¶
func NewRateLimiter(config RateLimitConfig) *RateLimiter
NewRateLimiter creates a new rate limiter.
type RequestHook ¶
RequestHook is called before a request is proxied. Return a non-nil error to reject the request.
type RequestLimiter ¶
type RequestLimiter interface {
Allow(r *http.Request) bool
AllowWithConfig(r *http.Request, config *RateLimitConfig) bool
Cleanup(maxAge time.Duration)
}
RequestLimiter handles request rate limiting.
type ResponseCache ¶
type ResponseCache struct {
// contains filtered or unexported fields
}
ResponseCache provides HTTP response caching for the gateway. This is a thin wrapper around middleware.ResponseCache that adapts the root-level Route type to the middleware-local Route type.
func NewResponseCache ¶
func NewResponseCache(config CachingConfig, logger forge.Logger, store CacheStore) *ResponseCache
NewResponseCache creates a new response cache.
func (*ResponseCache) Get ¶
func (rc *ResponseCache) Get(r *http.Request, route *Route) *CachedResponse
Get attempts to retrieve a cached response for the given request.
func (*ResponseCache) Invalidate ¶
func (rc *ResponseCache) Invalidate(ctx context.Context, method, path string) error
Invalidate removes a cached entry for the given request.
func (*ResponseCache) Set ¶
func (rc *ResponseCache) Set(r *http.Request, route *Route, statusCode int, headers http.Header, body []byte)
Set stores a response in the cache.
func (*ResponseCache) Stats ¶
func (rc *ResponseCache) Stats() *CacheStats
Stats returns the cache statistics.
func (*ResponseCache) WriteCachedResponse ¶
func (rc *ResponseCache) WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)
WriteCachedResponse writes a cached response to the client.
type ResponseCacher ¶
type ResponseCacher interface {
Get(r *http.Request, route *Route) *CachedResponse
Set(r *http.Request, route *Route, statusCode int, headers http.Header, body []byte)
WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)
Invalidate(ctx context.Context, method, path string) error
Stats() CacheStatsReader
}
ResponseCacher handles HTTP response caching.
type ResponseHook ¶
ResponseHook is called after a response is received from upstream.
type RetryConfig ¶
type RetryConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
MaxAttempts int `json:"maxAttempts" yaml:"max_attempts"`
Backoff BackoffStrategy `json:"backoff" yaml:"backoff"`
InitialDelay time.Duration `json:"initialDelay" yaml:"initial_delay"`
MaxDelay time.Duration `json:"maxDelay" yaml:"max_delay"`
Multiplier float64 `json:"multiplier" yaml:"multiplier"`
Jitter bool `json:"jitter" yaml:"jitter"`
RetryableStatus []int `json:"retryableStatus" yaml:"retryable_status"`
RetryableMethods []string `json:"retryableMethods" yaml:"retryable_methods"`
BudgetPercent float64 `json:"budgetPercent" yaml:"budget_percent"`
}
RetryConfig holds retry settings.
type RetryPolicy ¶
type RetryPolicy interface {
ShouldRetry(method string, statusCode int, attempt int, routeConfig *RetryConfig) bool
Delay(attempt int, routeConfig *RetryConfig) time.Duration
}
RetryPolicy determines retry behavior for failed requests.
type Route ¶
type Route struct {
ID string `json:"id"`
Path string `json:"path"`
Methods []string `json:"methods,omitempty"`
Targets []*Target `json:"targets"`
StripPrefix bool `json:"stripPrefix"`
AddPrefix string `json:"addPrefix,omitempty"`
RewritePath string `json:"rewritePath,omitempty"`
Headers HeaderPolicy `json:"headers"`
Protocol RouteProtocol `json:"protocol"`
Source RouteSource `json:"source"`
ServiceName string `json:"serviceName,omitempty"`
Priority int `json:"priority"`
Version int64 `json:"version"`
Enabled bool `json:"enabled"`
// Per-route overrides (nil = use global defaults)
Retry *RetryConfig `json:"retry,omitempty"`
Timeout *TimeoutConfig `json:"timeout,omitempty"`
RateLimit *RateLimitConfig `json:"rateLimit,omitempty"`
Auth *RouteAuthConfig `json:"auth,omitempty"`
CircuitBreaker *CBConfig `json:"circuitBreaker,omitempty"`
Cache *RouteCacheConfig `json:"cache,omitempty"`
TrafficPolicy *TrafficPolicy `json:"trafficPolicy,omitempty"`
Transform *TransformConfig `json:"transform,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Route represents a configured gateway route with full policy support.
func (*Route) GetAuth ¶
func (r *Route) GetAuth() *RouteAuthConfig
GetAuth returns the per-route auth config (implements security.Route).
type RouteAuthConfig ¶
type RouteAuthConfig = security.RouteAuthConfig
RouteAuthConfig defines per-route auth requirements.
Canonical definition: security.RouteAuthConfig
type RouteCacheConfig ¶
type RouteCacheConfig = middleware.RouteCacheConfig
RouteCacheConfig defines per-route caching policy.
Canonical definition: middleware.RouteCacheConfig
type RouteChangeHook ¶
type RouteChangeHook func(event RouteEvent)
RouteChangeHook is called when the route table changes.
type RouteConfig ¶
type RouteConfig struct {
Path string `json:"path" yaml:"path"`
Methods []string `json:"methods,omitempty" yaml:"methods"`
Targets []TargetConfig `json:"targets" yaml:"targets"`
StripPrefix bool `json:"stripPrefix" yaml:"strip_prefix"`
AddPrefix string `json:"addPrefix,omitempty" yaml:"add_prefix"`
RewritePath string `json:"rewritePath,omitempty" yaml:"rewrite_path"`
Headers HeaderPolicy `json:"headers" yaml:"headers"`
Protocol RouteProtocol `json:"protocol" yaml:"protocol"`
Priority int `json:"priority" yaml:"priority"`
Enabled bool `json:"enabled" yaml:"enabled"`
Retry *RetryConfig `json:"retry,omitempty" yaml:"retry"`
Timeout *TimeoutConfig `json:"timeout,omitempty" yaml:"timeout"`
RateLimit *RateLimitConfig `json:"rateLimit,omitempty" yaml:"rate_limit"`
Auth *RouteAuthConfig `json:"auth,omitempty" yaml:"auth"`
Cache *RouteCacheConfig `json:"cache,omitempty" yaml:"cache"`
TrafficPolicy *TrafficPolicy `json:"trafficPolicy,omitempty" yaml:"traffic_policy"`
Metadata map[string]any `json:"metadata,omitempty" yaml:"metadata"`
// ServiceName associates this route with a logical service name.
// When set, the route can contribute to the aggregated OpenAPI spec.
ServiceName string `json:"serviceName,omitempty" yaml:"service_name"`
// OpenAPISpec is the URL to the OpenAPI spec for this route's upstream service.
// When set (along with ServiceName), the aggregator will fetch and include
// this spec in the merged gateway documentation.
OpenAPISpec string `json:"openapiSpec,omitempty" yaml:"openapi_spec"`
}
RouteConfig defines a static route in configuration.
type RouteDTO ¶
type RouteDTO struct {
Path string `json:"path"`
Methods []string `json:"methods,omitempty"`
Targets []TargetDTO `json:"targets"`
StripPrefix bool `json:"stripPrefix"`
AddPrefix string `json:"addPrefix,omitempty"`
RewritePath string `json:"rewritePath,omitempty"`
Headers HeaderPolicy `json:"headers"`
Protocol RouteProtocol `json:"protocol"`
Priority int `json:"priority"`
Enabled bool `json:"enabled"`
Retry *RetryConfig `json:"retry,omitempty"`
Timeout *TimeoutConfig `json:"timeout,omitempty"`
RateLimit *RateLimitConfig `json:"rateLimit,omitempty"`
Auth *RouteAuthConfig `json:"auth,omitempty"`
CircuitBreaker *CBConfig `json:"circuitBreaker,omitempty"`
Cache *RouteCacheConfig `json:"cache,omitempty"`
TrafficPolicy *TrafficPolicy `json:"trafficPolicy,omitempty"`
Transform *TransformConfig `json:"transform,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
RouteDTO is the API request body for creating/updating a route.
type RouteEvent ¶
type RouteEvent struct {
Type RouteEventType `json:"type"`
Route *Route `json:"route"`
Timestamp time.Time `json:"timestamp"`
}
RouteEvent represents a change in the route table.
type RouteEventType ¶
type RouteEventType string
RouteEventType represents types of route events.
const ( // RouteEventAdded indicates a new route was added. RouteEventAdded RouteEventType = "added" // RouteEventUpdated indicates a route was updated. RouteEventUpdated RouteEventType = "updated" // RouteEventRemoved indicates a route was removed. RouteEventRemoved RouteEventType = "removed" )
type RouteProtocol ¶
type RouteProtocol string
RouteProtocol defines the protocol type for a gateway route.
const ( // ProtocolHTTP is standard HTTP/HTTPS proxying. ProtocolHTTP RouteProtocol = "http" // ProtocolWebSocket is WebSocket proxying. ProtocolWebSocket RouteProtocol = "websocket" // ProtocolSSE is Server-Sent Events proxying. ProtocolSSE RouteProtocol = "sse" // ProtocolGRPC is gRPC proxying. ProtocolGRPC RouteProtocol = "grpc" // ProtocolGraphQL is GraphQL proxying (HTTP-based with special handling). ProtocolGraphQL RouteProtocol = "graphql" )
type RouteRegistry ¶
type RouteRegistry interface {
AddRoute(route *Route) error
RemoveRoute(id string) error
UpdateRoute(route *Route) error
GetRoute(id string) (*Route, bool)
ListRoutes() []*Route
MatchRoute(path, method string) *Route
RouteCount() int
RemoveBySource(source RouteSource)
RemoveByServiceName(serviceName string)
OnRouteChange(fn func(RouteEvent))
}
RouteRegistry manages gateway route configuration and matching.
type RouteSource ¶
type RouteSource string
RouteSource indicates how a route was created.
const ( // SourceManual indicates a manually configured route. SourceManual RouteSource = "manual" // SourceFARP indicates a route auto-generated from FARP schemas. SourceFARP RouteSource = "farp" // SourceDiscovery indicates a route from service discovery. SourceDiscovery RouteSource = "discovery" )
type RouteStats ¶
type RouteStats struct {
RouteID string `json:"routeId"`
Path string `json:"path"`
TotalRequests int64 `json:"totalRequests"`
TotalErrors int64 `json:"totalErrors"`
// AvgLatencyMs is the mean over every answered upstream request since start.
AvgLatencyMs float64 `json:"avgLatencyMs"`
// P99LatencyMs is the nearest-rank p99 over the most recent LatencySamples responses.
P99LatencyMs float64 `json:"p99LatencyMs"`
// LatencySamples is how many recent responses P99LatencyMs covers.
LatencySamples int `json:"latencySamples"`
CacheHits int64 `json:"cacheHits"`
CacheMisses int64 `json:"cacheMisses"`
RateLimited int64 `json:"rateLimited"`
}
RouteStats holds per-route traffic statistics.
type RouteStore ¶
type RouteStore interface {
// ListRoutes returns all persisted routes.
ListRoutes(ctx context.Context) ([]*Route, error)
// GetRoute returns a single route by ID.
GetRoute(ctx context.Context, routeID string) (*Route, error)
// SaveRoute creates or updates a route.
SaveRoute(ctx context.Context, route *Route) error
// DeleteRoute removes a route by ID.
DeleteRoute(ctx context.Context, routeID string) error
}
RouteStore persists gateway route configuration.
type ServiceDiscoverer ¶
type ServiceDiscoverer interface {
Start(ctx context.Context) error
Stop()
Refresh(ctx context.Context) error
DiscoveredServices() []*DiscoveredService
}
ServiceDiscoverer manages automatic service discovery integration.
type ServiceDiscovery ¶
ServiceDiscovery is a backward-compatible alias for discovery.Manager.
func NewServiceDiscovery ¶
func NewServiceDiscovery( config DiscoveryConfig, logger forge.Logger, rm RouteRegistry, discService DiscoveryService, ) *ServiceDiscovery
NewServiceDiscovery creates a new service discovery integration. The RouteRegistry is adapted to satisfy discovery.RouteRegistry.
type ServiceFilter ¶
type ServiceFilter = disc.ServiceFilter
ServiceFilter defines a filter for discovered services.
Canonical definition: discovery.ServiceFilter
type ServiceInstanceInfo ¶
type ServiceInstanceInfo = disc.ServiceInstanceInfo
ServiceInstanceInfo represents a discovered service instance.
Canonical definition: discovery.ServiceInstanceInfo
type ServiceOpenAPISpec ¶
type ServiceOpenAPISpec = disc.ServiceOpenAPISpec
ServiceOpenAPISpec holds a cached OpenAPI spec for a single upstream service.
Canonical definition: discovery.ServiceOpenAPISpec
type StatsRecorder ¶
type StatsRecorder interface {
Snapshot(routes []*Route) *GatewayStats
RecordRequest(routeID, path string)
RecordError(routeID string)
RecordLatency(routeID string, d time.Duration)
RecordRateLimited()
RecordCircuitBreak()
RecordRetryAttempt()
RecordCacheHit()
RecordCacheMiss()
}
StatsRecorder collects and reports gateway traffic statistics.
type TLSManager ¶
type TLSManager = security.TLSManager
TLSManager is a backward-compatible alias for security.TLSManager.
func NewTLSManager ¶
func NewTLSManager(config TLSConfig, logger forge.Logger) *TLSManager
NewTLSManager creates a new TLS manager. Deprecated: Use security.NewTLSManager directly.
type TLSProvider ¶
type TLSProvider interface {
GlobalTLSConfig() *tls.Config
TargetTLSConfig(target *Target) *tls.Config
TransportForTarget(baseTransport *http.Transport, target *Target) *http.Transport
Start()
Stop()
Reload() error
LastReload() time.Time
}
TLSProvider manages TLS certificates and transport configuration.
type Target ¶
type Target struct {
ID string `json:"id"`
URL string `json:"url"`
Weight int `json:"weight"`
Healthy bool `json:"healthy"`
ActiveConns int64 `json:"activeConns"`
CircuitState CircuitState `json:"circuitState"`
TLS *TargetTLSConfig `json:"tls,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
Tags []string `json:"tags,omitempty"`
// Stats
TotalRequests int64 `json:"totalRequests"`
TotalErrors int64 `json:"totalErrors"`
AvgLatencyMs float64 `json:"avgLatencyMs"`
P99LatencyMs float64 `json:"p99LatencyMs"`
// contains filtered or unexported fields
}
Target represents an upstream service endpoint.
func (*Target) GetTLS ¶
func (t *Target) GetTLS() *TargetTLSConfig
GetTLS returns the per-target TLS config (implements security.Target).
func (*Target) HealthPath ¶
HealthPath returns a custom health check path for this target, if one is set in its metadata (key "health_check_path"). Returns empty string to use the monitor's default path. Implements health.HealthPathProvider.
func (*Target) IsDraining ¶
IsDraining returns true if the target is draining.
func (*Target) IsHealthy ¶
IsHealthy returns whether the target is healthy (implements health.Target).
func (*Target) RecordRequest ¶
RecordRequest records a request outcome.
func (*Target) SetDraining ¶
SetDraining sets the draining state.
func (*Target) SetHealthy ¶
SetHealthy sets the target health status (implements health.Target).
func (*Target) Snapshot ¶
func (t *Target) Snapshot()
Snapshot populates the exported stats fields from atomics. It writes to the shared target and races the proxy; new code uses Stats.
func (*Target) Stats ¶
func (t *Target) Stats() TargetStats
Stats reads the target's counters without writing to the target, unlike Snapshot, which fills the exported fields in place and races the proxy.
type TargetConfig ¶
type TargetConfig struct {
URL string `json:"url" yaml:"url"`
Weight int `json:"weight" yaml:"weight"`
Tags []string `json:"tags,omitempty" yaml:"tags"`
Metadata map[string]string `json:"metadata,omitempty" yaml:"metadata"`
TLS *TargetTLSConfig `json:"tls,omitempty" yaml:"tls"`
}
TargetConfig defines a target in configuration.
type TargetDTO ¶
type TargetDTO struct {
URL string `json:"url"`
Weight int `json:"weight"`
Tags []string `json:"tags,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
TLS *TargetTLSConfig `json:"tls,omitempty"`
}
TargetDTO is the API representation of a target.
type TargetStats ¶
type TargetStats struct {
ActiveConns int64 `json:"activeConns"`
TotalRequests int64 `json:"totalRequests"`
TotalErrors int64 `json:"totalErrors"`
AvgLatencyMs float64 `json:"avgLatencyMs"`
}
TargetStats is a point-in-time copy of a target's counters.
type TargetTLSConfig ¶
type TargetTLSConfig = security.TargetTLSConfig
TargetTLSConfig holds per-target TLS configuration.
Canonical definition: security.TargetTLSConfig
type TimeoutConfig ¶
type TimeoutConfig struct {
Connect time.Duration `json:"connect" yaml:"connect"`
Read time.Duration `json:"read" yaml:"read"`
Write time.Duration `json:"write" yaml:"write"`
Idle time.Duration `json:"idle" yaml:"idle"`
}
TimeoutConfig holds timeout settings.
type TracingConfig ¶
type TracingConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
PropagateFormat string `json:"propagateFormat,omitempty" yaml:"propagate_format"`
SampleRate float64 `json:"sampleRate" yaml:"sample_rate"`
}
TracingConfig holds tracing settings. The gateway doesn't read it: tracing, sampling and propagation are set on the Forge app, and bastion's spans follow that. It is kept so existing config and code keep working.
type TrafficMatch ¶
type TrafficMatch struct {
Type TrafficMatchType `json:"type"`
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
Negate bool `json:"negate,omitempty"`
}
TrafficMatch defines traffic matching criteria.
type TrafficMatchType ¶
type TrafficMatchType string
TrafficMatchType defines how traffic rules are matched.
const ( // MatchHeader matches on request header value. MatchHeader TrafficMatchType = "header" // MatchCookie matches on cookie value. MatchCookie TrafficMatchType = "cookie" // MatchWeight matches by random weight percentage. MatchWeight TrafficMatchType = "weight" // MatchIPRange matches by client IP range. MatchIPRange TrafficMatchType = "ipRange" )
type TrafficPolicy ¶
type TrafficPolicy struct {
Type TrafficSplitType `json:"type"`
Rules []TrafficRule `json:"rules"`
MirrorTarget string `json:"mirrorTarget,omitempty"`
}
TrafficPolicy defines traffic splitting rules for a route.
type TrafficRouter ¶
type TrafficRouter interface {
FilterTargets(r *http.Request, route *Route) []*Target
ShouldMirror(route *Route) string
}
TrafficRouter handles traffic splitting and mirroring.
type TrafficRule ¶
type TrafficRule struct {
Match TrafficMatch `json:"match"`
TargetTags []string `json:"targetTags"`
Weight int `json:"weight"`
}
TrafficRule defines a single traffic routing rule.
type TrafficSplitConfig ¶
type TrafficSplitConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
}
TrafficSplitConfig holds global traffic split settings.
type TrafficSplitType ¶
type TrafficSplitType string
TrafficSplitType defines the traffic splitting strategy.
const ( // TrafficCanary routes a percentage of traffic to canary targets. TrafficCanary TrafficSplitType = "canary" // TrafficBlueGreen switches between two target groups. TrafficBlueGreen TrafficSplitType = "blueGreen" // TrafficABTest routes based on header/cookie matching. TrafficABTest TrafficSplitType = "abTest" // TrafficMirror duplicates requests to a mirror target. TrafficMirror TrafficSplitType = "mirror" // TrafficWeighted uses explicit weight distribution. TrafficWeighted TrafficSplitType = "weighted" )
type TransformConfig ¶
type TransformConfig struct {
RequestHeaders HeaderPolicy `json:"requestHeaders"`
ResponseHeaders HeaderPolicy `json:"responseHeaders"`
}
TransformConfig defines request/response transformation.
type UpstreamHealthEvent ¶
type UpstreamHealthEvent struct {
TargetID string `json:"targetId"`
TargetURL string `json:"targetUrl"`
Healthy bool `json:"healthy"`
Previous bool `json:"previous"`
RouteID string `json:"routeId"`
Timestamp time.Time `json:"timestamp"`
}
UpstreamHealthEvent represents an upstream health change.
type UpstreamHealthHook ¶
type UpstreamHealthHook func(event UpstreamHealthEvent)
UpstreamHealthHook is called when upstream health changes.
type ValidationError ¶
ValidationError represents a configuration validation error.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors is a collection of validation errors.
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
type WAFPlugin ¶
type WAFPlugin struct {
BasePlugin
// contains filtered or unexported fields
}
WAFPlugin wraps security.WAFPlugin as a root-level GatewayPlugin.
func NewWAFPlugin ¶
NewWAFPlugin creates a WAF plugin that implements GatewayPlugin. Deprecated: Use security.NewWAFPlugin directly.
type WAFViolation ¶
type WAFViolation = security.WAFViolation
WAFViolation is a backward-compatible alias for security.WAFViolation.
type WSBroadcaster ¶
WSBroadcaster manages WebSocket connections for real-time updates.
type WebSocketConfig ¶
type WebSocketConfig struct {
ReadBufferSize int `json:"readBufferSize" yaml:"read_buffer_size"`
WriteBufferSize int `json:"writeBufferSize" yaml:"write_buffer_size"`
HandshakeTimeout time.Duration `json:"handshakeTimeout" yaml:"handshake_timeout"`
PingInterval time.Duration `json:"pingInterval" yaml:"ping_interval"`
PongTimeout time.Duration `json:"pongTimeout" yaml:"pong_timeout"`
}
WebSocketConfig holds WebSocket proxy settings.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package admin owns the gateway's operator writes and the read models that the REST API and the dashboard contract share.
|
Package admin owns the gateway's operator writes and the read models that the REST API and the dashboard contract share. |
|
Package api provides WebSocket hub and client types for real-time dashboard communication.
|
Package api provides WebSocket hub and client types for real-time dashboard communication. |
|
Package discovery provides FARP-based service discovery and OpenAPI specification aggregation for the Bastion API gateway.
|
Package discovery provides FARP-based service discovery and OpenAPI specification aggregation for the Bastion API gateway. |
|
contract
Package contract wires Bastion into the Forge dashboard's contract path.
|
Package contract wires Bastion into the Forge dashboard's contract path. |
|
Package gateway builds a Bastion gateway that proxies on its own.
|
Package gateway builds a Bastion gateway that proxies on its own. |
|
Package health provides upstream health monitoring with active probes, passive failure tracking, and health check history.
|
Package health provides upstream health monitoring with active probes, passive failure tracking, and health check history. |
|
internal
|
|
|
telemetry
Package telemetry holds bastion's tracing helpers: the tracer, root spans for background work, error recording that never copies an error's text, and the client span every outbound HTTP call gets.
|
Package telemetry holds bastion's tracing helpers: the tracer, root spans for background work, error recording that never copies an error's text, and the client span every outbound HTTP call gets. |
|
telemetry/telemetrytest
Package telemetrytest records bastion's spans and scrapes its metrics in tests.
|
Package telemetrytest records bastion's spans and scrapes its metrics in tests. |
|
Package middleware provides HTTP middleware including response caching, rate limiting, and compression for the gateway.
|
Package middleware provides HTTP middleware including response caching, rate limiting, and compression for the gateway. |
|
Package observability provides metrics, access logging, and audit logging for the gateway.
|
Package observability provides metrics, access logging, and audit logging for the gateway. |
|
Package plugin provides the gateway plugin system for extending the proxy pipeline with custom request/response processing logic.
|
Package plugin provides the gateway plugin system for extending the proxy pipeline with custom request/response processing logic. |
|
Package proxy provides the core reverse proxy engine with support for HTTP, gRPC, WebSocket, and SSE protocols.
|
Package proxy provides the core reverse proxy engine with support for HTTP, gRPC, WebSocket, and SSE protocols. |
|
Package resilience provides circuit breakers, retry logic, bulkheading, request coalescing, and graceful drain for the gateway proxy pipeline.
|
Package resilience provides circuit breakers, retry logic, bulkheading, request coalescing, and graceful drain for the gateway proxy pipeline. |
|
Package routing manages gateway route configuration, matching, load balancing, traffic splitting, and API versioning.
|
Package routing manages gateway route configuration, matching, load balancing, traffic splitting, and API versioning. |
|
Package security provides authentication, TLS management, admin auth, and web application firewall (WAF) for the gateway.
|
Package security provides authentication, TLS management, admin auth, and web application firewall (WAF) for the gateway. |
|
Package store defines the composite store interface for Bastion.
|
Package store defines the composite store interface for Bastion. |
|
memory
Package memory provides an in-memory implementation of the Bastion composite store.
|
Package memory provides an in-memory implementation of the Bastion composite store. |
|
mongo
Package mongo provides a MongoDB implementation of the Bastion composite store using grove ORM.
|
Package mongo provides a MongoDB implementation of the Bastion composite store using grove ORM. |
|
postgres
Package postgres provides a PostgreSQL implementation of the Bastion composite store using grove ORM with programmatic migrations.
|
Package postgres provides a PostgreSQL implementation of the Bastion composite store using grove ORM with programmatic migrations. |
|
sqlite
Package sqlite provides a SQLite implementation of the Bastion composite store using grove ORM with programmatic migrations.
|
Package sqlite provides a SQLite implementation of the Bastion composite store using grove ORM with programmatic migrations. |