gateway

package module
v0.9.7 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2026 License: Apache-2.0 Imports: 33 Imported by: 0

README

Forge Gateway Extension

Production-grade API gateway extension for Forge that turns any Forge application into a feature-complete reverse proxy with automatic service discovery, multi-protocol support, and an admin dashboard.

Features

  • Multi-protocol proxying: HTTP, WebSocket, SSE (Server-Sent Events), gRPC (unary + streaming)
  • Automatic service discovery: FARP-based schema-driven route generation from OpenAPI, AsyncAPI, GraphQL descriptors
  • Manual route configuration: Static routes via config file or admin API
  • Load balancing: Round-robin, weighted round-robin, random, least-connections, consistent hash
  • Circuit breakers: Per-target three-state (closed/open/half-open) circuit breakers
  • Health monitoring: Active HTTP probes + passive failure tracking with configurable thresholds
  • Rate limiting: Token-bucket algorithm (global, per-route, per-client)
  • Retry with backoff: Exponential, linear, fixed backoff with jitter and retry budgets
  • Traffic splitting: Canary, blue-green, A/B testing, shadow/mirror traffic
  • Authentication: API key, Bearer token, forward auth -- integrates with Forge auth extension
  • Response caching: In-memory or external cache store, per-route policies, Cache-Control respect
  • TLS/mTLS: Upstream TLS with CA certs, client certs for mTLS, auto cert reloading
  • Request/response transformation: Path rewriting, header manipulation, prefix stripping
  • CORS and IP filtering: Gateway-level security policies
  • Observability: Prometheus metrics, structured access logging, OpenTelemetry trace propagation
  • Admin dashboard: Real-time ForgeUI-based dashboard with routes, upstreams, stats, and service discovery views
  • Admin REST API: Full CRUD for routes, upstreams, stats, and configuration
  • Hot-reload: Configuration changes applied without restart
  • OpenAPI aggregation: Unified OpenAPI spec from all upstream services via FARP, Swagger UI, per-service specs
  • Hook system: Extensible OnRequest/OnResponse/OnError/OnRouteChange/OnUpstreamHealth hooks

Quick Start

package main

import (
    "github.com/xraph/forge"
    "github.com/xraph/forge/extensions/gateway"
)

func main() {
    app := forge.NewApp(forge.AppConfig{
        Name:    "api-gateway",
        Version: "1.0.0",
        Extensions: []forge.Extension{
            gateway.NewExtension(
                gateway.WithRoute(gateway.RouteConfig{
                    Path:    "/users/*",
                    Targets: []gateway.TargetConfig{
                        {URL: "http://user-service:8080", Weight: 1},
                    },
                    StripPrefix: true,
                    Protocol:    gateway.ProtocolHTTP,
                    Enabled:     true,
                }),
                gateway.WithRoute(gateway.RouteConfig{
                    Path:    "/orders/*",
                    Targets: []gateway.TargetConfig{
                        {URL: "http://order-service:8080", Weight: 1},
                    },
                    StripPrefix: true,
                    Protocol:    gateway.ProtocolHTTP,
                    Enabled:     true,
                }),
            ),
        },
    })

    app.Run()
}

With FARP Auto-Discovery

app := forge.NewApp(forge.AppConfig{
    Name: "api-gateway",
    Extensions: []forge.Extension{
        // Discovery extension enables FARP
        discovery.NewExtension(
            discovery.WithEnabled(true),
            discovery.WithBackend("consul"),
        ),
        // Gateway auto-discovers services
        gateway.NewExtension(
            gateway.WithDiscoveryEnabled(true),
            gateway.WithDashboardEnabled(true),
        ),
    },
})

Configuration

Programmatic Configuration
gateway.NewExtension(
    gateway.WithBasePath("/api"),
    gateway.WithLoadBalancing(gateway.LoadBalancingConfig{
        Strategy: gateway.LBWeightedRoundRobin,
    }),
    gateway.WithCircuitBreaker(gateway.CircuitBreakerConfig{
        Enabled:          true,
        FailureThreshold: 5,
        ResetTimeout:     30 * time.Second,
    }),
    gateway.WithRateLimiting(gateway.RateLimitConfig{
        Enabled:        true,
        RequestsPerSec: 1000,
        Burst:          100,
        PerClient:      true,
    }),
    gateway.WithHealthCheck(gateway.HealthCheckConfig{
        Enabled:  true,
        Interval: 10 * time.Second,
        Path:     "/health",
    }),
)
File-based Configuration (YAML/JSON)

The gateway loads config from Forge's ConfigManager under the gateway key:

gateway:
  enabled: true
  basePath: "/api"
  routes:
    - path: "/users/*"
      targets:
        - url: "http://user-service:8080"
          weight: 1
      stripPrefix: true
      protocol: http
      enabled: true
  circuitBreaker:
    enabled: true
    failureThreshold: 5
    resetTimeout: 30s
  rateLimiting:
    enabled: true
    requestsPerSec: 1000
    burst: 100
  healthCheck:
    enabled: true
    interval: 10s
    path: "/health"
  discovery:
    enabled: true
    watchMode: true
    autoPrefix: true
    prefixTemplate: "/{{.ServiceName}}"
  dashboard:
    enabled: true
    basePath: "/gateway"
    realtime: true

Admin API

Method Path Description
GET /gateway/api/routes List all routes
GET /gateway/api/routes/:id Get route details
POST /gateway/api/routes Create manual route
PUT /gateway/api/routes/:id Update route
DELETE /gateway/api/routes/:id Delete manual route
POST /gateway/api/routes/:id/enable Enable route
POST /gateway/api/routes/:id/disable Disable route
GET /gateway/api/upstreams List all targets
GET /gateway/api/stats Gateway statistics
GET /gateway/api/stats/routes Per-route statistics
GET /gateway/api/config Current configuration
GET /gateway/api/discovery/services Discovered services
POST /gateway/api/discovery/refresh Force FARP re-scan
GET /gateway/openapi.json Aggregated OpenAPI spec
GET /gateway/swagger Swagger UI
GET /gateway/api/openapi/services OpenAPI service listing
GET /gateway/api/openapi/services/:service Per-service OpenAPI spec
POST /gateway/api/openapi/refresh Force OpenAPI re-fetch
WS /gateway/ws Real-time event stream

Hook System

ext := gateway.NewExtension()

// Access hooks after extension start
app.AfterStart(func() {
    gw := forge.Must[*gateway.Extension](app.Container(), "gateway")

    gw.Hooks().OnRequest(func(r *http.Request, route *gateway.Route) error {
        // Add custom auth header
        r.Header.Set("X-Gateway-Auth", "validated")
        return nil
    })

    gw.Hooks().OnResponse(func(resp *http.Response, route *gateway.Route) {
        // Add custom response header
        resp.Header.Set("X-Served-By", "forge-gateway")
    })

    gw.Hooks().OnError(func(err error, route *gateway.Route, w http.ResponseWriter) {
        // Custom error page
        log.Printf("Gateway error on route %s: %v", route.Path, err)
    })
})

Architecture

