Bastion

Go Packages

Package imports and API documentation reference.

All Bastion packages are importable from the module github.com/xraph/bastion. This page is a comprehensive index of every package, its key types, and its primary functions.

Package Index

PackageImport PathDescription
bastiongithub.com/xraph/bastionRoot: Gateway, Config, Route, Target, HookEngine, options
extensiongithub.com/xraph/bastion/extensionForge extension wrapper with DI, dashboard, and store wiring
proxygithub.com/xraph/bastion/proxyProxy engine, HTTP/WebSocket/SSE/gRPC protocol handlers
discoverygithub.com/xraph/bastion/discoveryFARP integration, service watcher, OpenAPI aggregator types
healthgithub.com/xraph/bastion/healthHealth monitor, active/passive probes, health history
resiliencegithub.com/xraph/bastion/resilienceCircuit breaker, retry executor, bulkhead, connection drain
securitygithub.com/xraph/bastion/securityAuthentication, JWT, CORS, IP filter, TLS, WAF
routinggithub.com/xraph/bastion/routingRoute manager, load balancer, traffic splitting, versioning
middlewaregithub.com/xraph/bastion/middlewareRate limiter, response caching, compression
observabilitygithub.com/xraph/bastion/observabilityPrometheus metrics, access logging, audit logging
apigithub.com/xraph/bastion/apiAdmin REST API handlers, WebSocket hub
plugingithub.com/xraph/bastion/pluginPlugin manager, GraphQL stitching
dashboardgithub.com/xraph/bastion/dashboardForgeUI dashboard contributor, page/widget renderers
storegithub.com/xraph/bastion/storeComposite store interface
store/memorygithub.com/xraph/bastion/store/memoryIn-memory store for development/testing
store/postgresgithub.com/xraph/bastion/store/postgresPostgreSQL backend via Grove ORM
store/sqlitegithub.com/xraph/bastion/store/sqliteSQLite backend via Grove ORM
store/mongogithub.com/xraph/bastion/store/mongoMongoDB backend via Grove ORM
configgithub.com/xraph/bastionConfiguration types and file watcher (in root package)

Root Package: github.com/xraph/bastion

Gateway

type Gateway struct { /* embeds forge.BaseExtension */ }

func New(opts ...ConfigOption) forge.Extension

// Forge lifecycle
func (e *Gateway) Register(app forge.App) error
func (e *Gateway) Start(ctx context.Context) error
func (e *Gateway) Stop(ctx context.Context) error
func (e *Gateway) Health(ctx context.Context) error
func (e *Gateway) Dependencies() []string

// Component accessors
func (e *Gateway) RouteManager() RouteRegistry
func (e *Gateway) HealthMonitor() *health.Monitor
func (e *Gateway) Stats() StatsRecorder
func (e *Gateway) Hooks() *HookEngine
func (e *Gateway) Auth() *GatewayAuth
func (e *Gateway) Cache() *ResponseCache
func (e *Gateway) TLS() *TLSManager
func (e *Gateway) RateLimiter() *RateLimiter
func (e *Gateway) OpenAPI() *OpenAPIAggregator
func (e *Gateway) Discovery() *ServiceDiscovery
func (e *Gateway) Config() Config
func (e *Gateway) Hub() WSBroadcaster
func (e *Gateway) App() forge.App
func (e *Gateway) AccessLog() *AccessLogger
func (e *Gateway) Snapshot() *GatewayStats

Config and Options

type Config struct {
    Enabled        bool
    BasePath       string
    Routes         []RouteConfig
    Timeouts       TimeoutConfig
    Retry          RetryConfig
    BufferPool     BufferPoolConfig
    CircuitBreaker CircuitBreakerConfig
    RateLimiting   RateLimitConfig
    HealthCheck    HealthCheckConfig
    LoadBalancing  LoadBalancingConfig
    TrafficSplit   TrafficSplitConfig
    Auth           AuthConfig
    TLS            TLSConfig
    IPFilter       IPFilterConfig
    CORS           CORSConfig
    Caching        CachingConfig
    Discovery      DiscoveryConfig
    Metrics        MetricsConfig
    Tracing        TracingConfig
    AccessLog      AccessLogConfig
    OpenAPI        OpenAPIConfig
    Dashboard      DashboardConfig
    WebSocket      WebSocketConfig
    SSE            SSEConfig
}

func DefaultConfig() Config

type ConfigOption func(*Config)