Client Request
    │
    ├── IP Filter
    ├── CORS
    ├── Rate Limiter (global)
    ├── Route Matcher
    ├── Rate Limiter (per-route)
    ├── Authentication (API key/Bearer/forward auth)
    ├── Response Cache (check)
    ├── Request Hooks
    ├── Traffic Splitter
    ├── Load Balancer
    ├── Circuit Breaker Check
    ├── TLS/mTLS (per-target)
    ├── Protocol Proxy (HTTP/WS/SSE/gRPC)
    │   ├── Path Rewriting
    │   ├── Header Manipulation
    │   └── Upstream Connection
    ├── Response Cache (store)
    ├── Response Hooks
    ├── Access Logger
    └── Client Response

OpenAPI Aggregation

The gateway automatically discovers and aggregates OpenAPI specifications from all upstream services that publish their schemas via FARP. This provides a single, unified API documentation view for all services behind the gateway.

How It Works
  1. Discovery: Services register with FARP and expose their OpenAPI spec via metadata (farp.openapi or farp.openapi.path)
  2. Fetching: The gateway periodically fetches OpenAPI specs from all discovered services
  3. Merging: Specs are merged into a unified OpenAPI 3.1.0 document with service-level tags and namespaced schemas
  4. Serving: The aggregated spec is available at /gateway/openapi.json and browsable via Swagger UI at /gateway/swagger
Configuration
gateway.NewExtension(
    gateway.WithOpenAPI(gateway.OpenAPIConfig{
        Enabled:         true,
        Path:            "/openapi.json",
        UIPath:          "/swagger",
        Title:           "My API Gateway",
        Description:     "All services behind the gateway",
        Version:         "1.0.0",
        RefreshInterval: 30 * time.Second,
        FetchTimeout:    10 * time.Second,
        MergeStrategy:   "prefix",           // "prefix" or "flat"
        IncludeGatewayRoutes: true,           // Include gateway admin API
        ExcludeServices: []string{"internal"},// Services to skip
    }),
)
YAML Configuration
gateway:
  openapi:
    enabled: true
    path: "/openapi.json"
    uiPath: "/swagger"
    title: "My API Gateway"
    refreshInterval: 30s
    mergeStrategy: prefix
    includeGatewayRoutes: true
    excludeServices:
      - internal-admin
Per-Service Specs

Individual service specs are available at /gateway/api/openapi/services/:serviceName, allowing you to access each service's original spec independently.

ForgeUI Dashboard

The gateway includes a built-in admin dashboard that can run standalone or be mounted into the dashboard extension:

  • Overview: Real-time stats (requests, errors, latency, health)
  • Routes: Sortable table with path, protocol, source, targets, status
  • Upstreams: Health matrix, circuit breaker states, connection counts
  • Services: Discovered FARP services with schema types

The dashboard uses ForgeUI (gomponents + Alpine.js + Tailwind CSS) for a fully server-rendered, interactive UI with WebSocket real-time updates.

License

Same license as the Forge framework.

Documentation

Index

Constants

View Source
const (
	// ServiceKey is the DI key for the gateway service.
	ServiceKey = "gateway"
)

DI container keys for the gateway extension.

Variables

This section is empty.

Functions

func GatewayMiddleware

func GatewayMiddleware(config Config, next http.Handler) http.Handler

GatewayMiddleware wraps http.Handler with gateway-level middleware.

func NewExtension

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

NewExtension creates a new gateway extension.

func ProxyGRPC

func ProxyGRPC(w http.ResponseWriter, r *http.Request, route *Route, target *Target, config Config, logger forge.Logger)

ProxyGRPC proxies a gRPC request to the upstream target. It handles:

  • gRPC metadata (headers) propagation
  • gRPC deadline/timeout propagation
  • Unary, server-streaming, client-streaming, and bidirectional streaming RPCs
  • gRPC trailers
  • gRPC status codes

func ProxySSE

func ProxySSE(
	w http.ResponseWriter,
	r *http.Request,
	route *Route,
	target *Target,
	config Config,
	logger forge.Logger,
)

ProxySSE proxies a Server-Sent Events connection to an upstream target.

func ProxyWebSocket

func ProxyWebSocket(
	w http.ResponseWriter,
	r *http.Request,
	route *Route,
	target *Target,
	config WebSocketConfig,
	logger forge.Logger,
)

ProxyWebSocket proxies a WebSocket connection to an upstream target.

func RewritePath

func RewritePath(path string, route *Route) string

RewritePath applies path rewriting rules to a request.

func ValidateTLSConfig

func ValidateTLSConfig(config TLSConfig) error

ValidateTLSConfig checks that the TLS configuration is valid.

Types

type APIKeyAuthProvider

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

APIKeyAuthProvider validates requests using API keys in headers or query params.

func NewAPIKeyAuthProvider

func NewAPIKeyAuthProvider(name, header, queryParam string, keys []*APIKeyEntry) *APIKeyAuthProvider

NewAPIKeyAuthProvider creates an API key auth provider.

func (*APIKeyAuthProvider) Authenticate

func (*APIKeyAuthProvider) Name

func (p *APIKeyAuthProvider) Name() string

type APIKeyEntry

type APIKeyEntry struct {
	Key      string         `json:"key"`
	Subject  string         `json:"subject"`
	Scopes   []string       `json:"scopes,omitempty"`
	Metadata map[string]any `json:"metadata,omitempty"`
}

APIKeyEntry represents a registered API key with associated metadata.

type AccessLogConfig

type AccessLogConfig struct {
	Enabled        bool     `json:"enabled" yaml:"enabled"`
	RedactHeaders  []string `json:"redactHeaders,omitempty" yaml:"redact_headers"`
	IncludeBody    bool     `json:"includeBody" yaml:"include_body"`
	MaxBodyLogSize int      `json:"maxBodyLogSize" yaml:"max_body_log_size"`
}

AccessLogConfig holds access logging settings.

type AccessLogger

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

AccessLogger provides structured access logging for gateway requests.

func NewAccessLogger

func NewAccessLogger(config AccessLogConfig, logger forge.Logger) *AccessLogger

NewAccessLogger creates a new access logger.

func (*AccessLogger) Log

func (al *AccessLogger) Log(r *http.Request, statusCode int, latency time.Duration, route *Route, target *Target)

Log logs a gateway request.

func (*AccessLogger) LogAdminAction

func (al *AccessLogger) LogAdminAction(action, resource, result string, r *http.Request)

LogAdminAction logs an admin API action.

type AdminHandlers

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

AdminHandlers provides REST API handlers for the gateway admin.

func NewAdminHandlers

func NewAdminHandlers(ext *Extension) *AdminHandlers

NewAdminHandlers creates new admin handlers.

type AuthConfig

type AuthConfig struct {
	Enabled        bool     `json:"enabled" yaml:"enabled"`
	DefaultPolicy  string   `json:"defaultPolicy,omitempty" yaml:"default_policy"`
	Providers      []string `json:"providers,omitempty" yaml:"providers"`
	ForwardHeaders bool     `json:"forwardHeaders" yaml:"forward_headers"`
}

AuthConfig holds gateway-level auth settings.

type AuthError

type AuthError struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

AuthError represents an authentication/authorization error.

func (*AuthError) Error

func (e *AuthError) Error() string

type AuthProvider

type AuthProvider interface {
	// Name returns the provider name.
	Name() string

	// Authenticate validates a request and returns an auth context or error.
	Authenticate(ctx context.Context, r *http.Request) (*GatewayAuthContext, error)
}

AuthProvider is the gateway's interface for authentication providers. This mirrors the auth extension's AuthProvider interface, decoupled to avoid a hard dependency on extensions/auth.

type AuthRegistry

type AuthRegistry interface {
	// Get returns a provider by name.
	Get(name string) (AuthProvider, bool)

	// Has checks if a provider exists.
	Has(name string) bool

	// List returns all registered provider names.
	List() []string

	// Register adds a custom auth provider.
	Register(provider AuthProvider) error
}

AuthRegistry manages authentication providers for the gateway. It supports resolving auth from the Forge auth extension, as well as registering custom gateway-specific providers.

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 BearerTokenAuthProvider

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

BearerTokenAuthProvider validates Bearer tokens by forwarding them to a validation endpoint or using a configurable validation function.

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.

func (*BearerTokenAuthProvider) Authenticate

func (*BearerTokenAuthProvider) Name

func (p *BearerTokenAuthProvider) Name() string

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 struct {
	// contains filtered or unexported fields
}

CacheStats tracks cache hit/miss metrics.

func (*CacheStats) Hits

func (cs *CacheStats) Hits() int64

Hits returns the total cache hits.

func (*CacheStats) Misses

func (cs *CacheStats) Misses() int64

Misses returns the total cache misses.

type CacheStore

type CacheStore interface {
	Get(ctx context.Context, key string) ([]byte, error)
	Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
}

CacheStore is the gateway's interface for a cache backend. This decouples from the concrete cache extension, allowing the gateway to use any backend that implements this interface.

type CachedResponse

type CachedResponse struct {
	StatusCode int               `json:"statusCode"`
	Headers    map[string]string `json:"headers"`
	Body       []byte            `json:"body"`
	CachedAt   time.Time         `json:"cachedAt"`
	TTL        time.Duration     `json:"ttl"`
}

CachedResponse represents a cached HTTP response.

type CachingConfig

type CachingConfig struct {
	Enabled    bool          `json:"enabled" yaml:"enabled"`
	DefaultTTL time.Duration `json:"defaultTtl" yaml:"default_ttl"`
	MaxSize    int           `json:"maxSize" yaml:"max_size"`
	Methods    []string      `json:"methods,omitempty" yaml:"methods"`
	VaryBy     []string      `json:"varyBy,omitempty" yaml:"vary_by"`
}

CachingConfig holds response caching settings.

type CircuitBreakHook

type CircuitBreakHook func(targetID string, from, to CircuitState)

CircuitBreakHook is called when a circuit breaker state changes.

type CircuitBreaker

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

CircuitBreaker implements a per-target circuit breaker with three states.

func NewCircuitBreaker

func NewCircuitBreaker(targetID string, config CircuitBreakerConfig) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker for a target.

func (*CircuitBreaker) Allow

func (cb *CircuitBreaker) Allow() bool

Allow checks if a request is allowed through the circuit breaker.

func (*CircuitBreaker) RecordFailure

func (cb *CircuitBreaker) RecordFailure()

RecordFailure records a failed request.

func (*CircuitBreaker) RecordSuccess

func (cb *CircuitBreaker) RecordSuccess()

RecordSuccess records a successful request.

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

Reset resets the circuit breaker to closed state.

func (*CircuitBreaker) SetOnStateChange

func (cb *CircuitBreaker) SetOnStateChange(fn func(targetID string, from, to CircuitState))

SetOnStateChange sets the state change callback.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns the current circuit state.

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 CircuitBreakerManager

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

CircuitBreakerManager manages circuit breakers for all targets.

func NewCircuitBreakerManager

func NewCircuitBreakerManager(config CircuitBreakerConfig) *CircuitBreakerManager

NewCircuitBreakerManager creates a new circuit breaker manager.

func (*CircuitBreakerManager) Get

func (m *CircuitBreakerManager) Get(targetID string) *CircuitBreaker

Get returns the circuit breaker for a target, creating one if necessary.

func (*CircuitBreakerManager) GetWithConfig

func (m *CircuitBreakerManager) GetWithConfig(targetID string, cfg *CBConfig) *CircuitBreaker

GetWithConfig returns a circuit breaker with a per-route config override.

func (*CircuitBreakerManager) Remove

func (m *CircuitBreakerManager) Remove(targetID string)

Remove removes a circuit breaker for a target.

func (*CircuitBreakerManager) SetOnStateChange

func (m *CircuitBreakerManager) SetOnStateChange(fn func(targetID string, from, to CircuitState))

SetOnStateChange sets the global state change callback.

type CircuitState

type CircuitState string

CircuitState represents the circuit breaker state.

const (
	// CircuitClosed allows requests through (normal operation).
	CircuitClosed CircuitState = "closed"

	// CircuitOpen rejects requests (fail-fast).
	CircuitOpen CircuitState = "open"

	// CircuitHalfOpen allows limited probe requests.
	CircuitHalfOpen CircuitState = "half_open"
)

type Client

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

Client is a middleman between the websocket connection and the hub.

func NewClient

func NewClient(hub *Hub, conn *websocket.Conn) *Client

NewClient creates a new WebSocket client.

func (*Client) Start

func (c *Client) Start()

Start starts the client's read and write pumps.

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 configures OpenTelemetry tracing
	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"`

	// 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.

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 WithAuth

func WithAuth(auth AuthConfig) ConfigOption

WithAuth sets the auth configuration.

func WithBasePath

func WithBasePath(path string) ConfigOption

WithBasePath sets the base path prefix for all gateway routes.

func WithCORS

func WithCORS(cors CORSConfig) ConfigOption

WithCORS sets the CORS configuration.

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 WithConfig

func WithConfig(config Config) ConfigOption

WithConfig sets the complete config.

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 WithDiscoveryEnabled

func WithDiscoveryEnabled(enabled bool) ConfigOption

WithDiscoveryEnabled enables/disables FARP discovery.

func WithEnabled

func WithEnabled(enabled bool) ConfigOption

WithEnabled sets whether the gateway is enabled.

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 WithOpenAPI

func WithOpenAPI(o OpenAPIConfig) ConfigOption

WithOpenAPI sets the OpenAPI aggregation configuration.

func WithOpenAPIEnabled

func WithOpenAPIEnabled(enabled bool) ConfigOption

WithOpenAPIEnabled enables/disables OpenAPI aggregation.

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 WithSSE

func WithSSE(sse SSEConfig) ConfigOption

WithSSE sets the SSE proxy configuration.

func WithTLS

func WithTLS(tls TLSConfig) ConfigOption

WithTLS sets the TLS configuration.

func WithTimeouts

func WithTimeouts(timeouts TimeoutConfig) ConfigOption

WithTimeouts sets the timeout configuration.