func WithEnabled(enabled bool) ConfigOption
func WithBasePath(path string) ConfigOption
func WithRoute(route RouteConfig) ConfigOption
func WithRoutes(routes []RouteConfig) ConfigOption
func WithServiceRoute(name, path, url, specURL string) ConfigOption
func WithTimeouts(timeouts TimeoutConfig) ConfigOption
func WithRetry(retry RetryConfig) ConfigOption
func WithCircuitBreaker(cb CircuitBreakerConfig) ConfigOption
func WithRateLimiting(rl RateLimitConfig) ConfigOption
func WithHealthCheck(hc HealthCheckConfig) ConfigOption
func WithLoadBalancing(lb LoadBalancingConfig) ConfigOption
func WithAuth(auth AuthConfig) ConfigOption
func WithTLS(tls TLSConfig) ConfigOption
func WithCaching(caching CachingConfig) ConfigOption
func WithDiscovery(disc DiscoveryConfig) ConfigOption
func WithDiscoveryEnabled(enabled bool) ConfigOption
func WithDiscoveryPollInterval(d time.Duration) ConfigOption
func WithDiscoveryWatchMode(enabled bool) ConfigOption
func WithDiscoveryAutoPrefix(enabled bool) ConfigOption
func WithDiscoveryPrefixTemplate(tmpl string) ConfigOption
func WithDiscoveryStripPrefix(strip bool) ConfigOption
func WithDiscoveryServiceFilters(filters ...ServiceFilter) ConfigOption
func WithDiscoveryPrefixOverrides(overrides map[string]string) ConfigOption
func WithMetrics(m MetricsConfig) ConfigOption
func WithTracing(t TracingConfig) ConfigOption
func WithAccessLog(al AccessLogConfig) ConfigOption
func WithOpenAPI(o OpenAPIConfig) ConfigOption
func WithOpenAPIEnabled(enabled bool) ConfigOption
func WithOpenAPIRootDocs(enabled bool) ConfigOption
func WithOpenAPIGatewayDocs(enabled bool) ConfigOption
func WithExtensionFilter(filter ExtensionPathFilter) ConfigOption
func WithDashboard(d DashboardConfig) ConfigOption
func WithDashboardEnabled(enabled bool) ConfigOption
func WithCORS(cors CORSConfig) ConfigOption
func WithIPFilter(ipf IPFilterConfig) ConfigOption
func WithWebSocket(ws WebSocketConfig) ConfigOption
func WithSSE(sse SSEConfig) ConfigOption
func WithConfig(config Config) ConfigOption

Route and Target Types

type Route struct {
    ID          string
    Path        string
    Methods     []string
    Targets     []*Target
    StripPrefix bool
    AddPrefix   string
    RewritePath string
    Headers     HeaderPolicy
    Protocol    RouteProtocol
    Source      RouteSource
    ServiceName string
    Priority    int
    Version     int64
    Enabled     bool
    // Per-route overrides (nil = use global)
    Retry          *RetryConfig
    Timeout        *TimeoutConfig
    RateLimit      *RateLimitConfig
    Auth           *RouteAuthConfig
    CircuitBreaker *CBConfig
    Cache          *RouteCacheConfig
    TrafficPolicy  *TrafficPolicy
    Transform      *TransformConfig
    Metadata       map[string]any
    CreatedAt      time.Time
    UpdatedAt      time.Time
}

type Target struct {
    ID           string
    URL          string
    Weight       int
    Healthy      bool
    ActiveConns  int64
    CircuitState CircuitState
    TLS          *TargetTLSConfig
    Metadata     map[string]string
    Tags         []string
    TotalRequests int64
    TotalErrors   int64
    AvgLatencyMs  float64
    P99LatencyMs  float64
}

Protocol and Strategy Constants

// Route protocols
type RouteProtocol string
const (
    ProtocolHTTP      RouteProtocol = "http"
    ProtocolWebSocket RouteProtocol = "websocket"
    ProtocolSSE       RouteProtocol = "sse"
    ProtocolGRPC      RouteProtocol = "grpc"
    ProtocolGraphQL   RouteProtocol = "graphql"
)

// Route sources
type RouteSource string
const (
    SourceManual    RouteSource = "manual"
    SourceFARP      RouteSource = "farp"
    SourceDiscovery RouteSource = "discovery"
)

// Load balancing strategies
type LoadBalanceStrategy string
const (
    LBRoundRobin         LoadBalanceStrategy = "roundRobin"
    LBWeightedRoundRobin LoadBalanceStrategy = "weightedRoundRobin"
    LBRandom             LoadBalanceStrategy = "random"
    LBLeastConnections   LoadBalanceStrategy = "leastConnections"
    LBConsistentHash     LoadBalanceStrategy = "consistentHash"
)

// Circuit breaker states
type CircuitState string
const (
    CircuitClosed   CircuitState = "closed"
    CircuitOpen     CircuitState = "open"
    CircuitHalfOpen CircuitState = "halfOpen"
)

// Backoff strategies
type BackoffStrategy string
const (
    BackoffExponential BackoffStrategy = "exponential"
    BackoffLinear      BackoffStrategy = "linear"
    BackoffFixed       BackoffStrategy = "fixed"
)