func WithTracing

func WithTracing(t TracingConfig) ConfigOption

WithTracing sets the tracing configuration.

func WithWebSocket

func WithWebSocket(ws WebSocketConfig) ConfigOption

WithWebSocket sets the WebSocket proxy configuration.

type DashboardConfig

type DashboardConfig struct {
	Enabled  bool   `json:"enabled" yaml:"enabled"`
	BasePath string `json:"basePath" yaml:"base_path"`
	Title    string `json:"title,omitempty" yaml:"title"`
	Realtime bool   `json:"realtime" yaml:"realtime"`
}

DashboardConfig holds admin dashboard settings.

type DiscoveredService

type DiscoveredService struct {
	Name         string            `json:"name"`
	Version      string            `json:"version"`
	Address      string            `json:"address"`
	Port         int               `json:"port"`
	Protocols    []string          `json:"protocols"`
	SchemaTypes  []string          `json:"schemaTypes"`
	Capabilities []string          `json:"capabilities"`
	Healthy      bool              `json:"healthy"`
	Metadata     map[string]string `json:"metadata,omitempty"`
	RouteCount   int               `json:"routeCount"`
	DiscoveredAt time.Time         `json:"discoveredAt"`
}

DiscoveredService represents a service found via FARP/discovery.

type DiscoveryConfig

type DiscoveryConfig struct {
	Enabled        bool            `json:"enabled" yaml:"enabled"`
	PollInterval   time.Duration   `json:"pollInterval" yaml:"poll_interval"`
	WatchMode      bool            `json:"watchMode" yaml:"watch_mode"`
	ServiceFilters []ServiceFilter `json:"serviceFilters,omitempty" yaml:"service_filters"`
	AutoPrefix     bool            `json:"autoPrefix" yaml:"auto_prefix"`
	PrefixTemplate string          `json:"prefixTemplate,omitempty" yaml:"prefix_template"`
	StripPrefix    bool            `json:"stripPrefix" yaml:"strip_prefix"`
}

DiscoveryConfig holds FARP auto-discovery settings.

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 ErrorHook

type ErrorHook func(err error, route *Route, w http.ResponseWriter)

ErrorHook is called when an upstream error occurs.

type Extension

type Extension struct {
	*forge.BaseExtension
	// contains filtered or unexported fields
}

Extension implements the gateway extension for Forge.

func (*Extension) Auth

func (e *Extension) Auth() *GatewayAuth

Auth returns the gateway auth handler.

func (*Extension) Cache

func (e *Extension) Cache() *ResponseCache

Cache returns the response cache.

func (*Extension) Dependencies

func (e *Extension) Dependencies() []string

Dependencies returns extension dependencies.

func (*Extension) Health

func (e *Extension) Health(ctx context.Context) error

Health checks if the gateway is healthy.

func (*Extension) HealthMonitor

func (e *Extension) HealthMonitor() *HealthMonitor

HealthMonitor returns the health monitor.

func (*Extension) Hooks

func (e *Extension) Hooks() *HookEngine

Hooks returns the hook engine.

func (*Extension) OpenAPI

func (e *Extension) OpenAPI() *OpenAPIAggregator

OpenAPI returns the OpenAPI aggregator.

func (*Extension) Register

func (e *Extension) Register(app forge.App) error

Register registers the gateway extension.

func (*Extension) RouteManager

func (e *Extension) RouteManager() *RouteManager

RouteManager returns the route manager.

func (*Extension) Start

func (e *Extension) Start(ctx context.Context) error

Start starts the gateway extension.

func (*Extension) Stats

func (e *Extension) Stats() *StatsCollector

Stats returns the stats collector.

func (*Extension) Stop

func (e *Extension) Stop(_ context.Context) error

Stop stops the gateway extension.

func (*Extension) TLS

func (e *Extension) TLS() *TLSManager

TLS returns the TLS manager.

type ForgeUIIntegration

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

ForgeUIIntegration provides ForgeUI-specific functionality for the gateway dashboard.

func NewForgeUIIntegration

func NewForgeUIIntegration(
	config DashboardConfig,
	gwConfig Config,
	routeManager *RouteManager,
	healthMon *HealthMonitor,
	stats *StatsCollector,
	disc *ServiceDiscovery,
	hub *Hub,
	logger forge.Logger,
) *ForgeUIIntegration

NewForgeUIIntegration creates a new ForgeUI integration for the gateway.

func (*ForgeUIIntegration) RegisterRoutes

func (fi *ForgeUIIntegration) RegisterRoutes(r *router.Router)

RegisterRoutes registers gateway dashboard routes with a ForgeUI router.

func (*ForgeUIIntegration) Start

func (fi *ForgeUIIntegration) Start(ctx context.Context) error

Start starts background services.

func (*ForgeUIIntegration) Stop

Stop stops background services.

type ForwardAuthProvider

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

ForwardAuthProvider delegates authentication to an external auth service. It sends the original request headers to the auth endpoint and uses the response to determine authentication status.

func NewForwardAuthProvider

func NewForwardAuthProvider(name, endpoint string, headers []string) *ForwardAuthProvider

NewForwardAuthProvider creates a forward auth provider.

func (*ForwardAuthProvider) Authenticate

func (*ForwardAuthProvider) Name

func (p *ForwardAuthProvider) Name() string

type GRPCProxy

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

GRPCProxy handles gRPC reverse proxying for both unary and streaming RPCs. It works at the HTTP/2 transport layer, forwarding raw gRPC frames between client and upstream, preserving headers, trailers, and streaming semantics.

func NewGRPCProxy

func NewGRPCProxy(config Config, logger forge.Logger) *GRPCProxy

NewGRPCProxy creates a new gRPC reverse proxy engine.

func (*GRPCProxy) ServeHTTP

func (gp *GRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request, route *Route, target *Target)

ServeHTTP processes a gRPC proxy request.

type GatewayAuth

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

GatewayAuth handles authentication for gateway requests. It operates at the HTTP transport level (before request proxying), supporting multiple auth strategies and per-route configuration.

func NewGatewayAuth

func NewGatewayAuth(config AuthConfig, logger forge.Logger) *GatewayAuth

NewGatewayAuth creates a new gateway auth handler.

func (*GatewayAuth) Authenticate

func (ga *GatewayAuth) Authenticate(r *http.Request, route *Route) (*GatewayAuthContext, error)

Authenticate checks if a request is authenticated based on configuration. It supports:

  • Global auth (applied to all routes unless skipped)
  • Per-route auth overrides (specific providers, scopes, skip)
  • Multiple providers tried in order (OR logic)
  • Auth context forwarding to upstream via headers

func (*GatewayAuth) ForwardAuthHeaders

func (ga *GatewayAuth) ForwardAuthHeaders(r *http.Request, authCtx *GatewayAuthContext)

ForwardAuthHeaders adds authentication context to upstream request headers. This allows upstream services to access the authenticated user info without re-authenticating.

func (*GatewayAuth) RegisterProvider

func (ga *GatewayAuth) RegisterProvider(provider AuthProvider)

RegisterProvider registers a custom gateway-level auth provider.

func (*GatewayAuth) SetForgeAuth

func (ga *GatewayAuth) SetForgeAuth(registry AuthRegistry)

SetForgeAuth sets the optional Forge auth extension integration.

type GatewayAuthContext

type GatewayAuthContext struct {
	// Subject is the authenticated entity (user ID, service ID, etc.)
	Subject string `json:"subject"`

	// Claims holds additional authentication claims (roles, permissions, etc.)
	Claims map[string]any `json:"claims,omitempty"`

	// Scopes holds OAuth2 scopes or permission strings
	Scopes []string `json:"scopes,omitempty"`

	// ProviderName identifies which auth provider authenticated this request
	ProviderName string `json:"providerName"`
}

GatewayAuthContext holds authenticated subject information for gateway requests.

func (*GatewayAuthContext) HasScope

func (a *GatewayAuthContext) HasScope(scope string) bool

HasScope checks if the auth context has a specific scope.

func (*GatewayAuthContext) HasScopes

func (a *GatewayAuthContext) HasScopes(scopes ...string) bool

HasScopes checks if the auth context has all specified scopes.

type GatewayMetrics

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

GatewayMetrics manages Prometheus metrics for the gateway.

func NewGatewayMetrics

func NewGatewayMetrics(metrics forge.Metrics, config MetricsConfig) *GatewayMetrics

NewGatewayMetrics creates a new gateway metrics collector.

func (*GatewayMetrics) RecordCacheHit

func (gm *GatewayMetrics) RecordCacheHit()

RecordCacheHit records a cache hit.

func (*GatewayMetrics) RecordCacheMiss

func (gm *GatewayMetrics) RecordCacheMiss()

RecordCacheMiss records a cache miss.

func (*GatewayMetrics) RecordLatency

func (gm *GatewayMetrics) RecordLatency(routeID, method, upstream string, seconds float64)

RecordLatency records request latency.

func (*GatewayMetrics) RecordRateLimited

func (gm *GatewayMetrics) RecordRateLimited()

RecordRateLimited records a rate-limited request.

func (*GatewayMetrics) RecordRequest

func (gm *GatewayMetrics) RecordRequest(routeID, method, status, upstream string)

RecordRequest records a request metric.

func (*GatewayMetrics) RecordRetry

func (gm *GatewayMetrics) RecordRetry(routeID string, attempt int)

RecordRetry records a retry attempt.

func (*GatewayMetrics) SetActiveConnections

func (gm *GatewayMetrics) SetActiveConnections(protocol string, count float64)

SetActiveConnections sets the active connections gauge.

func (*GatewayMetrics) SetCircuitBreakerState

func (gm *GatewayMetrics) SetCircuitBreakerState(targetID string, state CircuitState)

SetCircuitBreakerState sets the circuit breaker state gauge.

func (*GatewayMetrics) SetDiscoveryRoutes

func (gm *GatewayMetrics) SetDiscoveryRoutes(source string, count float64)

SetDiscoveryRoutes sets the count of discovered routes by source.

func (*GatewayMetrics) SetUpstreamHealth

func (gm *GatewayMetrics) SetUpstreamHealth(targetID string, healthy bool)

SetUpstreamHealth sets the upstream health gauge.

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     float64                `json:"avgLatencyMs"`
	P99LatencyMs     float64                `json:"p99LatencyMs"`
	RequestsPerSec   float64                `json:"requestsPerSec"`
	CacheHits        int64                  `json:"cacheHits"`
	CacheMisses      int64                  `json:"cacheMisses"`
	RateLimited      int64                  `json:"rateLimited"`
	CircuitBreaks    int64                  `json:"circuitBreaks"`
	RetryAttempts    int64                  `json:"retryAttempts"`
	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

type HealthCheckConfig struct {
	Enabled              bool          `json:"enabled" yaml:"enabled"`
	Interval             time.Duration `json:"interval" yaml:"interval"`
	Timeout              time.Duration `json:"timeout" yaml:"timeout"`
	Path                 string        `json:"path" yaml:"path"`
	FailureThreshold     int           `json:"failureThreshold" yaml:"failure_threshold"`
	SuccessThreshold     int           `json:"successThreshold" yaml:"success_threshold"`
	EnablePassive        bool          `json:"enablePassive" yaml:"enable_passive"`
	PassiveFailThreshold int           `json:"passiveFailThreshold" yaml:"passive_fail_threshold"`
}

HealthCheckConfig holds health check settings.

type HealthMonitor

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

HealthMonitor monitors the health of upstream targets.

func NewHealthMonitor

func NewHealthMonitor(config HealthCheckConfig, logger forge.Logger) *HealthMonitor

NewHealthMonitor creates a new health monitor.

func (*HealthMonitor) Deregister

func (hm *HealthMonitor) Deregister(targetID string)

Deregister removes a target from health monitoring.

func (*HealthMonitor) Health

func (hm *HealthMonitor) Health(_ context.Context) error

Health returns an error if no targets are healthy (for HealthManager integration).

func (*HealthMonitor) RecordPassiveFailure

func (hm *HealthMonitor) RecordPassiveFailure(targetID string)

RecordPassiveFailure records a passive health check failure.

func (*HealthMonitor) RecordPassiveSuccess

func (hm *HealthMonitor) RecordPassiveSuccess(targetID string)

RecordPassiveSuccess records a passive health check success.

func (*HealthMonitor) Register

func (hm *HealthMonitor) Register(routeID string, target *Target)

Register registers a target for health monitoring.

func (*HealthMonitor) SetOnHealthChange

func (hm *HealthMonitor) SetOnHealthChange(fn func(event UpstreamHealthEvent))

SetOnHealthChange sets the health change callback.

func (*HealthMonitor) Start

func (hm *HealthMonitor) Start(ctx context.Context)

Start starts the health monitor background loop.

func (*HealthMonitor) Stop

func (hm *HealthMonitor) Stop()

Stop stops the health monitor.

type HookEngine

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

HookEngine manages gateway hooks.

func NewHookEngine

func NewHookEngine() *HookEngine

NewHookEngine creates a new hook engine.

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 Hub

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

Hub maintains the set of active WebSocket clients.

func NewHub

func NewHub(logger forge.Logger) *Hub

NewHub creates a new WebSocket hub.

func (*Hub) Broadcast

func (h *Hub) Broadcast(data any) error

Broadcast sends a message to all connected clients.

func (*Hub) ClientCount

func (h *Hub) ClientCount() int

ClientCount returns the number of connected clients.

func (*Hub) Run

func (h *Hub) Run()

Run starts the hub's main loop.

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 struct {
	// contains filtered or unexported fields
}

InMemoryCacheStore provides a simple in-memory LRU cache for the gateway. It is used as the default cache backend when no external store is configured.

func NewInMemoryCacheStore

func NewInMemoryCacheStore(maxSize int) *InMemoryCacheStore

NewInMemoryCacheStore creates a new in-memory cache store.

func (*InMemoryCacheStore) CleanExpired

func (s *InMemoryCacheStore) CleanExpired()

CleanExpired removes all expired entries.