Hook Engine

type HookEngine struct { /* unexported */ }

func NewHookEngine() *HookEngine

func (he *HookEngine) OnRequest(fn RequestHook)
func (he *HookEngine) OnResponse(fn ResponseHook)
func (he *HookEngine) OnError(fn ErrorHook)
func (he *HookEngine) OnRouteChange(fn RouteChangeHook)
func (he *HookEngine) OnUpstreamHealth(fn UpstreamHealthHook)
func (he *HookEngine) OnCircuitBreak(fn CircuitBreakHook)

// Hook type signatures
type RequestHook        func(r *http.Request, route *Route) error
type ResponseHook       func(resp *http.Response, route *Route)
type ErrorHook          func(err error, route *Route, w http.ResponseWriter)
type RouteChangeHook    func(event RouteEvent)
type UpstreamHealthHook func(event UpstreamHealthEvent)
type CircuitBreakHook   func(targetID string, from, to CircuitState)

Event Types

type RouteEvent struct {
    Type      RouteEventType
    Route     *Route
    Timestamp time.Time
}

type RouteEventType string
const (
    RouteEventAdded   RouteEventType = "added"
    RouteEventUpdated RouteEventType = "updated"
    RouteEventRemoved RouteEventType = "removed"
)

type UpstreamHealthEvent struct {
    TargetID  string
    TargetURL string
    Healthy   bool
    Previous  bool
    RouteID   string
    Timestamp time.Time
}

type GatewayStats struct {
    TotalRequests    int64
    TotalErrors      int64
    ActiveConns      int64
    ActiveWSConns    int64
    ActiveSSEConns   int64
    AvgLatencyMs     float64
    P99LatencyMs     float64
    RequestsPerSec   float64
    CacheHits        int64
    CacheMisses      int64
    RateLimited      int64
    CircuitBreaks    int64
    RetryAttempts    int64
    TotalRoutes      int
    HealthyUpstreams int
    TotalUpstreams   int
    RouteStats       map[string]*RouteStats
    Uptime           int64
    StartedAt        time.Time
}

Plugin Interface

type GatewayPlugin interface {
    Name() string
    OnRequest(r *http.Request, route *Route) error
    OnResponse(resp *http.Response, route *Route)
    OnError(err error, route *Route, w http.ResponseWriter)
}

type BasePlugin struct {
    PluginName string
}

extension

The extension package wraps the gateway as a Forge extension with dashboard integration, discovery auto-wiring, and Grove-based persistent store support.

type Extension struct { /* unexported */ }

func New(opts ...bastion.ConfigOption) *Extension
func (e *Extension) Configure(opts ...func(*Extension)) *Extension

// Forge lifecycle
func (e *Extension) Register(app forge.App) error
func (e *Extension) Start(ctx context.Context) error
func (e *Extension) Stop(ctx context.Context) error
func (e *Extension) Health(ctx context.Context) error

// Extension options
func WithGroveDatabase(name string) func(*Extension)
func WithStore(s store.Store) func(*Extension)
func WithDisableMigrate() func(*Extension)

proxy

The proxy engine handles HTTP reverse proxying with protocol detection and multi-protocol support.

// Core proxy engine
type Engine struct { /* unexported */ }

// Protocol handlers for WebSocket, SSE, gRPC proxying
// Custom transport with connection pooling and TLS support

discovery

FARP integration for automatic service discovery and route generation.

type DiscoveryConfig struct {
    Enabled          bool
    PollInterval     time.Duration
    WatchMode        bool
    ServiceFilters   []ServiceFilter
    AutoPrefix       bool
    PrefixTemplate   string
    StripPrefix      bool
    PrefixOverrides  map[string]string
}

type ServiceFilter struct {
    IncludeTags []string
    ExcludeTags []string
    NamePattern string
}

type DiscoveredService struct {
    Name         string
    Version      string
    Address      string
    Port         int
    Protocols    []string
    SchemaTypes  []string
    Capabilities []string
    Healthy      bool
    Metadata     map[string]string
    RouteCount   int
    DiscoveredAt time.Time
}

type OpenAPIConfig struct {
    Enabled            bool
    Path               string
    UIPath             string
    Title              string
    Description        string
    Version            string
    RefreshInterval    time.Duration
    FetchTimeout       time.Duration
    MergeStrategy      string
    EnableRootDocs     bool
    EnableGatewayDocs  bool
    ExcludeServices    []string
    ExtensionFilters   []ExtensionPathFilter
    RootUIPath         string
}

type ServiceInstanceInfo struct {
    ID       string
    Name     string
    Version  string
    Address  string
    Port     int
    Tags     []string
    Metadata map[string]string
    Healthy  bool
}