func (*InMemoryCacheStore) Delete

func (s *InMemoryCacheStore) Delete(_ context.Context, key string) error

func (*InMemoryCacheStore) Get

func (s *InMemoryCacheStore) Get(_ context.Context, key string) ([]byte, error)

func (*InMemoryCacheStore) Set

func (s *InMemoryCacheStore) Set(_ context.Context, key string, value []byte, ttl time.Duration) error

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.

func NewLoadBalancer

func NewLoadBalancer(strategy LoadBalanceStrategy) LoadBalancer

NewLoadBalancer creates a load balancer for the given strategy.

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 MetricsConfig

type MetricsConfig struct {
	Enabled bool   `json:"enabled" yaml:"enabled"`
	Prefix  string `json:"prefix,omitempty" yaml:"prefix"`
}

MetricsConfig holds metrics settings.

type OpenAPIAggregator

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

OpenAPIAggregator fetches, caches, and merges OpenAPI specs from all discovered upstream services (via FARP metadata). It exposes:

  • A unified merged OpenAPI spec combining all service paths under gateway prefixes
  • Per-service OpenAPI specs fetched and cached from upstream endpoints
  • A Swagger UI for browsing the aggregated spec

Schema fetching uses the `farp.openapi` metadata key set by the discovery extension's SchemaPublisher. The aggregator periodically refreshes specs and supports on-demand refresh.

func NewOpenAPIAggregator

func NewOpenAPIAggregator(config OpenAPIConfig, logger forge.Logger, rm *RouteManager, disc *ServiceDiscovery) *OpenAPIAggregator

NewOpenAPIAggregator creates a new OpenAPI aggregator.

func (*OpenAPIAggregator) HandleMergedSpec

func (oa *OpenAPIAggregator) HandleMergedSpec(ctx forge.Context) error

HandleMergedSpec serves the aggregated OpenAPI spec as JSON.

func (*OpenAPIAggregator) HandleRefresh

func (oa *OpenAPIAggregator) HandleRefresh(ctx forge.Context) error

HandleRefresh triggers an immediate spec refresh.

func (*OpenAPIAggregator) HandleServiceList

func (oa *OpenAPIAggregator) HandleServiceList(ctx forge.Context) error

HandleServiceList returns a summary of all services with their OpenAPI spec status.

func (*OpenAPIAggregator) HandleServiceSpec

func (oa *OpenAPIAggregator) HandleServiceSpec(ctx forge.Context) error

HandleServiceSpec serves the OpenAPI spec for a specific service.

func (*OpenAPIAggregator) HandleSwaggerUI

func (oa *OpenAPIAggregator) HandleSwaggerUI(ctx forge.Context) error

HandleSwaggerUI serves a Swagger UI page for the aggregated spec.

func (*OpenAPIAggregator) LastRefresh

func (oa *OpenAPIAggregator) LastRefresh() time.Time

LastRefresh returns the time of the last spec refresh.

func (*OpenAPIAggregator) MergedSpec

func (oa *OpenAPIAggregator) MergedSpec() []byte

MergedSpec returns the pre-serialized merged OpenAPI spec JSON.

func (*OpenAPIAggregator) MergedSpecMap

func (oa *OpenAPIAggregator) MergedSpecMap() map[string]any

MergedSpecMap returns the merged spec as a map.

func (*OpenAPIAggregator) Refresh

func (oa *OpenAPIAggregator) Refresh(ctx context.Context)

Refresh fetches all upstream OpenAPI specs and rebuilds the merged spec.

func (*OpenAPIAggregator) ServiceSpec

func (oa *OpenAPIAggregator) ServiceSpec(serviceName string) *ServiceOpenAPISpec

ServiceSpec returns the cached spec for a specific service.

func (*OpenAPIAggregator) ServiceSpecs

func (oa *OpenAPIAggregator) ServiceSpecs() map[string]*ServiceOpenAPISpec

ServiceSpecs returns all cached service specs.

func (*OpenAPIAggregator) Start

func (oa *OpenAPIAggregator) Start(ctx context.Context)

Start begins the periodic spec refresh loop.

type OpenAPIConfig

type OpenAPIConfig struct {
	// Enabled turns on/off the OpenAPI aggregation feature
	Enabled bool `json:"enabled" yaml:"enabled"`

	// Path is the endpoint path to serve the aggregated OpenAPI spec
	Path string `json:"path" yaml:"path"`

	// UIPath is the endpoint path to serve the Swagger UI
	UIPath string `json:"uiPath" yaml:"ui_path"`

	// Title is the title for the aggregated spec
	Title string `json:"title" yaml:"title"`

	// Description is the description for the aggregated spec
	Description string `json:"description" yaml:"description"`

	// Version is the version for the aggregated spec
	Version string `json:"version" yaml:"version"`

	// RefreshInterval is how often to re-fetch upstream specs
	RefreshInterval time.Duration `json:"refreshInterval" yaml:"refresh_interval"`

	// FetchTimeout is the timeout for fetching a single upstream spec
	FetchTimeout time.Duration `json:"fetchTimeout" yaml:"fetch_timeout"`

	// StripServicePrefix controls whether service prefixes are included in paths
	StripServicePrefix bool `json:"stripServicePrefix" yaml:"strip_service_prefix"`

	// MergeStrategy controls how conflicting paths are handled:
	// "prefix" (default) - prefix all paths with /{serviceName}
	// "flat" - merge paths as-is, last wins on conflict
	MergeStrategy string `json:"mergeStrategy" yaml:"merge_strategy"`

	// IncludeGatewayRoutes includes the gateway's own admin routes in the spec
	IncludeGatewayRoutes bool `json:"includeGatewayRoutes" yaml:"include_gateway_routes"`

	// ExcludeServices is a list of service names to exclude from aggregation
	ExcludeServices []string `json:"excludeServices,omitempty" yaml:"exclude_services"`

	// ContactName is the contact name for the spec info
	ContactName string `json:"contactName,omitempty" yaml:"contact_name"`

	// ContactEmail is the contact email for the spec info
	ContactEmail string `json:"contactEmail,omitempty" yaml:"contact_email"`
}

OpenAPIConfig holds configuration for the OpenAPI aggregation feature.

func DefaultOpenAPIConfig

func DefaultOpenAPIConfig() OpenAPIConfig

DefaultOpenAPIConfig returns defaults for OpenAPI aggregation.

type PathRewriter

type PathRewriter struct{}

PathRewriter rewrites request paths according to route configuration.

type ProxyEngine

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

ProxyEngine handles HTTP reverse proxying to upstream targets.

func NewProxyEngine

func NewProxyEngine(
	config Config,
	logger forge.Logger,
	rm *RouteManager,
	hm *HealthMonitor,
	cbm *CircuitBreakerManager,
	rl *RateLimiter,
	stats *StatsCollector,
	hooks *HookEngine,
) *ProxyEngine

NewProxyEngine creates a new proxy engine.

func (*ProxyEngine) ServeHTTP

func (pe *ProxyEngine) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP is the main gateway handler.

func (*ProxyEngine) SetAuth

func (pe *ProxyEngine) SetAuth(auth *GatewayAuth)

SetAuth sets the gateway auth handler on the proxy engine.

func (*ProxyEngine) SetCache

func (pe *ProxyEngine) SetCache(cache *ResponseCache)

SetCache sets the response cache on the proxy engine.

func (*ProxyEngine) SetTLSManager

func (pe *ProxyEngine) SetTLSManager(tlsMgr *TLSManager)

SetTLSManager sets the TLS manager on the proxy engine.

type RateLimitConfig

type RateLimitConfig struct {
	Enabled        bool    `json:"enabled" yaml:"enabled"`
	RequestsPerSec float64 `json:"requestsPerSec" yaml:"requests_per_sec"`
	Burst          int     `json:"burst" yaml:"burst"`
	PerClient      bool    `json:"perClient" yaml:"per_client"`
	KeyHeader      string  `json:"keyHeader,omitempty" yaml:"key_header"`
}

RateLimitConfig holds rate limiting settings.

type RateLimiter

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

RateLimiter implements token-bucket rate limiting.

func NewRateLimiter

func NewRateLimiter(config RateLimitConfig) *RateLimiter

NewRateLimiter creates a new rate limiter.

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(r *http.Request) bool

Allow checks if a request is allowed.

func (*RateLimiter) AllowWithConfig

func (rl *RateLimiter) AllowWithConfig(r *http.Request, config *RateLimitConfig) bool

AllowWithConfig checks rate limit with a per-route override.

func (*RateLimiter) Cleanup

func (rl *RateLimiter) Cleanup(maxAge time.Duration)

Cleanup removes stale buckets older than the given duration.

type RequestHook

type RequestHook func(r *http.Request, route *Route) error

RequestHook is called before a request is proxied. Return a non-nil error to reject the request.

type ResponseCache

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

ResponseCache provides HTTP response caching for the gateway. It supports:

  • Configurable cache backends (in-memory, external via CacheStore interface)
  • Per-route cache policies with TTL, vary-by headers, and method filtering
  • Cache-Control header respect (no-cache, no-store, max-age)
  • Automatic cache key generation based on method, path, query, and vary-by headers
  • Cache invalidation via admin API
  • Metrics (hits/misses)

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. Returns nil if not cached, cache is disabled, or the request is not cacheable.

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 ResponseHook

type ResponseHook func(resp *http.Response, route *Route)

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 RetryExecutor

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

RetryExecutor manages retry logic for proxy requests.

func NewRetryExecutor

func NewRetryExecutor(config RetryConfig) *RetryExecutor

NewRetryExecutor creates a new retry executor.

func (*RetryExecutor) Delay

func (re *RetryExecutor) Delay(attempt int, routeConfig *RetryConfig) time.Duration

Delay returns the delay before the next retry attempt.

func (*RetryExecutor) ShouldRetry

func (re *RetryExecutor) ShouldRetry(method string, statusCode int, attempt int, routeConfig *RetryConfig) bool

ShouldRetry determines if a request should be retried.

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 ConvertFARPRoutes

func ConvertFARPRoutes(serviceName string, farpRoutes []farpgw.ServiceRoute, prefix string, stripPrefix bool) []*Route

ConvertFARPRoutes converts FARP gateway client ServiceRoutes into gateway Routes.

type RouteAuthConfig

type RouteAuthConfig struct {
	Enabled     bool     `json:"enabled"`
	Providers   []string `json:"providers,omitempty"`
	Scopes      []string `json:"scopes,omitempty"`
	SkipAuth    bool     `json:"skipAuth,omitempty"`
	ForwardAuth bool     `json:"forwardAuth,omitempty"`
}

RouteAuthConfig defines per-route auth requirements.

type RouteCacheConfig

type RouteCacheConfig struct {
	Enabled bool          `json:"enabled"`
	TTL     time.Duration `json:"ttl,omitempty"`
	Methods []string      `json:"methods,omitempty"`
	VaryBy  []string      `json:"varyBy,omitempty"`
}

RouteCacheConfig defines per-route caching policy.

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"`
}

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 RouteManager

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

RouteManager manages the dynamic route table with thread-safe operations.

func NewRouteManager

func NewRouteManager() *RouteManager

NewRouteManager creates a new route manager.

func (*RouteManager) AddRoute

func (rm *RouteManager) AddRoute(route *Route) error

AddRoute adds a new route to the table.

func (*RouteManager) GetRoute

func (rm *RouteManager) GetRoute(id string) (*Route, bool)

GetRoute returns a route by ID.

func (*RouteManager) ListRoutes

func (rm *RouteManager) ListRoutes() []*Route

ListRoutes returns all routes.

func (*RouteManager) MatchRoute

func (rm *RouteManager) MatchRoute(path, method string) *Route

MatchRoute finds the best matching route for a request path and method.

func (*RouteManager) OnRouteChange

func (rm *RouteManager) OnRouteChange(fn func(RouteEvent))

OnRouteChange registers a listener for route events.

func (*RouteManager) RemoveByServiceName

func (rm *RouteManager) RemoveByServiceName(serviceName string)

RemoveByServiceName removes all routes for a service.

func (*RouteManager) RemoveBySource

func (rm *RouteManager) RemoveBySource(source RouteSource)

RemoveBySource removes all routes from a specific source.

func (*RouteManager) RemoveRoute

func (rm *RouteManager) RemoveRoute(id string) error

RemoveRoute removes a route by ID.

func (*RouteManager) RouteCount

func (rm *RouteManager) RouteCount() int

RouteCount returns the number of routes.

func (*RouteManager) UpdateRoute

func (rm *RouteManager) UpdateRoute(route *Route) error

UpdateRoute updates an existing route.

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 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  float64 `json:"avgLatencyMs"`
	P99LatencyMs  float64 `json:"p99LatencyMs"`
	CacheHits     int64   `json:"cacheHits"`
	CacheMisses   int64   `json:"cacheMisses"`
	RateLimited   int64   `json:"rateLimited"`
}

RouteStats holds per-route traffic statistics.

type SSEConfig

type SSEConfig struct {
	FlushInterval time.Duration `json:"flushInterval" yaml:"flush_interval"`
}

SSEConfig holds SSE proxy settings.

type ServiceDiscovery

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

ServiceDiscovery integrates FARP and service discovery for automatic route generation.

func NewServiceDiscovery

func NewServiceDiscovery(
	config DiscoveryConfig,
	logger forge.Logger,
	rm *RouteManager,
	discService DiscoveryService,
) *ServiceDiscovery

NewServiceDiscovery creates a new service discovery integration.

func (*ServiceDiscovery) DiscoveredServices

func (sd *ServiceDiscovery) DiscoveredServices() []*DiscoveredService

DiscoveredServices returns all discovered services.

func (*ServiceDiscovery) Refresh

func (sd *ServiceDiscovery) Refresh(ctx context.Context) error

Refresh forces a re-scan of services.

func (*ServiceDiscovery) Start

func (sd *ServiceDiscovery) Start(ctx context.Context) error

Start begins service discovery.

func (*ServiceDiscovery) Stop