health

Active and passive health monitoring for upstream targets.

type Config struct {
    Enabled              bool
    Interval             time.Duration
    Timeout              time.Duration
    Path                 string
    FailureThreshold     int
    SuccessThreshold     int
    EnablePassive        bool
    PassiveFailThreshold int
}

type Monitor struct { /* unexported */ }

func NewMonitor(cfg Config, logger forge.Logger) *Monitor
func (m *Monitor) Start(ctx context.Context)
func (m *Monitor) Stop()
func (m *Monitor) Health(ctx context.Context) error
func (m *Monitor) Register(routeID string, target health.Target)
func (m *Monitor) Deregister(targetID string)
func (m *Monitor) SetOnHealthChange(fn func(Event))

type Event struct {
    TargetID  string
    TargetURL string
    Healthy   bool
    Timestamp time.Time
}

resilience

Circuit breaker, retry, and bulkhead patterns for upstream fault tolerance.

// Circuit breaker
type CircuitBreaker struct { /* unexported */ }
type CircuitBreakerConfig struct {
    Enabled          bool
    FailureThreshold int
    FailureWindow    time.Duration
    ResetTimeout     time.Duration
    HalfOpenMax      int
}

// Retry executor
type RetryConfig struct {
    Enabled          bool
    MaxAttempts      int
    Backoff          BackoffStrategy
    InitialDelay     time.Duration
    MaxDelay         time.Duration
    Multiplier       float64
    Jitter           bool
    RetryableStatus  []int
    RetryableMethods []string
    BudgetPercent    float64
}

// Bulkhead (concurrency limiter)
type Bulkhead struct { /* unexported */ }

// Connection drain for graceful shutdown
type Drain struct { /* unexported */ }

security

Authentication, authorization, and network security.

type AuthConfig struct {
    Enabled        bool
    ForwardHeaders bool
    // JWT, API key, and custom provider configs
}

type AuthProvider interface {
    Name() string
    Authenticate(r *http.Request) (*AuthContext, error)
}

type AuthContext struct {
    Subject  string
    Claims   map[string]any
    Provider string
}

routing

Route management, load balancing, and traffic splitting.

type RouteRegistry interface {
    AddRoute(route *Route) error
    UpdateRoute(route *Route) error
    RemoveRoute(id string) error
    GetRoute(id string) (*Route, bool)
    ListRoutes() []*Route
    RouteCount() int
    MatchRoute(method, path string) (*Route, bool)
    OnRouteChange(fn func(RouteEvent))
}

type LoadBalancer interface {
    Select(targets []*Target, key string) *Target
}

api

Admin REST API handlers and WebSocket hub for real-time updates.

type Handlers struct { /* unexported */ }

func NewHandlers(gw Gateway, hub *Hub) *Handlers

// Route management
func (h *Handlers) HandleListRoutes(ctx forge.Context) error
func (h *Handlers) HandleGetRoute(ctx forge.Context) error
func (h *Handlers) HandleCreateRoute(ctx forge.Context) error
func (h *Handlers) HandleUpdateRoute(ctx forge.Context) error
func (h *Handlers) HandleDeleteRoute(ctx forge.Context) error
func (h *Handlers) HandleEnableRoute(ctx forge.Context) error
func (h *Handlers) HandleDisableRoute(ctx forge.Context) error

// Monitoring
func (h *Handlers) HandleListUpstreams(ctx forge.Context) error
func (h *Handlers) HandleGetStats(ctx forge.Context) error
func (h *Handlers) HandleGetRouteStats(ctx forge.Context) error
func (h *Handlers) HandleGetConfig(ctx forge.Context) error

// Discovery
func (h *Handlers) HandleListDiscoveredServices(ctx forge.Context) error
func (h *Handlers) HandleRefreshDiscovery(ctx forge.Context) error
func (h *Handlers) HandleRegisterService(ctx forge.Context) error
func (h *Handlers) HandleDeregisterService(ctx forge.Context) error

// WebSocket
func (h *Handlers) HandleWebSocket(ctx forge.Context) error

type Hub struct { /* unexported */ }
func NewHub() *Hub

store

Composite store interface for persistent gateway state.

type Store interface {
    RouteStore
    CircuitBreakerStore
    HealthStore
    CacheStore
    RateLimitStore
    AuditSink
    Migrate(ctx context.Context) error
    Ping(ctx context.Context) error
    Close() error
}

Store Implementations

BackendConstructorDriver
Memorymemory.New() *StoreNone
PostgreSQLpostgres.New(db *grove.DB) *Storegrove/drivers/pgdriver
SQLitesqlite.New(db *grove.DB) *Storegrove/drivers/sqlitedriver
MongoDBmongo.New(db *grove.DB) *Storegrove/drivers/mongodriver

On this page