func (sd *ServiceDiscovery) Stop()

Stop stops service discovery.

type ServiceFilter

type ServiceFilter struct {
	IncludeNames    []string          `json:"includeNames,omitempty" yaml:"include_names"`
	ExcludeNames    []string          `json:"excludeNames,omitempty" yaml:"exclude_names"`
	IncludeTags     []string          `json:"includeTags,omitempty" yaml:"include_tags"`
	ExcludeTags     []string          `json:"excludeTags,omitempty" yaml:"exclude_tags"`
	RequireMetadata map[string]string `json:"requireMetadata,omitempty" yaml:"require_metadata"`
}

ServiceFilter defines a filter for discovered services.

type ServiceInstanceInfo

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

ServiceInstanceInfo represents a discovered service instance. This mirrors the fields we need from discovery.ServiceInstance.

func (*ServiceInstanceInfo) IsHealthy

func (si *ServiceInstanceInfo) IsHealthy() bool

IsHealthy returns whether the instance is healthy.

func (*ServiceInstanceInfo) URL

func (si *ServiceInstanceInfo) URL(scheme string) string

URL returns the full URL for the service instance.

type ServiceOpenAPISpec

type ServiceOpenAPISpec struct {
	ServiceName string         `json:"serviceName"`
	Version     string         `json:"version"`
	SpecURL     string         `json:"specUrl"`
	Spec        map[string]any `json:"spec,omitempty"`
	FetchedAt   time.Time      `json:"fetchedAt"`
	Error       string         `json:"error,omitempty"`
	Healthy     bool           `json:"healthy"`
	PathCount   int            `json:"pathCount"`
}

ServiceOpenAPISpec holds a cached OpenAPI spec for a single upstream service.

type StatsCollector

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

StatsCollector collects gateway-level statistics.

func NewStatsCollector

func NewStatsCollector() *StatsCollector

NewStatsCollector creates a new stats collector.

func (*StatsCollector) Snapshot

func (sc *StatsCollector) Snapshot(rm *RouteManager, hm *HealthMonitor) *GatewayStats

Snapshot returns the current gateway stats.

type TLSConfig

type TLSConfig struct {
	Enabled            bool          `json:"enabled" yaml:"enabled"`
	CACertFile         string        `json:"caCertFile,omitempty" yaml:"ca_cert_file"`
	ClientCertFile     string        `json:"clientCertFile,omitempty" yaml:"client_cert_file"`
	ClientKeyFile      string        `json:"clientKeyFile,omitempty" yaml:"client_key_file"`
	InsecureSkipVerify bool          `json:"insecureSkipVerify,omitempty" yaml:"insecure_skip_verify"`
	MinVersion         string        `json:"minVersion,omitempty" yaml:"min_version"`
	CipherSuites       []string      `json:"cipherSuites,omitempty" yaml:"cipher_suites"`
	ReloadInterval     time.Duration `json:"reloadInterval,omitempty" yaml:"reload_interval"`
}

TLSConfig holds upstream TLS settings.

type TLSManager

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

TLSManager manages TLS configurations for upstream connections. It supports:

  • Global TLS configuration for all upstream connections
  • Per-target TLS overrides (specific CA certs, client certs for mTLS)
  • Automatic certificate reloading on a configurable interval
  • TLS version and cipher suite configuration
  • InsecureSkipVerify for development/testing

func NewTLSManager

func NewTLSManager(config TLSConfig, logger forge.Logger) *TLSManager

NewTLSManager creates a new TLS manager.

func (*TLSManager) GlobalTLSConfig

func (tm *TLSManager) GlobalTLSConfig() *tls.Config

GlobalTLSConfig returns the current global TLS configuration. This is safe for concurrent use.

func (*TLSManager) LastReload

func (tm *TLSManager) LastReload() time.Time

LastReload returns the time of the last certificate reload.

func (*TLSManager) Reload

func (tm *TLSManager) Reload() error

Reload forces an immediate certificate reload.

func (*TLSManager) Start

func (tm *TLSManager) Start()

Start begins the certificate reload loop if configured.

func (*TLSManager) Stop

func (tm *TLSManager) Stop()

Stop stops the certificate reload loop.

func (*TLSManager) TargetTLSConfig

func (tm *TLSManager) TargetTLSConfig(target *Target) *tls.Config

TargetTLSConfig returns a TLS configuration for a specific target. If the target has per-target TLS overrides, those are used. Otherwise, the global TLS config is returned.

func (*TLSManager) TransportForTarget

func (tm *TLSManager) TransportForTarget(baseTransport *http.Transport, target *Target) *http.Transport

TransportForTarget returns an http.Transport configured with the appropriate TLS settings for the given target.

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) DecrConns

func (t *Target) DecrConns()

DecrConns decrements active connections.

func (*Target) IncrConns

func (t *Target) IncrConns()

IncrConns increments active connections.

func (*Target) IsDraining

func (t *Target) IsDraining() bool

IsDraining returns true if the target is draining.

func (*Target) RecordRequest

func (t *Target) RecordRequest(latency time.Duration, isError bool)

RecordRequest records a request outcome.

func (*Target) SetDraining

func (t *Target) SetDraining(v bool)

SetDraining sets the draining state.

func (*Target) Snapshot

func (t *Target) Snapshot()

Snapshot populates the exported stats fields from atomics.

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 TargetTLSConfig

type TargetTLSConfig struct {
	Enabled            bool   `json:"enabled"`
	CACertFile         string `json:"caCertFile,omitempty"`
	ClientCertFile     string `json:"clientCertFile,omitempty"`
	ClientKeyFile      string `json:"clientKeyFile,omitempty"`
	InsecureSkipVerify bool   `json:"insecureSkipVerify,omitempty"`
	ServerName         string `json:"serverName,omitempty"`
}

TargetTLSConfig holds per-target TLS configuration.

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.

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 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 TrafficSplitter

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

TrafficSplitter evaluates traffic rules to determine target selection.

func NewTrafficSplitter

func NewTrafficSplitter(enabled bool) *TrafficSplitter

NewTrafficSplitter creates a new traffic splitter.

func (*TrafficSplitter) FilterTargets

func (ts *TrafficSplitter) FilterTargets(r *http.Request, route *Route) []*Target

FilterTargets filters targets based on the route's traffic policy and request. Returns the filtered targets, or the original targets if no policy applies.

func (*TrafficSplitter) ShouldMirror

func (ts *TrafficSplitter) ShouldMirror(route *Route) string

ShouldMirror returns the mirror target URL if the request should be mirrored.

type TransformConfig

type TransformConfig struct {
	RequestHeaders  HeaderPolicy `json:"requestHeaders,omitempty"`
	ResponseHeaders HeaderPolicy `json:"responseHeaders,omitempty"`
}

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 WSMessage

type WSMessage struct {
	Type      string    `json:"type"`
	Timestamp time.Time `json:"timestamp"`
	Data      any       `json:"data"`
}

WSMessage represents a WebSocket message.

func NewWSMessage

func NewWSMessage(msgType string, data any) WSMessage

NewWSMessage creates a new WebSocket message.

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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