bastion

package module
v1.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: MIT Imports: 24 Imported by: 0

README

Bastion, an API gateway for Go that runs as a Forge extension, with load balancing and service discovery

Bastion: API gateway for Go and Forge

Bastion is an API gateway and reverse proxy written in Go that runs as an extension inside a Forge app. It proxies HTTP, WebSocket, SSE and gRPC traffic to your upstream services, builds routes from config, from an admin API or from FARP service discovery, and adds load balancing, circuit breakers, retries, health checks, rate limiting, traffic splitting (canary, blue-green, A/B, mirror), authentication, response caching and OpenAPI aggregation. Bastion replaced Forge's old extensions/gateway package and lives in its own module.

CI Go Reference GitHub Stars

Documentation · Quick start · Features · Routes · Discovery · Admin API · Configuration · FAQ

Quick start

You need Go 1.26 or later.

go get github.com/xraph/bastion@latest
go get github.com/xraph/forge/extensions/discovery@latest

Save this as main.go. It sends everything under /users/ to a service on port 9100:

package main

import (
	"log"

	"github.com/xraph/bastion"
	"github.com/xraph/bastion/gateway"
	"github.com/xraph/forge"
	"github.com/xraph/forge/extensions/discovery"
)

func main() {
	app := forge.NewApp(forge.AppConfig{
		Name:        "edge",
		HTTPAddress: ":8080",
		Extensions: []forge.Extension{
			discovery.NewExtension(discovery.WithBackend("memory")),
			gateway.New(
				bastion.WithRoute(bastion.RouteConfig{
					Path:        "/users/*",
					Targets:     []bastion.TargetConfig{{URL: "http://localhost:9100", Weight: 1}},
					StripPrefix: true,
					Enabled:     true,
				}),
				bastion.WithAdminToken("change-me"),
			),
		},
	})

	if err := app.Run(); err != nil {
		log.Fatal(err)
	}
}

Start any HTTP service on port 9100 (python3 -m http.server 9100 will do), then run the gateway:

go mod tidy
go run .

From another terminal:

curl -i http://localhost:8080/users/42
# the upstream sees GET /42, and the response carries X-Gateway-Route: manual-/users/*

curl -H "Authorization: Bearer change-me" http://localhost:8080/gateway/api/routes

The second call lists the routes the gateway knows about, including your manual one and anything discovery found. Without the token it answers 401.

The gateway lists Forge's discovery extension as a dependency, which is why the example registers it with the in-memory backend. Leave it out and Bastion logs a warning and serves only your configured and admin-created routes.

Why Bastion?

You already run your services on Forge, and the usual next step is putting nginx, Envoy or Kong in front of them, with a second config language and a second deploy. Bastion is the gateway as one more extension in a Forge app, so it uses the same config files, logger, metrics, health checks and container as the services behind it, and you can hook into requests with plain Go functions.

You need Bastion gives you
A reverse proxy for every protocol HTTP, WebSocket, SSE, gRPC and GraphQL routes, each with path rewriting, prefix stripping and header policies
Routes that follow your services FARP discovery that builds routes from what your services publish, with a prefix per service, plus a push registration endpoint
Spreading load Round robin, weighted round robin, random, least connections and consistent hashing
Not hammering a sick upstream Per-target circuit breakers, active health probes and passive failure tracking
Retrying safely Exponential, linear or fixed backoff with jitter, a retry budget, and retries only on idempotent methods and 502, 503 and 504 by default
Releasing gradually Canary, blue-green, A/B and weighted splits by header, cookie, weight or IP range, plus traffic mirroring
Guarding the edge API key, bearer token, forward auth and JWT providers, IP allow and deny lists, CORS, and TLS or mTLS to upstreams; a WAF ships as a plugin (security.NewWAFPlugin) you attach with the plugin package
Cutting load on upstreams Token-bucket rate limiting (global, per route, per client) and in-memory response caching
One API reference OpenAPI and AsyncAPI specs fetched from your services and merged into one document
Operating it An admin REST API, a WebSocket event stream, and a contributor for the Forge dashboard

Routes

A route matches a path (and optionally methods) and sends the request to one or more targets:

bastion.WithRoute(bastion.RouteConfig{
	Path:        "/orders/*",
	Methods:     []string{"GET", "POST"},
	Targets: []bastion.TargetConfig{
		{URL: "http://orders-a:8080", Weight: 3},
		{URL: "http://orders-b:8080", Weight: 1},
	},
	StripPrefix: true,
	Protocol:    bastion.ProtocolHTTP,
	Enabled:     true,
})

You set Protocol to ProtocolHTTP, ProtocolWebSocket, ProtocolSSE, ProtocolGRPC or ProtocolGraphQL. If one route needs different behaviour from the rest, you can give it its own Retry, Timeout, RateLimit, Auth, Cache and TrafficPolicy, and you change what the upstream sees with AddPrefix, RewritePath and Headers.

Every proxied response carries an X-Gateway-Route header naming the route that matched. Check it first when a request lands somewhere you didn't expect.

Routes come from three places. You write manual routes with WithRoute, WithRoutes or the routes key in your config. Discovery routes come from FARP and get rebuilt on every update. And you or your operators can create routes through the REST API or the dashboard. You can only edit manual and admin-created routes through the admin API, because discovery would overwrite anything you changed on its routes the next time it ran.

Service discovery with FARP

Turn discovery on and Bastion asks Forge's discovery extension (Consul, etcd, Kubernetes, Eureka, mDNS or memory) for services, then reads the routes each one publishes through FARP. By default each service gets the prefix /{{.ServiceName}}, which is stripped before the request goes upstream:

discovery.NewExtension(
	discovery.WithBackend("consul"),
	discovery.WithConsul("localhost:8500", ""),
),
gateway.New(
	bastion.WithDiscoveryEnabled(true),
	bastion.WithDiscoveryPrefixTemplate("/api/{{.ServiceName}}"),
),

Discovery polls every 30 seconds. You can filter which services become routes with WithDiscoveryServiceFilters, rename prefixes with WithDiscoveryPrefixOverrides, and keep other Forge extensions' paths out with WithExtensionFilter. Services can also push-register themselves at POST /_farp/v1/register, with heartbeats at PUT /_farp/v1/heartbeat/:id. Those endpoints are mounted with the admin API, so they need dashboard.enabled, but they skip the admin auth, because the services calling them have no admin credentials.

If your services publish OpenAPI through FARP, Bastion fetches their specs and merges them into one document at /gateway/openapi.json, with per-service specs under /gateway/api/openapi/services. Your API consumers get one reference for everything behind the gateway. Turn on WithOpenAPIRootDocs(true) if you also want the merged spec at /openapi.json and Swagger UI at /docs.

These spec endpoints are mounted whenever OpenAPI aggregation is on (openapi.enabled, the default), whatever dashboard.enabled says. They don't sit behind the admin token or admin middleware either, and that includes POST /gateway/api/openapi/refresh, which makes the gateway re-fetch every upstream spec. If your specs aren't public, or you don't want anyone triggering a refresh, put your own guard in front of those paths or turn aggregation off with WithOpenAPIEnabled(false).

Hooks and auth providers

Hooks() gives you OnRequest, OnResponse, OnError, OnRouteChange, OnUpstreamHealth and OnCircuitBreak. The hook engine exists once the app has registered the gateway, so add your hooks in a Forge lifecycle hook:

gw := gateway.New(bastion.WithRoutes(routes))

app := forge.NewApp(forge.AppConfig{Name: "edge", Extensions: []forge.Extension{gw}})

err := app.RegisterHookFn(forge.PhaseAfterRegister, "bastion-hooks", func(ctx context.Context, app forge.App) error {
	gw.Hooks().OnRequest(func(r *http.Request, route *bastion.Route) error {
		r.Header.Set("X-Edge", "bastion")
		return nil
	})
	return nil
})

If your OnRequest hook returns an error, the request stops there. For gateway-level auth, you register a provider from the security package with gw.Auth().RegisterProvider(...) and list its name in AuthConfig.Providers: NewAPIKeyAuthProvider, NewBearerTokenAuthProvider, NewForwardAuthProvider or NewJWTAuthProvider.

JWT provider

Point it at your identity provider's JWKS and register it in the same kind of hook:

gw := gateway.New(
	bastion.WithRoutes(routes),
	bastion.WithAuth(bastion.AuthConfig{Enabled: true, Providers: []string{"jwt"}, ForwardHeaders: true}),
)

err := app.RegisterHookFn(forge.PhaseAfterRegister, "bastion-jwt", func(ctx context.Context, app forge.App) error {
	gw.Auth().RegisterProvider(security.NewJWTAuthProvider(security.JWTAuthConfig{
		Name:     "jwt",
		JWKSURL:  "https://idp.example.com/.well-known/jwks.json",
		Issuer:   "https://idp.example.com",
		Audience: "orders-api",
	}))
	return nil
})

That's all you need. The gateway runs the provider for you, whether you register it before the gateway starts or after: the provider fetches the JWKS during startup, refreshes it every RefreshInterval (an hour unless you set it) and stops when the gateway does. You don't have to call StartKeyRefresh. If you already do, it keeps working, and a second start does nothing.

The provider rejects every token until it holds a verification key, so while your identity provider is unreachable at boot, the routes behind it answer 401. If that first fetch fails, the refresh retries a few seconds later and backs off toward the refresh interval, and a request that finds no key loaded asks for one too (once every five seconds at most). A failed fetch, or a JWKS with no usable key in it, leaves the keys you already have in place.

A token whose kid the provider hasn't loaded makes it fetch again, inside the same five-second limit, so a key your identity provider has just rotated in works straight away. A request waits at most three seconds on a fetch.

Leave JWKSURL empty and the provider accepts nothing. Give it an https URL. The fetch only follows redirects to https, and the gateway logs a warning at start for a plain http JWKS anywhere but loopback.

It accepts RS256, RS384, RS512, ES256, ES384 and ES512. Set Algorithms to narrow that list. A token signed with anything else, none included, is rejected before the provider looks at a key. When a token names a kid, the key has to carry that kid. When it doesn't, the provider uses the one key that fits the token's algorithm and rejects the token if several do. That's how a JWKS with a single key and no kid works. Either way, an ES token is never checked with an RSA key, or the other way round.

A client that's turned away gets a 401 saying invalid token (or token expired for a good token past its exp). The reason goes to the gateway's debug log.

The gateway drops any X-Auth-Subject, X-Auth-Provider, X-Auth-Scopes, X-Auth-Role or X-Auth-Email a client sends, on every route, so the ones your upstream sees are the ones the gateway set. Other X-Auth- headers pass through untouched.

Persist routes in a database

The gateway package keeps admin-created routes in memory, so they're gone after a restart, and it doesn't pull in any database driver. If you want them persisted, use the extension package. It's the same gateway plus a store:

import bastionext "github.com/xraph/bastion/extension"

bastionext.New(
	bastion.WithAdminToken(os.Getenv("BASTION_ADMIN_TOKEN")),
).Configure(bastionext.WithGroveDatabase("main"))

The store comes from bastionext.WithStore(s), then the named *grove.DB from WithGroveDatabase, then the default *grove.DB in the container. The Grove driver picks the PostgreSQL, SQLite or MongoDB backend, and the store's migrations run at start unless you pass bastionext.WithDisableMigrate(). With none of those, the gateway runs in memory. Only the in-memory store has tests today, so check the database backends against a real server before you rely on them.

Admin API

The admin API is mounted under the dashboard base path, /gateway by default:

Method Path What it does
GET, POST /gateway/api/routes List routes, or create a manual route
GET, PUT, DELETE /gateway/api/routes/:id Read, update or delete a route
POST /gateway/api/routes/:id/enable, /gateway/api/routes/:id/disable Turn a route on or off
GET /gateway/api/upstreams Targets with health and circuit state
GET /gateway/api/stats, /gateway/api/stats/routes Gateway and per-route statistics
GET /gateway/api/config The running configuration
GET /gateway/api/discovery/services Services discovery has found
POST /gateway/api/discovery/refresh Re-scan discovery now
GET /gateway/ws Real-time event stream for the dashboard

Protect it. With WithAdminToken, every admin request has to carry Authorization: Bearer <token>, and with WithAdminMiddleware you can put your own auth in front, such as an Authsome session check. With neither, Bastion logs a warning at every start, unless you set WithAllowUnauthenticatedAdmin(true) because something else guards it.

The extension package also registers a contract contributor for the Forge dashboard, whose plugin-bastion package has overview, routes and upstreams pages. MIGRATION.md explains what happened to the old Go-rendered dashboard pages.

Configuration

Bastion reads extensions.bastion, or a top-level bastion key, from your Forge config files. Anything you leave out keeps its default, and options you pass in code win over the file:

extensions:
  bastion:
    enabled: true
    base_path: ""                  # prefix for proxied routes
    routes:
      - path: /users/*
        strip_prefix: true
        enabled: true
        targets:
          - url: http://users:8080
            weight: 1
    load_balancing:
      strategy: leastConnections   # roundRobin, weightedRoundRobin, random, consistentHash
    circuit_breaker:
      enabled: true
      failure_threshold: 5
      reset_timeout: 30s
    retry:
      enabled: true
      max_attempts: 3
    rate_limiting:
      enabled: true
      requests_per_sec: 1000
      burst: 100
      per_client: true
    health_check:
      enabled: true
      interval: 10s
    discovery:
      enabled: true
      prefix_template: "/{{.ServiceName}}"
    dashboard:
      enabled: true                # gates the admin API, the WebSocket hub and the FARP push endpoints
      base_path: /gateway
      admin_token: ""

The defaults have discovery, retries, circuit breakers, health checks, metrics, access logs and the admin API turned on, and rate limiting, caching, auth, CORS, IP filtering and traffic splitting turned off. Every block has a matching option in code: WithTimeouts, WithRetry, WithCircuitBreaker, WithRateLimiting, WithHealthCheck, WithLoadBalancing, WithAuth, WithTLS, WithCaching, WithCORS, WithIPFilter, WithOpenAPI, WithAsyncAPI, WithMetrics, WithTracing, WithAccessLog, WithDashboard and WithConfig for the whole thing.

Tracing is the exception. Bastion's spans follow your Forge app's tracing config, so you turn them on, sample them and export them there. The tracing block and WithTracing are still accepted so existing config parses, but the gateway doesn't read them. The observability docs list every span and metric.

Documentation

If you want to Read
Run a first gateway Getting started, full example
Define routes and upstreams Routes, upstreams, protocols
Tune resilience Load balancing, circuit breakers, health monitoring, rate limiting
Ship gradually Traffic splitting
Secure the edge Authentication, TLS
Use discovery and merged specs Discovery, OpenAPI aggregation
Operate it Admin API, dashboard, hooks

The Go API is on pkg.go.dev. New code should import the subpackages (routing, proxy, resilience, security and so on) directly; the type aliases in the root package are there for older callers.

FAQ

How do I build an API gateway in Go?

Create a Forge app, add gateway.New with a bastion.WithRoute for each upstream, and run it. The quick start is a complete gateway in about thirty lines.

What happened to Forge's gateway extension?

It moved out of Forge and became Bastion. Swap the import from github.com/xraph/forge/extensions/gateway to github.com/xraph/bastion (types and options) plus github.com/xraph/bastion/gateway or github.com/xraph/bastion/extension (the extension itself). The extension registers under the name bastion and reads extensions.bastion from config.

Does Bastion proxy WebSockets and gRPC?

Yes. Set Protocol on the route to ProtocolWebSocket, ProtocolSSE or ProtocolGRPC (unary and streaming). Buffer sizes and ping intervals for WebSockets live under WithWebSocket, and SSE flushing under WithSSE.

How do I do a canary release with Bastion?

Tag the targets on a route (for example stable and canary), turn on traffic splitting with TrafficSplit.Enabled in the config, and give the route a TrafficPolicy of type canary whose rules send a weight, a header or a cookie to the canary tag.

Can I use Bastion without service discovery?

Yes. Set bastion.WithDiscoveryEnabled(false) and define every route yourself, in code, in config or through the admin API.

Contributing

Issues and focused pull requests are welcome on GitHub. Everything runs from the repo root:

GOWORK=off go build ./...
make test          # go test -v ./...
make test-race
make vet
make lint
gofmt -s -w . && goimports -w -local github.com/xraph/bastion .

Format with that goimports line, not make fmt, which groups imports for the wrong module and fails CI's Format job. Tests need nothing beyond Go. make build, make run and make dev point at a cmd/bastion that doesn't exist, so skip them. AGENTS.md explains which packages may import the root, how the extension wires the subsystems, and how releases go out. Commits follow Conventional Commits.

License

MIT. See LICENSE.

Bastion is part of the forgery stack built on Forge, by Rex Raphael and contributors.

Documentation

Index

Constants

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

DI container keys for the gateway extension.

Variables

View Source
var ErrCircuitNotFound = errors.New("bastion: no circuit breaker for target")

ErrCircuitNotFound is returned by ResetCircuit for a target id with no breaker. Breakers are created on a target's first proxied request, so a target that has never served traffic has none.

Functions

func GatewayMiddleware

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

GatewayMiddleware wraps http.Handler with gateway-level middleware.

func IsExtensionPathExcluded

func IsExtensionPathExcluded(upstreamPath string, filter *ExtensionPathFilter) bool

IsExtensionPathExcluded checks whether an upstream path should be excluded based on the given extension path filter.

Filtering logic (in priority order):

  1. If the path starts with any IncludePrefixes entry → include (highest priority).
  2. If the path starts with any ExcludePrefixes entry → exclude.
  3. If any path segment matches a KnownExtensions name that is NOT in AllowedExtensions → exclude.
  4. Otherwise → include (native service path).

This handles both direct mounts (/{ext}/...) and nested mounts (/api/{ext}/v1/...) because it checks ALL path segments, not just the first.

func New

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

New creates the core bastion gateway.

On its own it proxies nothing. The proxy engine, route manager and admin API are built in subpackages that import this one, so they have to be injected (SetProxyHandler and friends) before Start, or no catch-all route is registered. gateway.New does that for you and keeps the store packages out of your build; extension.New does the same and adds grove-backed persistence.

func RewritePath

func RewritePath(path string, route *Route) string

RewritePath returns the path to send upstream for a request on route. It applies the route's rules in this order: StripPrefix removes the route's path prefix, AddPrefix is put in front, and then RewritePath, a "pattern:replacement" regex rule, runs on the result. The rule splits at the first colon, so the pattern can't contain one. An invalid rule leaves the path as it is.

func ValidateConfig

func ValidateConfig(c *Config) error

ValidateConfig validates the gateway configuration and returns all errors found.

func ValidateTLSConfig

func ValidateTLSConfig(config TLSConfig) error

ValidateTLSConfig checks that the TLS configuration is valid. Deprecated: Use security.ValidateTLSConfig directly.

Types

type APIKeyAuthProvider

type APIKeyAuthProvider = security.APIKeyAuthProvider

APIKeyAuthProvider is a backward-compatible alias for security.APIKeyAuthProvider.

func NewAPIKeyAuthProvider

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

NewAPIKeyAuthProvider creates an API key auth provider. Deprecated: Use security.NewAPIKeyAuthProvider directly.

type APIKeyEntry

type APIKeyEntry = security.APIKeyEntry

APIKeyEntry is a backward-compatible alias for security.APIKeyEntry.

type AccessLogConfig

type AccessLogConfig = observability.AccessLogConfig

AccessLogConfig holds access logging settings. The canonical definition lives in the observability subpackage.

type AccessLogWriter

type AccessLogWriter interface {
	Log(r *http.Request, statusCode int, latency time.Duration, route *Route, target *Target)
	LogAdminAction(action, resource, result string, r *http.Request)
}

AccessLogWriter logs HTTP request/response access entries.

type AccessLogger deprecated

type AccessLogger = observability.AccessLogger

AccessLogger is an alias for observability.AccessLogger.

Deprecated: Use observability.AccessLogger directly.

func NewAccessLogger deprecated

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

NewAccessLogger creates a new access logger.

Deprecated: Use observability.NewAccessLogger directly.

type AdminAuthConfig

type AdminAuthConfig = security.AdminAuthConfig

AdminAuthConfig is a backward-compatible alias for security.AdminAuthConfig.

type AdminAuthMiddleware

type AdminAuthMiddleware = security.AdminAuthMiddleware

AdminAuthMiddleware is a backward-compatible alias for security.AdminAuthMiddleware.

func NewAdminAuthMiddleware

func NewAdminAuthMiddleware(config AdminAuthConfig) *AdminAuthMiddleware

NewAdminAuthMiddleware creates a new admin auth middleware. Deprecated: Use security.NewAdminAuthMiddleware directly.

type AsyncAPIAggregator

type AsyncAPIAggregator = disc.AsyncAPIAggregator

AsyncAPIAggregator is a backward-compatible alias for discovery.AsyncAPIAggregator.

func NewAsyncAPIAggregator

func NewAsyncAPIAggregator(config AsyncAPIConfig, logger forge.Logger, sd *ServiceDiscovery) *AsyncAPIAggregator

NewAsyncAPIAggregator creates a new AsyncAPI aggregator.

type AsyncAPIConfig

type AsyncAPIConfig = disc.AsyncAPIConfig

AsyncAPIConfig holds AsyncAPI aggregation settings.

Canonical definition: discovery.AsyncAPIConfig

func DefaultAsyncAPIConfig

func DefaultAsyncAPIConfig() AsyncAPIConfig

DefaultAsyncAPIConfig returns defaults for AsyncAPI aggregation.

type AuditAction

type AuditAction = observability.AuditAction

AuditAction represents the type of admin action taken.

Canonical definition: observability.AuditAction

type AuditConfig

type AuditConfig = observability.AuditConfig

AuditConfig configures audit logging.

Canonical definition: observability.AuditConfig

type AuditEvent

type AuditEvent = observability.AuditEvent

AuditEvent represents an auditable action in the gateway.

Canonical definition: observability.AuditEvent

type AuditLogger deprecated

type AuditLogger = observability.AuditLogger

AuditLogger is an alias for observability.AuditLogger.

Deprecated: Use observability.AuditLogger directly.

func NewAuditLogger deprecated

func NewAuditLogger(config AuditConfig, logger forge.Logger) *AuditLogger

NewAuditLogger creates a new audit logger.

Deprecated: Use observability.NewAuditLogger directly.

type AuditSink

type AuditSink = observability.AuditSink

AuditSink is the interface for consuming audit events.

Canonical definition: observability.AuditSink

type AuthConfig

type AuthConfig = security.AuthConfig

AuthConfig holds gateway-level auth settings.

Canonical definition: security.AuthConfig

type AuthError

type AuthError = security.AuthError

AuthError represents an authentication failure.

Canonical definition: security.AuthError

type AuthProvider

type AuthProvider = security.AuthProvider

AuthProvider is the gateway's interface for authentication providers.

Canonical definition: security.AuthProvider

type AuthRegistry

type AuthRegistry = security.AuthRegistry

AuthRegistry manages authentication providers for the gateway.

Canonical definition: security.AuthRegistry

type Authenticator

type Authenticator interface {
	SetForgeAuth(registry AuthRegistry)
	RegisterProvider(provider AuthProvider)
	Authenticate(r *http.Request, route *Route) (*GatewayAuthContext, error)
	ForwardAuthHeaders(r *http.Request, authCtx *GatewayAuthContext)
}

Authenticator handles gateway-level authentication.

type BackoffStrategy

type BackoffStrategy string

BackoffStrategy defines retry backoff algorithms.

const (
	// BackoffExponential uses exponential backoff.
	BackoffExponential BackoffStrategy = "exponential"

	// BackoffLinear uses linear backoff.
	BackoffLinear BackoffStrategy = "linear"

	// BackoffFixed uses a fixed delay.
	BackoffFixed BackoffStrategy = "fixed"
)

type BasePlugin

type BasePlugin struct {
	PluginName string
}

BasePlugin provides no-op defaults for the GatewayPlugin interface, allowing plugins to override only the methods they care about.

func (*BasePlugin) Name

func (bp *BasePlugin) Name() string

func (*BasePlugin) OnError

func (bp *BasePlugin) OnError(_ error, _ *Route, _ http.ResponseWriter)

func (*BasePlugin) OnRequest

func (bp *BasePlugin) OnRequest(_ *http.Request, _ *Route) error

func (*BasePlugin) OnResponse

func (bp *BasePlugin) OnResponse(_ *http.Response, _ *Route)

type BearerTokenAuthProvider

type BearerTokenAuthProvider = security.BearerTokenAuthProvider

BearerTokenAuthProvider is a backward-compatible alias for security.BearerTokenAuthProvider.

func NewBearerTokenAuthProvider

func NewBearerTokenAuthProvider(name string, validate func(ctx context.Context, token string) (*GatewayAuthContext, error)) *BearerTokenAuthProvider

NewBearerTokenAuthProvider creates a bearer token auth provider with a custom validator. Deprecated: Use security.NewBearerTokenAuthProvider directly.

type Breaker

type Breaker interface {
	Allow() bool
	RecordSuccess()
	RecordFailure()
	// ReleaseProbe returns a half-open probe slot for a request that
	// neither succeeded nor failed.
	ReleaseProbe()
	State() CircuitState
	Reset()
}

Breaker represents a single circuit breaker for an upstream target.

type BufferPoolConfig

type BufferPoolConfig struct {
	MaxRequestBodySize  int `json:"maxRequestBodySize" yaml:"max_request_body_size"`
	MaxResponseBodySize int `json:"maxResponseBodySize" yaml:"max_response_body_size"`
}

BufferPoolConfig holds buffer pool settings.

type CBConfig

type CBConfig struct {
	FailureThreshold int           `json:"failureThreshold"`
	ResetTimeout     time.Duration `json:"resetTimeout"`
	HalfOpenMax      int           `json:"halfOpenMax"`
}

CBConfig is a per-route circuit breaker override.

type CORSConfig

type CORSConfig struct {
	Enabled       bool     `json:"enabled" yaml:"enabled"`
	AllowOrigins  []string `json:"allowOrigins,omitempty" yaml:"allow_origins"`
	AllowMethods  []string `json:"allowMethods,omitempty" yaml:"allow_methods"`
	AllowHeaders  []string `json:"allowHeaders,omitempty" yaml:"allow_headers"`
	ExposeHeaders []string `json:"exposeHeaders,omitempty" yaml:"expose_headers"`
	AllowCreds    bool     `json:"allowCredentials" yaml:"allow_credentials"`
	MaxAge        int      `json:"maxAge" yaml:"max_age"`
}

CORSConfig holds CORS settings.

type CacheStats

type CacheStats = middleware.CacheStats

CacheStats tracks cache hit/miss metrics.

Canonical definition: middleware.CacheStats

type CacheStatsReader

type CacheStatsReader interface {
	Hits() int64
	Misses() int64
}

CacheStatsReader provides read access to cache statistics.

type CacheStore

type CacheStore = middleware.CacheStore

CacheStore is the gateway's interface for a cache backend.

Canonical definition: middleware.CacheStore

type CachedResponse

type CachedResponse = middleware.CachedResponse

CachedResponse represents a cached HTTP response.

Canonical definition: middleware.CachedResponse

type CachingConfig

type CachingConfig = middleware.CachingConfig

CachingConfig holds response caching settings.

Canonical definition: middleware.CachingConfig

type CircuitBreakHook

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

CircuitBreakHook is called when a circuit breaker state changes.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Enabled          bool          `json:"enabled" yaml:"enabled"`
	FailureThreshold int           `json:"failureThreshold" yaml:"failure_threshold"`
	FailureWindow    time.Duration `json:"failureWindow" yaml:"failure_window"`
	ResetTimeout     time.Duration `json:"resetTimeout" yaml:"reset_timeout"`
	HalfOpenMax      int           `json:"halfOpenMax" yaml:"half_open_max"`
}

CircuitBreakerConfig holds circuit breaker settings.

type CircuitBreakerSnapshot

type CircuitBreakerSnapshot struct {
	TargetID        string       `json:"targetId"`
	State           CircuitState `json:"state"`
	FailureCount    int          `json:"failureCount"`
	SuccessCount    int          `json:"successCount"`
	LastFailure     time.Time    `json:"lastFailure"`
	LastStateChange time.Time    `json:"lastStateChange"`
	UpdatedAt       time.Time    `json:"updatedAt"`
}

CircuitBreakerSnapshot is the persistable state of a circuit breaker.

type CircuitBreakerStore

type CircuitBreakerStore interface {
	// GetState returns the persisted state for a target.
	GetState(ctx context.Context, targetID string) (*CircuitBreakerSnapshot, error)

	// SaveState persists the current circuit breaker state for a target.
	SaveState(ctx context.Context, snap *CircuitBreakerSnapshot) error

	// ListStates returns all persisted circuit breaker states.
	ListStates(ctx context.Context) ([]*CircuitBreakerSnapshot, error)

	// DeleteState removes the persisted state for a target.
	DeleteState(ctx context.Context, targetID string) error
}

CircuitBreakerStore persists circuit breaker state snapshots.

type CircuitControl

type CircuitControl interface {
	Get(targetID string) Breaker
	GetWithConfig(targetID string, cfg *CBConfig) Breaker
	Remove(targetID string)
	SetOnStateChange(fn func(targetID string, from, to CircuitState))
	Snapshots() []CircuitBreakerSnapshot
	Reset(targetID string) bool
}

CircuitControl manages circuit breakers across all upstream targets.

type CircuitState

type CircuitState = observability.CircuitState

CircuitState represents the circuit breaker state. The canonical definition lives in the observability subpackage.

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

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

	// CircuitHalfOpen allows limited probe requests.
	CircuitHalfOpen CircuitState = observability.CircuitHalfOpen
)

type CompressionConfig

type CompressionConfig = middleware.CompressionConfig

CompressionConfig configures response compression.

Canonical definition: middleware.CompressionConfig

type CompressionMiddleware

type CompressionMiddleware = middleware.CompressionMiddleware

CompressionMiddleware wraps an http.Handler with gzip compression.

Canonical definition: middleware.CompressionMiddleware

func NewCompressionMiddleware

func NewCompressionMiddleware(config CompressionConfig) *CompressionMiddleware

NewCompressionMiddleware creates a new compression middleware.

type Config

type Config struct {
	// Enabled determines if the gateway is active
	Enabled bool `json:"enabled" yaml:"enabled"`

	// BasePath is the prefix for all proxied routes (e.g., "/gw")
	BasePath string `json:"basePath" yaml:"base_path"`

	// Routes are manually defined upstream routes
	Routes []RouteConfig `json:"routes" yaml:"routes"`

	// Timeouts for upstream connections
	Timeouts TimeoutConfig `json:"timeouts" yaml:"timeouts"`

	// Retry is the global retry policy
	Retry RetryConfig `json:"retry" yaml:"retry"`

	// BufferPool configures request/response buffer sizes
	BufferPool BufferPoolConfig `json:"bufferPool" yaml:"buffer_pool"`

	// CircuitBreaker is the global circuit breaker config
	CircuitBreaker CircuitBreakerConfig `json:"circuitBreaker" yaml:"circuit_breaker"`

	// RateLimiting is the global rate limiting config
	RateLimiting RateLimitConfig `json:"rateLimiting" yaml:"rate_limiting"`

	// HealthCheck configures upstream health checking
	HealthCheck HealthCheckConfig `json:"healthCheck" yaml:"health_check"`

	// LoadBalancing configures the load balancing strategy
	LoadBalancing LoadBalancingConfig `json:"loadBalancing" yaml:"load_balancing"`

	// TrafficSplit configures global traffic splitting
	TrafficSplit TrafficSplitConfig `json:"trafficSplit" yaml:"traffic_split"`

	// Auth configures gateway-level authentication
	Auth AuthConfig `json:"auth" yaml:"auth"`

	// TLS configures upstream TLS/mTLS
	TLS TLSConfig `json:"tls" yaml:"tls"`

	// IPFilter configures IP allow/deny lists
	IPFilter IPFilterConfig `json:"ipFilter" yaml:"ip_filter"`

	// CORS configures gateway-level CORS
	CORS CORSConfig `json:"cors" yaml:"cors"`

	// Caching configures response caching
	Caching CachingConfig `json:"caching" yaml:"caching"`

	// Discovery configures FARP-based auto-discovery
	Discovery DiscoveryConfig `json:"discovery" yaml:"discovery"`

	// Metrics configures Prometheus metrics
	Metrics MetricsConfig `json:"metrics" yaml:"metrics"`

	// Tracing is accepted but not read. Bastion's spans follow the Forge
	// app's tracing config; the field stays so existing config parses.
	Tracing TracingConfig `json:"tracing" yaml:"tracing"`

	// AccessLog configures structured access logging
	AccessLog AccessLogConfig `json:"accessLog" yaml:"access_log"`

	// OpenAPI configures the aggregated OpenAPI spec from all upstream services
	OpenAPI OpenAPIConfig `json:"openapi" yaml:"openapi"`

	// AsyncAPI configures the aggregated AsyncAPI spec from all upstream services
	AsyncAPI AsyncAPIConfig `json:"asyncapi" yaml:"asyncapi"`

	// Dashboard configures the admin UI
	Dashboard DashboardConfig `json:"dashboard" yaml:"dashboard"`

	// WebSocket configures WebSocket proxy settings
	WebSocket WebSocketConfig `json:"webSocket" yaml:"web_socket"`

	// SSE configures SSE proxy settings
	SSE SSEConfig `json:"sse" yaml:"sse"`
}

Config holds the complete gateway configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default gateway configuration.

func FromOctopusConfig

func FromOctopusConfig(oc OctopusConfig) Config

FromOctopusConfig converts an octopus-format config to bastion's native Config.

type ConfigOption

type ConfigOption func(*Config)

ConfigOption configures the gateway extension.

func WithAccessLog

func WithAccessLog(al AccessLogConfig) ConfigOption

WithAccessLog sets the access log configuration.

func WithAdminMiddleware

func WithAdminMiddleware(mw ...forge.Middleware) ConfigOption

WithAdminMiddleware adds middleware in front of every admin API handler, for auth that a static token can't express. Calls accumulate. See DashboardConfig.AdminMiddleware.

func WithAdminToken

func WithAdminToken(token string) ConfigOption

WithAdminToken requires "Authorization: Bearer <token>" on every admin API request. See DashboardConfig.AdminToken.

func WithAllowUnauthenticatedAdmin

func WithAllowUnauthenticatedAdmin(allow bool) ConfigOption

WithAllowUnauthenticatedAdmin acknowledges that the admin API runs with no authentication of its own. See DashboardConfig.AllowUnauthenticatedAdmin.

func WithAsyncAPI

func WithAsyncAPI(a AsyncAPIConfig) ConfigOption

WithAsyncAPI sets the AsyncAPI aggregation configuration.

func WithAsyncAPIEnabled

func WithAsyncAPIEnabled(enabled bool) ConfigOption

WithAsyncAPIEnabled enables/disables AsyncAPI aggregation.

func 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 WithDiscoveryAutoPrefix

func WithDiscoveryAutoPrefix(enabled bool) ConfigOption

WithDiscoveryAutoPrefix sets whether discovered services get automatic path prefixes.

func WithDiscoveryEnabled

func WithDiscoveryEnabled(enabled bool) ConfigOption

WithDiscoveryEnabled enables/disables FARP discovery.

func WithDiscoveryPollInterval

func WithDiscoveryPollInterval(d time.Duration) ConfigOption

WithDiscoveryPollInterval sets the service discovery polling interval.

func WithDiscoveryPrefixOverrides

func WithDiscoveryPrefixOverrides(overrides map[string]string) ConfigOption

WithDiscoveryPrefixOverrides sets per-service route prefix overrides. An empty string value mounts the service at root (no prefix).

Example: WithDiscoveryPrefixOverrides(map[string]string{"twinos": ""}) mounts "twinos" at / instead of /twinos.

func WithDiscoveryPrefixTemplate

func WithDiscoveryPrefixTemplate(tmpl string) ConfigOption

WithDiscoveryPrefixTemplate sets the template for auto-generated route prefixes.

func WithDiscoveryPushInstanceTTL

func WithDiscoveryPushInstanceTTL(ttl time.Duration) ConfigOption

WithDiscoveryPushInstanceTTL sets the TTL for push-registered service instances. Instances that do not re-register within this duration are automatically evicted. Set to 0 to disable TTL (default).

func WithDiscoveryServiceFilters

func WithDiscoveryServiceFilters(filters ...ServiceFilter) ConfigOption

WithDiscoveryServiceFilters sets the service filters for discovery.

func WithDiscoveryStripPrefix

func WithDiscoveryStripPrefix(strip bool) ConfigOption

WithDiscoveryStripPrefix sets whether auto-generated prefixes are stripped before proxying.

func WithDiscoveryWatchMode

func WithDiscoveryWatchMode(enabled bool) ConfigOption

WithDiscoveryWatchMode sets whether discovery uses watch mode instead of polling.

func WithEnabled

func WithEnabled(enabled bool) ConfigOption

WithEnabled sets whether the gateway is enabled.

func WithExtensionFilter

func WithExtensionFilter(filter ExtensionPathFilter) ConfigOption

WithExtensionFilter adds an extension path filter for a specific service. Extension paths matching knownExtensions but not in allowedExtensions will be excluded from the OpenAPI spec and optionally blocked at the proxy level.

func WithHealthCheck

func WithHealthCheck(hc HealthCheckConfig) ConfigOption

WithHealthCheck sets the health check configuration.

func WithIPFilter

func WithIPFilter(ipf IPFilterConfig) ConfigOption

WithIPFilter sets the IP filter configuration.

func WithLoadBalancing

func WithLoadBalancing(lb LoadBalancingConfig) ConfigOption

WithLoadBalancing sets the load balancing strategy.

func WithMetrics

func WithMetrics(m MetricsConfig) ConfigOption

WithMetrics sets the metrics configuration.

func WithOctopusConfig

func WithOctopusConfig(oc OctopusConfig) ConfigOption

WithOctopusConfig applies an octopus-format config to the gateway.

func WithOctopusConfigFile

func WithOctopusConfigFile(path string) ConfigOption

WithOctopusConfigFile loads and applies an octopus-format YAML config file.

func WithOpenAPI

func WithOpenAPI(o OpenAPIConfig) ConfigOption

WithOpenAPI sets the OpenAPI aggregation configuration.

func WithOpenAPIDisableServiceTags

func WithOpenAPIDisableServiceTags(disabled bool) ConfigOption

WithOpenAPIDisableServiceTags disables automatic per-service tag creation and per-operation tag injection in the merged OpenAPI spec.

func WithOpenAPIEnabled

func WithOpenAPIEnabled(enabled bool) ConfigOption

WithOpenAPIEnabled enables/disables OpenAPI aggregation.

func WithOpenAPIGatewayDocs

func WithOpenAPIGatewayDocs(enabled bool) ConfigOption

WithOpenAPIGatewayDocs enables serving the gateway's own admin API documentation at the dashboard-prefixed swagger path (e.g., /gateway/swagger). Disabled by default.

func WithOpenAPIRootDocs

func WithOpenAPIRootDocs(enabled bool) ConfigOption

WithOpenAPIRootDocs enables serving the aggregated OpenAPI spec and Swagger UI at root-level paths (/openapi.json and /docs) in addition to the dashboard-prefixed paths.

func WithOpenAPIServiceTagOnly

func WithOpenAPIServiceTagOnly(enabled bool) ConfigOption

WithOpenAPIServiceTagOnly replaces all upstream operation tags with just the service-name tag. Ignored when DisableServiceTags is true.

func WithRateLimiting

func WithRateLimiting(rl RateLimitConfig) ConfigOption

WithRateLimiting sets the rate limiting configuration.

func WithRetry

func WithRetry(retry RetryConfig) ConfigOption

WithRetry sets the retry configuration.

func WithRoute

func WithRoute(route RouteConfig) ConfigOption

WithRoute adds a manual route configuration.

func WithRoutes

func WithRoutes(routes []RouteConfig) ConfigOption

WithRoutes sets all manual route configurations.

func WithSSE

func WithSSE(sse SSEConfig) ConfigOption

WithSSE sets the SSE proxy configuration.

func WithServiceRoute

func WithServiceRoute(serviceName, path, targetURL, openapiSpecURL string) ConfigOption

WithServiceRoute adds a manual route associated with a named service and its OpenAPI specification URL. The service's spec will be included in the gateway's aggregated API documentation at /docs.

func 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 Config.Tracing, which the gateway doesn't read. Configure tracing on the Forge app instead. The option is kept so existing code still compiles.

func WithWebSocket

func WithWebSocket(ws WebSocketConfig) ConfigOption

WithWebSocket sets the WebSocket proxy configuration.

type ConfigWatcher

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

ConfigWatcher monitors a config file and triggers a callback when the file changes. It uses polling rather than OS-specific file watchers for portability.

func NewConfigWatcher

func NewConfigWatcher(path string, interval time.Duration, onChange func(Config)) *ConfigWatcher

NewConfigWatcher creates a config file watcher.

func (*ConfigWatcher) SetErrorHandler

func (cw *ConfigWatcher) SetErrorHandler(fn func(error))

SetErrorHandler sets a callback for errors during config reload.

func (*ConfigWatcher) Start

func (cw *ConfigWatcher) Start()

Start begins polling the config file for changes.

func (*ConfigWatcher) Stop

func (cw *ConfigWatcher) Stop()

Stop ends the polling loop and waits for it to finish.

type DashboardConfig

type DashboardConfig struct {
	// Enabled gates the admin REST API, the WebSocket hub, and the
	// OpenAPI/AsyncAPI endpoints.
	Enabled bool `json:"enabled" yaml:"enabled"`
	// BasePath prefixes the admin REST API, the WebSocket hub, and the
	// OpenAPI/AsyncAPI endpoints.
	BasePath string `json:"basePath" yaml:"base_path"`
	// Title is unused. It is kept so existing configuration still parses.
	Title string `json:"title,omitempty" yaml:"title"`
	// Realtime gates the WebSocket hub.
	Realtime bool `json:"realtime" yaml:"realtime"`

	// AdminToken, when set, is the bearer token every admin API request
	// has to carry ("Authorization: Bearer <token>"). It covers the REST
	// API under BasePath+"/api" and the WebSocket hub. It is never written
	// out as JSON, so the admin config endpoint doesn't hand it back.
	AdminToken string `json:"-" yaml:"admin_token"`
	// AdminMiddleware runs in front of every admin API handler, after the
	// AdminToken check. Use it to plug in your own auth: a session check,
	// an mTLS identity, an authsome guard. Set it with WithAdminMiddleware.
	AdminMiddleware []forge.Middleware `json:"-" yaml:"-"`
	// AllowUnauthenticatedAdmin says you mean to serve the admin API with
	// neither AdminToken nor AdminMiddleware, say behind a private network
	// or an authenticating proxy. Without it the gateway logs a warning at
	// start every time it registers an open admin API.
	AllowUnauthenticatedAdmin bool `json:"allowUnauthenticatedAdmin" yaml:"allow_unauthenticated_admin"`
}

DashboardConfig holds admin surface settings. The Go-rendered dashboard has been retired; the React plugin reads the bastion contract contributor.

func (DashboardConfig) AdminAuthenticated

func (d DashboardConfig) AdminAuthenticated() bool

AdminAuthenticated reports whether the admin API has any authentication configured: an AdminToken, AdminMiddleware, or both.

type DiscoveredService

type DiscoveredService = disc.DiscoveredService

DiscoveredService represents a service found via FARP/discovery.

Canonical definition: discovery.DiscoveredService

type DiscoveryConfig

type DiscoveryConfig = disc.DiscoveryConfig

DiscoveryConfig holds FARP auto-discovery settings.

Canonical definition: discovery.DiscoveryConfig

type DiscoveryService

type DiscoveryService interface {
	// ListServices lists all registered service names.
	ListServices(ctx context.Context) ([]string, error)

	// DiscoverHealthy returns healthy instances for a service.
	DiscoverHealthy(ctx context.Context, serviceName string) ([]*ServiceInstanceInfo, error)
}

DiscoveryService is the interface that the gateway requires from a discovery provider. This decouples the gateway from the concrete discovery.Service type.

type DistributedRateLimiter

type DistributedRateLimiter = middleware.DistributedRateLimiter

DistributedRateLimiter extends the basic RateLimiter with an external store for multi-instance rate limiting.

Canonical definition: middleware.DistributedRateLimiter

func NewDistributedRateLimiter

func NewDistributedRateLimiter(config RateLimitConfig, store RateLimitStore) *DistributedRateLimiter

NewDistributedRateLimiter creates a rate limiter backed by an external store.

type ErrorHook

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

ErrorHook is called when an upstream error occurs.

type ExtensionPathFilter

type ExtensionPathFilter = disc.ExtensionPathFilter

ExtensionPathFilter defines per-service extension path filtering.

Canonical definition: discovery.ExtensionPathFilter

type ForwardAuthProvider

type ForwardAuthProvider = security.ForwardAuthProvider

ForwardAuthProvider is a backward-compatible alias for security.ForwardAuthProvider.

func NewForwardAuthProvider

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

NewForwardAuthProvider creates a forward auth provider. Deprecated: Use security.NewForwardAuthProvider directly.

type Gateway

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

Gateway implements the Bastion API gateway.

func (*Gateway) AccessLog

func (e *Gateway) AccessLog() *AccessLogger

AccessLog returns the access logger.

func (*Gateway) App

func (e *Gateway) App() forge.App

App returns the Forge app instance.

func (*Gateway) AsyncAPI

func (e *Gateway) AsyncAPI() *AsyncAPIAggregator

AsyncAPI returns the AsyncAPI aggregator.

func (*Gateway) Auth

func (e *Gateway) Auth() *GatewayAuth

Auth returns the gateway auth handler.

func (*Gateway) Cache

func (e *Gateway) Cache() *ResponseCache

Cache returns the response cache.

func (*Gateway) Circuits

func (e *Gateway) Circuits() []CircuitBreakerSnapshot

Circuits returns a snapshot of every circuit breaker, sorted by target id. It is nil when circuit control is not wired.

func (*Gateway) Config

func (e *Gateway) Config() Config

Config returns the gateway configuration.

func (*Gateway) Dependencies

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

Dependencies returns extension dependencies.

func (*Gateway) Discovery

func (e *Gateway) Discovery() *ServiceDiscovery

Discovery returns the service discovery integration.

func (*Gateway) GatewayMetrics

func (e *Gateway) GatewayMetrics() *GatewayMetrics

GatewayMetrics returns the gateway's metrics, recorded through the Forge app's metrics. It is nil before Register and when metrics are disabled, and a nil value records nothing.

func (*Gateway) Health

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

Health checks if the gateway is healthy.

func (*Gateway) HealthMonitor

func (e *Gateway) HealthMonitor() *health.Monitor

HealthMonitor returns the health monitor.

func (*Gateway) Hooks

func (e *Gateway) Hooks() *HookEngine

Hooks returns the hook engine.

func (*Gateway) Hub

func (e *Gateway) Hub() WSBroadcaster

Hub returns the WebSocket hub for real-time updates.

func (*Gateway) OpenAPI

func (e *Gateway) OpenAPI() *OpenAPIAggregator

OpenAPI returns the OpenAPI aggregator.

func (*Gateway) RateLimiter

func (e *Gateway) RateLimiter() *RateLimiter

RateLimiter returns the rate limiter.

func (*Gateway) Register

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

Register registers the bastion gateway.

func (*Gateway) ResetCircuit

func (e *Gateway) ResetCircuit(targetID string) error

ResetCircuit closes the breaker for targetID.

func (*Gateway) RouteManager

func (e *Gateway) RouteManager() RouteRegistry

RouteManager returns the route registry.

func (*Gateway) RoutesPersisted

func (e *Gateway) RoutesPersisted() bool

RoutesPersisted reports whether a route store is wired, so a route created through the admin API survives a restart.

func (*Gateway) SetAdminHandlerSetup

func (e *Gateway) SetAdminHandlerSetup(fn func(gw *Gateway, router forge.Router))

SetAdminHandlerSetup sets the callback for registering admin dashboard routes.

func (*Gateway) SetCacheStore

func (e *Gateway) SetCacheStore(store CacheStore)

SetCacheStore sets an external cache store for response caching.

func (*Gateway) SetCircuitControl

func (e *Gateway) SetCircuitControl(cb CircuitControl)

SetCircuitControl sets the circuit breaker manager.

func (*Gateway) SetDiscoveryService

func (e *Gateway) SetDiscoveryService(svc DiscoveryService)

SetDiscoveryService sets the discovery service adapter and initializes the ServiceDiscovery integration. This is called by the extension adapter to inject the concrete discovery.Service dependency.

func (*Gateway) SetProxyHandler

func (e *Gateway) SetProxyHandler(h http.Handler)

SetProxyHandler sets the HTTP handler for proxying.

func (*Gateway) SetRetryPolicy

func (e *Gateway) SetRetryPolicy(r RetryPolicy)

SetRetryPolicy sets the retry executor.

func (*Gateway) SetRouteRegistry

func (e *Gateway) SetRouteRegistry(rm RouteRegistry)

SetRouteRegistry sets the route manager implementation.

func (*Gateway) SetStatsRecorder

func (e *Gateway) SetStatsRecorder(s StatsRecorder)

SetStatsRecorder sets the stats collector.

func (*Gateway) SetStore

func (e *Gateway) SetStore(s any)

SetStore sets a composite store that provides persistence for all gateway subsystems (routes, circuit breakers, health checks, cache, rate limits, audit). The store is decomposed into subsystem-specific interfaces.

func (*Gateway) SetTrafficRouter

func (e *Gateway) SetTrafficRouter(t TrafficRouter)

SetTrafficRouter sets the traffic splitter.

func (*Gateway) SetWSBroadcaster

func (e *Gateway) SetWSBroadcaster(h WSBroadcaster)

SetWSBroadcaster sets the WebSocket hub for dashboard.

func (*Gateway) Snapshot

func (e *Gateway) Snapshot() *GatewayStats

Snapshot returns current gateway statistics. Uptime counts from the moment Start completed and is zero before it. Cache counters come from the response cache, so they count real lookups only.

func (*Gateway) Start

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

Start starts the bastion gateway. It is idempotent — calling Start() multiple times (e.g. when forge re-starts extensions after middleware application) is safe and only performs initialization once.

func (*Gateway) Stats

func (e *Gateway) Stats() StatsRecorder

Stats returns the stats recorder.

func (*Gateway) Stop

func (e *Gateway) Stop(ctx context.Context) error

Stop stops the bastion gateway.

func (*Gateway) TLS

func (e *Gateway) TLS() *TLSManager

TLS returns the TLS manager.

type GatewayAuth

type GatewayAuth = security.Auth

GatewayAuth is a backward-compatible alias for security.Auth.

func NewGatewayAuth

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

NewGatewayAuth creates a new gateway auth handler. Deprecated: Use security.NewAuth directly.

type GatewayAuthContext

type GatewayAuthContext = security.AuthContext

GatewayAuthContext holds authenticated subject information for gateway requests.

Canonical definition: security.AuthContext

type GatewayMetrics deprecated

type GatewayMetrics = observability.Metrics

GatewayMetrics is an alias for observability.Metrics.

Deprecated: Use observability.Metrics directly.

func NewGatewayMetrics deprecated

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

NewGatewayMetrics creates a new gateway metrics collector.

Deprecated: Use observability.NewMetrics directly.

type GatewayPlugin

type GatewayPlugin interface {
	// Name returns a unique identifier for the plugin.
	Name() string

	// OnRequest is called before a request is forwarded to the upstream.
	// Return a non-nil error to reject the request (short-circuits the pipeline).
	OnRequest(r *http.Request, route *Route) error

	// OnResponse is called after the upstream response is received.
	OnResponse(resp *http.Response, route *Route)

	// OnError is called when the upstream returns an error.
	OnError(err error, route *Route, w http.ResponseWriter)
}

GatewayPlugin is a composable extension point for the gateway. Plugins are invoked in registration order at the request, response, and error stages of the proxy pipeline.

type GatewayStats

type GatewayStats struct {
	TotalRequests  int64 `json:"totalRequests"`
	TotalErrors    int64 `json:"totalErrors"`
	ActiveConns    int64 `json:"activeConns"`
	ActiveWSConns  int64 `json:"activeWsConns"`
	ActiveSSEConns int64 `json:"activeSseConns"`
	// AvgLatencyMs is the mean over every answered upstream request since start.
	AvgLatencyMs float64 `json:"avgLatencyMs"`
	// P99LatencyMs is the nearest-rank p99 over the most recent LatencySamples responses.
	P99LatencyMs float64 `json:"p99LatencyMs"`
	// LatencySamples is how many recent responses P99LatencyMs covers.
	LatencySamples int     `json:"latencySamples"`
	RequestsPerSec float64 `json:"requestsPerSec"`
	CacheHits      int64   `json:"cacheHits"`
	CacheMisses    int64   `json:"cacheMisses"`
	RateLimited    int64   `json:"rateLimited"`
	CircuitBreaks  int64   `json:"circuitBreaks"`
	RetryAttempts  int64   `json:"retryAttempts"`
	// RetryBudgetExhausted counts retries the retry budget refused.
	RetryBudgetExhausted int64                  `json:"retryBudgetExhausted"`
	TotalRoutes          int                    `json:"totalRoutes"`
	HealthyUpstreams     int                    `json:"healthyUpstreams"`
	TotalUpstreams       int                    `json:"totalUpstreams"`
	RouteStats           map[string]*RouteStats `json:"routeStats,omitempty"`
	Uptime               int64                  `json:"uptime"`
	StartedAt            time.Time              `json:"startedAt"`
}

GatewayStats holds aggregated gateway traffic statistics.

type HeaderPolicy

type HeaderPolicy struct {
	Add    map[string]string `json:"add,omitempty"`
	Set    map[string]string `json:"set,omitempty"`
	Remove []string          `json:"remove,omitempty"`
}

HeaderPolicy defines header manipulation rules.

type HealthCheckConfig

type HealthCheckConfig = health.Config

HealthCheckConfig holds health check settings. This is a backward-compatible alias for health.Config.

type HealthCheckResult

type HealthCheckResult = health.CheckResult

HealthCheckResult records a single health check outcome.

Canonical definition: health.CheckResult

type HealthChecker

type HealthChecker interface {
	Register(routeID string, target *Target)
	Deregister(targetID string)
	RecordPassiveFailure(targetID string)
	RecordPassiveSuccess(targetID string)
	Start(ctx context.Context)
	Stop()
	Health(ctx context.Context) error
	SetOnHealthChange(fn func(event UpstreamHealthEvent))
}

HealthChecker manages health monitoring for upstream targets.

type HealthHistory

type HealthHistory = health.History

HealthHistory is a backward-compatible alias for health.History.

func NewHealthHistory

func NewHealthHistory(capacity int) *HealthHistory

NewHealthHistory creates a new HealthHistory. Deprecated: Use health.NewHistory directly.

type HealthMonitor

type HealthMonitor = health.Monitor

HealthMonitor is a backward-compatible alias for health.Monitor.

func NewHealthMonitor

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

NewHealthMonitor creates a new HealthMonitor. Deprecated: Use health.NewMonitor directly.

type HealthStore

type HealthStore interface {
	// RecordCheck persists a single health check result.
	RecordCheck(ctx context.Context, result *HealthCheckResult) error

	// GetHistory returns recent health check results for a target, newest first.
	GetHistory(ctx context.Context, targetID string, limit int) ([]HealthCheckResult, error)

	// GetLatestState returns the most recent health check for a target.
	GetLatestState(ctx context.Context, targetID string) (*HealthCheckResult, error)
}

HealthStore persists health check results for upstream targets.

type HealthSummary

type HealthSummary = health.Summary

HealthSummary provides a summary of health check history for a target.

Canonical definition: health.Summary

type HookEngine

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

HookEngine manages gateway hooks.

func 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 IPFilterConfig

type IPFilterConfig struct {
	Enabled  bool     `json:"enabled" yaml:"enabled"`
	AllowIPs []string `json:"allowIps,omitempty" yaml:"allow_ips"`
	DenyIPs  []string `json:"denyIps,omitempty" yaml:"deny_ips"`
}

IPFilterConfig holds IP allow/deny list settings.

type InMemoryCacheStore

type InMemoryCacheStore = middleware.InMemoryCacheStore

InMemoryCacheStore provides a simple in-memory LRU cache for the gateway.

Canonical definition: middleware.InMemoryCacheStore

func NewInMemoryCacheStore

func NewInMemoryCacheStore(maxSize int) *InMemoryCacheStore

NewInMemoryCacheStore creates a new in-memory cache store.

type InMemoryRateLimitStore

type InMemoryRateLimitStore = middleware.InMemoryRateLimitStore

InMemoryRateLimitStore is a local implementation of RateLimitStore.

Canonical definition: middleware.InMemoryRateLimitStore

func NewInMemoryRateLimitStore

func NewInMemoryRateLimitStore() *InMemoryRateLimitStore

NewInMemoryRateLimitStore creates a new in-memory rate limit store.

type JWTAuthConfig

type JWTAuthConfig = security.JWTAuthConfig

JWTAuthConfig is a backward-compatible alias for security.JWTAuthConfig.

type JWTAuthProvider

type JWTAuthProvider = security.JWTAuthProvider

JWTAuthProvider is a backward-compatible alias for security.JWTAuthProvider.

func NewJWTAuthProvider

func NewJWTAuthProvider(config JWTAuthConfig) *JWTAuthProvider

NewJWTAuthProvider creates a JWT auth provider. Deprecated: Use security.NewJWTAuthProvider directly.

type LoadBalanceStrategy

type LoadBalanceStrategy string

LoadBalanceStrategy defines load balancing algorithms.

const (
	// LBRoundRobin selects targets in round-robin order.
	LBRoundRobin LoadBalanceStrategy = "roundRobin"

	// LBWeightedRoundRobin selects targets using smooth weighted round-robin.
	LBWeightedRoundRobin LoadBalanceStrategy = "weightedRoundRobin"

	// LBRandom selects a random target.
	LBRandom LoadBalanceStrategy = "random"

	// LBLeastConnections selects the target with fewest active connections.
	LBLeastConnections LoadBalanceStrategy = "leastConnections"

	// LBConsistentHash uses consistent hashing for sticky routing.
	LBConsistentHash LoadBalanceStrategy = "consistentHash"
)

type LoadBalancer

type LoadBalancer interface {
	// Select picks a target from the provided list.
	// The key is used for consistent hashing (may be empty for other strategies).
	Select(targets []*Target, key string) *Target
}

LoadBalancer selects a target from a list of healthy targets.

type LoadBalancingConfig

type LoadBalancingConfig struct {
	Strategy      LoadBalanceStrategy `json:"strategy" yaml:"strategy"`
	ConsistentKey string              `json:"consistentKey,omitempty" yaml:"consistent_key"`
}

LoadBalancingConfig holds load balancing settings.

type LogAuditSink deprecated

type LogAuditSink = observability.LogAuditSink

LogAuditSink is an alias for observability.LogAuditSink.

Deprecated: Use observability.LogAuditSink directly.

func NewLogAuditSink deprecated

func NewLogAuditSink(logger forge.Logger) *LogAuditSink

NewLogAuditSink creates a sink that writes audit events to a forge.Logger.

Deprecated: Use observability.NewLogAuditSink directly.

type MetricsConfig

type MetricsConfig = observability.MetricsConfig

MetricsConfig holds metrics settings. The canonical definition lives in the observability subpackage.

type OctopusAPIKeyEntry

type OctopusAPIKeyEntry struct {
	Key       string   `yaml:"key" json:"key"`
	Name      string   `yaml:"name" json:"name"`
	Scopes    []string `yaml:"scopes" json:"scopes"`
	RateLimit *int     `yaml:"rate_limit,omitempty" json:"rate_limit,omitempty"`
}

OctopusAPIKeyEntry mirrors octopus API key entries.

type OctopusAdminConfig

type OctopusAdminConfig struct {
	AuthProvider string   `yaml:"auth_provider" json:"auth_provider"`
	AllowedIPs   []string `yaml:"allowed_ips" json:"allowed_ips"`
}

OctopusAdminConfig mirrors octopus admin settings.

type OctopusAuthConfig

type OctopusAuthConfig struct {
	DefaultProvider string   `yaml:"default_provider" json:"default_provider"`
	GlobalEnforce   bool     `yaml:"global_enforce" json:"global_enforce"`
	SkipPaths       []string `yaml:"skip_paths" json:"skip_paths"`
	PrincipalHeader string   `yaml:"principal_header" json:"principal_header"`
	RolesHeader     string   `yaml:"roles_header" json:"roles_header"`
	ScopesHeader    string   `yaml:"scopes_header" json:"scopes_header"`
	TokenCacheTTL   string   `yaml:"token_cache_ttl" json:"token_cache_ttl"`
	ErrorFormat     string   `yaml:"error_format" json:"error_format"`
}

OctopusAuthConfig mirrors octopus global auth settings.

type OctopusAuthProviderConfig

type OctopusAuthProviderConfig struct {
	Type string `yaml:"type" json:"type"`

	// JWT fields
	Secret        string `yaml:"secret,omitempty" json:"secret,omitempty"`
	PublicKey     string `yaml:"public_key,omitempty" json:"public_key,omitempty"`
	PublicKeyFile string `yaml:"public_key_file,omitempty" json:"public_key_file,omitempty"`
	Algorithm     string `yaml:"algorithm,omitempty" json:"algorithm,omitempty"`
	Issuer        string `yaml:"issuer,omitempty" json:"issuer,omitempty"`
	Audience      string `yaml:"audience,omitempty" json:"audience,omitempty"`
	HeaderName    string `yaml:"header_name,omitempty" json:"header_name,omitempty"`
	TokenPrefix   string `yaml:"token_prefix,omitempty" json:"token_prefix,omitempty"`

	// OIDC fields
	IssuerURL           string   `yaml:"issuer_url,omitempty" json:"issuer_url,omitempty"`
	JWKSRefreshInterval string   `yaml:"jwks_refresh_interval,omitempty" json:"jwks_refresh_interval,omitempty"`
	RequiredScopes      []string `yaml:"required_scopes,omitempty" json:"required_scopes,omitempty"`
	FallbackProvider    string   `yaml:"fallback_provider,omitempty" json:"fallback_provider,omitempty"`

	// API Key fields
	QueryParam        string               `yaml:"query_param,omitempty" json:"query_param,omitempty"`
	Keys              []OctopusAPIKeyEntry `yaml:"keys,omitempty" json:"keys,omitempty"`
	ExternalValidator string               `yaml:"external_validator,omitempty" json:"external_validator,omitempty"`

	// Forward Auth fields
	Endpoint        string   `yaml:"endpoint,omitempty" json:"endpoint,omitempty"`
	ForwardHeaders  []string `yaml:"forward_headers,omitempty" json:"forward_headers,omitempty"`
	ResponseHeaders []string `yaml:"response_headers,omitempty" json:"response_headers,omitempty"`
	CacheTTL        string   `yaml:"cache_ttl,omitempty" json:"cache_ttl,omitempty"`

	// mTLS fields
	ClientCAFile         string              `yaml:"client_ca_file,omitempty" json:"client_ca_file,omitempty"`
	RequireClientCert    bool                `yaml:"require_client_cert,omitempty" json:"require_client_cert,omitempty"`
	ExtractCNAsPrincipal bool                `yaml:"extract_cn_as_principal,omitempty" json:"extract_cn_as_principal,omitempty"`
	CNToRoles            map[string][]string `yaml:"cn_to_roles,omitempty" json:"cn_to_roles,omitempty"`

	// Timeout (shared by forward_auth)
	Timeout string `yaml:"timeout,omitempty" json:"timeout,omitempty"`
}

OctopusAuthProviderConfig mirrors octopus auth provider (tagged enum).

type OctopusCBConfig

type OctopusCBConfig struct {
	ErrorThreshold float32 `yaml:"error_threshold" json:"error_threshold"`
	MinRequests    int     `yaml:"min_requests" json:"min_requests"`
	Timeout        string  `yaml:"timeout" json:"timeout"`
}

OctopusCBConfig mirrors octopus circuit breaker settings.

type OctopusCORSConfig

type OctopusCORSConfig struct {
	AllowedOrigins   []string `yaml:"allowed_origins" json:"allowed_origins"`
	AllowedMethods   []string `yaml:"allowed_methods" json:"allowed_methods"`
	AllowedHeaders   []string `yaml:"allowed_headers" json:"allowed_headers"`
	ExposedHeaders   []string `yaml:"exposed_headers" json:"exposed_headers"`
	MaxAge           int      `yaml:"max_age" json:"max_age"`
	AllowCredentials bool     `yaml:"allow_credentials" json:"allow_credentials"`
}

OctopusCORSConfig mirrors octopus global CORS settings.

type OctopusCompressionConfig

type OctopusCompressionConfig struct {
	Enabled    bool     `yaml:"enabled" json:"enabled"`
	Level      int      `yaml:"level" json:"level"`
	MinSize    int      `yaml:"min_size" json:"min_size"`
	Algorithms []string `yaml:"algorithms" json:"algorithms"`
}

OctopusCompressionConfig mirrors octopus compression settings.

type OctopusConfig

type OctopusConfig struct {
	Gateway       OctopusGatewayConfig                 `yaml:"gateway" json:"gateway"`
	Upstreams     []OctopusUpstreamConfig              `yaml:"upstreams" json:"upstreams"`
	Routes        []OctopusRouteConfig                 `yaml:"routes" json:"routes"`
	Plugins       []OctopusPluginConfig                `yaml:"plugins" json:"plugins"`
	FARP          OctopusFARPConfig                    `yaml:"farp" json:"farp"`
	Observability OctopusObservabilityConfig           `yaml:"observability" json:"observability"`
	AuthProviders map[string]OctopusAuthProviderConfig `yaml:"auth_providers" json:"auth_providers"`
	Auth          OctopusAuthConfig                    `yaml:"auth" json:"auth"`
	CORS          *OctopusCORSConfig                   `yaml:"cors" json:"cors"`
	Admin         OctopusAdminConfig                   `yaml:"admin" json:"admin"`
	GRPC          OctopusGRPCConfig                    `yaml:"grpc" json:"grpc"`
}

OctopusConfig mirrors the octopus gateway YAML configuration format. Use FromOctopusConfig to convert to bastion's native Config type.

func LoadOctopusConfig

func LoadOctopusConfig(path string) (OctopusConfig, error)

LoadOctopusConfig reads and parses an octopus-format YAML config file.

type OctopusDiscoveryBackend

type OctopusDiscoveryBackend struct {
	Type    string         `yaml:"type" json:"type"`
	Enabled bool           `yaml:"enabled" json:"enabled"`
	Config  map[string]any `yaml:"config" json:"config"`
}

OctopusDiscoveryBackend mirrors an octopus discovery backend entry.

type OctopusFARPConfig

type OctopusFARPConfig struct {
	Enabled        bool                        `yaml:"enabled" json:"enabled"`
	WatchInterval  string                      `yaml:"watch_interval" json:"watch_interval"`
	SchemaCacheTTL string                      `yaml:"schema_cache_ttl" json:"schema_cache_ttl"`
	Discovery      *OctopusFARPDiscoveryConfig `yaml:"discovery" json:"discovery"`
}

OctopusFARPConfig mirrors octopus FARP settings.

type OctopusFARPDiscoveryConfig

type OctopusFARPDiscoveryConfig struct {
	Backends []OctopusDiscoveryBackend `yaml:"backends" json:"backends"`
}

OctopusFARPDiscoveryConfig mirrors octopus FARP discovery backend settings.

type OctopusGRPCConfig

type OctopusGRPCConfig struct {
	Enabled             bool              `yaml:"enabled" json:"enabled"`
	MaxMessageSize      int               `yaml:"max_message_size" json:"max_message_size"`
	EnableReflection    bool              `yaml:"enable_reflection" json:"enable_reflection"`
	EnableGRPCWeb       bool              `yaml:"enable_grpc_web" json:"enable_grpc_web"`
	DeadlinePropagation bool              `yaml:"deadline_propagation" json:"deadline_propagation"`
	Services            map[string]string `yaml:"services" json:"services"`
}

OctopusGRPCConfig mirrors octopus gRPC settings.

type OctopusGatewayConfig

type OctopusGatewayConfig struct {
	Listen              string                    `yaml:"listen" json:"listen"`
	Workers             int                       `yaml:"workers" json:"workers"`
	RequestTimeout      string                    `yaml:"request_timeout" json:"request_timeout"`
	ShutdownTimeout     string                    `yaml:"shutdown_timeout" json:"shutdown_timeout"`
	MaxBodySize         int                       `yaml:"max_body_size" json:"max_body_size"`
	TLS                 *OctopusTLSConfig         `yaml:"tls" json:"tls"`
	Compression         *OctopusCompressionConfig `yaml:"compression" json:"compression"`
	InternalRoutePrefix *string                   `yaml:"internal_route_prefix" json:"internal_route_prefix"`
}

OctopusGatewayConfig mirrors octopus gateway.* settings.

type OctopusHealthCheckConfig

type OctopusHealthCheckConfig struct {
	Type               string `yaml:"type" json:"type"`
	Path               string `yaml:"path" json:"path"`
	Interval           string `yaml:"interval" json:"interval"`
	Timeout            string `yaml:"timeout" json:"timeout"`
	HealthyThreshold   int    `yaml:"healthy_threshold" json:"healthy_threshold"`
	UnhealthyThreshold int    `yaml:"unhealthy_threshold" json:"unhealthy_threshold"`
}

OctopusHealthCheckConfig mirrors octopus health check settings.

type OctopusInstanceConfig

type OctopusInstanceConfig struct {
	ID       string            `yaml:"id" json:"id"`
	Host     string            `yaml:"host" json:"host"`
	Port     int               `yaml:"port" json:"port"`
	Weight   int               `yaml:"weight" json:"weight"`
	Metadata map[string]string `yaml:"metadata" json:"metadata"`
}

OctopusInstanceConfig mirrors octopus instance definitions.

type OctopusLoggingConfig

type OctopusLoggingConfig struct {
	Level  string `yaml:"level" json:"level"`
	Format string `yaml:"format" json:"format"`
}

OctopusLoggingConfig mirrors octopus logging settings.

type OctopusMetricsConfig

type OctopusMetricsConfig struct {
	Enabled  bool   `yaml:"enabled" json:"enabled"`
	Endpoint string `yaml:"endpoint" json:"endpoint"`
}

OctopusMetricsConfig mirrors octopus metrics settings.

type OctopusObservabilityConfig

type OctopusObservabilityConfig struct {
	Logging OctopusLoggingConfig `yaml:"logging" json:"logging"`
	Metrics OctopusMetricsConfig `yaml:"metrics" json:"metrics"`
	Tracing OctopusTracingConfig `yaml:"tracing" json:"tracing"`
}

OctopusObservabilityConfig mirrors octopus observability settings.

type OctopusPluginConfig

type OctopusPluginConfig struct {
	Name       string         `yaml:"name" json:"name"`
	PluginType string         `yaml:"plugin_type" json:"plugin_type"`
	Enabled    bool           `yaml:"enabled" json:"enabled"`
	Priority   int            `yaml:"priority" json:"priority"`
	Config     map[string]any `yaml:"config" json:"config"`
}

OctopusPluginConfig mirrors octopus plugin definitions.

type OctopusRouteCORSConfig

type OctopusRouteCORSConfig struct {
	AllowedOrigins   []string `yaml:"allowed_origins" json:"allowed_origins"`
	AllowedMethods   []string `yaml:"allowed_methods" json:"allowed_methods"`
	AllowedHeaders   []string `yaml:"allowed_headers" json:"allowed_headers"`
	AllowCredentials bool     `yaml:"allow_credentials" json:"allow_credentials"`
	MaxAge           int      `yaml:"max_age" json:"max_age"`
}

OctopusRouteCORSConfig mirrors octopus per-route CORS override.

type OctopusRouteConfig

type OctopusRouteConfig struct {
	Path          string                       `yaml:"path" json:"path"`
	Methods       []string                     `yaml:"methods" json:"methods"`
	Upstream      string                       `yaml:"upstream" json:"upstream"`
	Priority      int                          `yaml:"priority" json:"priority"`
	StripPrefix   *string                      `yaml:"strip_prefix" json:"strip_prefix"`
	AddPrefix     *string                      `yaml:"add_prefix" json:"add_prefix"`
	Metadata      map[string]string            `yaml:"metadata" json:"metadata"`
	AuthProvider  *string                      `yaml:"auth_provider" json:"auth_provider"`
	SkipAuth      bool                         `yaml:"skip_auth" json:"skip_auth"`
	RequireRoles  []string                     `yaml:"require_roles" json:"require_roles"`
	RequireScopes []string                     `yaml:"require_scopes" json:"require_scopes"`
	AuthzRule     *string                      `yaml:"authz_rule" json:"authz_rule"`
	Timeout       *string                      `yaml:"timeout" json:"timeout"`
	RateLimit     *OctopusRouteRateLimitConfig `yaml:"rate_limit" json:"rate_limit"`
	CORS          *OctopusRouteCORSConfig      `yaml:"cors" json:"cors"`
}

OctopusRouteConfig mirrors octopus route definitions.

type OctopusRouteRateLimitConfig

type OctopusRouteRateLimitConfig struct {
	RequestsPerWindow int    `yaml:"requests_per_window" json:"requests_per_window"`
	WindowSize        string `yaml:"window_size" json:"window_size"`
}

OctopusRouteRateLimitConfig mirrors octopus per-route rate limiting.

type OctopusTLSConfig

type OctopusTLSConfig struct {
	CertFile           string `yaml:"cert_file" json:"cert_file"`
	KeyFile            string `yaml:"key_file" json:"key_file"`
	ClientCAFile       string `yaml:"client_ca_file" json:"client_ca_file"`
	RequireClientCert  bool   `yaml:"require_client_cert" json:"require_client_cert"`
	MinTLSVersion      string `yaml:"min_tls_version" json:"min_tls_version"`
	EnableCertReload   bool   `yaml:"enable_cert_reload" json:"enable_cert_reload"`
	ReloadIntervalSecs int    `yaml:"reload_interval_secs" json:"reload_interval_secs"`
}

OctopusTLSConfig mirrors octopus TLS settings.

type OctopusTracingConfig

type OctopusTracingConfig struct {
	Enabled        bool   `yaml:"enabled" json:"enabled"`
	JaegerEndpoint string `yaml:"jaeger_endpoint" json:"jaeger_endpoint"`
}

OctopusTracingConfig mirrors octopus tracing settings.

type OctopusUpstreamConfig

type OctopusUpstreamConfig struct {
	Name           string                    `yaml:"name" json:"name"`
	Instances      []OctopusInstanceConfig   `yaml:"instances" json:"instances"`
	LBPolicy       string                    `yaml:"lb_policy" json:"lb_policy"`
	HealthCheck    *OctopusHealthCheckConfig `yaml:"health_check" json:"health_check"`
	CircuitBreaker *OctopusCBConfig          `yaml:"circuit_breaker" json:"circuit_breaker"`
}

OctopusUpstreamConfig mirrors octopus upstream definitions.

type OpenAPIAggregator

type OpenAPIAggregator = disc.OpenAPIAggregator

OpenAPIAggregator is a backward-compatible alias for discovery.OpenAPIAggregator.

func NewOpenAPIAggregator

func NewOpenAPIAggregator(config OpenAPIConfig, logger forge.Logger, rm RouteRegistry, sd *ServiceDiscovery) *OpenAPIAggregator

NewOpenAPIAggregator creates a new OpenAPI aggregator.

type OpenAPIConfig

type OpenAPIConfig = disc.OpenAPIConfig

OpenAPIConfig holds configuration for the OpenAPI aggregation feature.

Canonical definition: discovery.OpenAPIConfig

func DefaultOpenAPIConfig

func DefaultOpenAPIConfig() OpenAPIConfig

DefaultOpenAPIConfig returns defaults for OpenAPI aggregation.

type OpenAPIService

type OpenAPIService interface {
	Start(ctx context.Context)
	Refresh(ctx context.Context)
	MergedSpec() []byte
	MergedSpecMap() map[string]any
	ServiceSpec(serviceName string) *ServiceOpenAPISpec
	ServiceSpecs() map[string]*ServiceOpenAPISpec
	LastRefresh() time.Time
	HandleMergedSpec(ctx forge.Context) error
	HandleSwaggerUI(ctx forge.Context) error
	HandleServiceList(ctx forge.Context) error
	HandleServiceSpec(ctx forge.Context) error
	HandleRefresh(ctx forge.Context) error
}

OpenAPIService handles OpenAPI spec aggregation and serving.

type PathRewriter

type PathRewriter struct{}

PathRewriter rewrites request paths according to route configuration.

type RateLimitConfig

type RateLimitConfig = middleware.RateLimitConfig

RateLimitConfig holds rate limiting settings.

Canonical definition: middleware.RateLimitConfig

type RateLimitStore

type RateLimitStore = middleware.RateLimitStore

RateLimitStore is the interface for distributed rate limiting backends. Implementations must be safe for concurrent use.

Canonical definition: middleware.RateLimitStore

type RateLimiter

type RateLimiter = middleware.RateLimiter

RateLimiter implements token-bucket rate limiting.

Canonical definition: middleware.RateLimiter

func NewRateLimiter

func NewRateLimiter(config RateLimitConfig) *RateLimiter

NewRateLimiter creates a new rate limiter.

type RequestHook

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 RequestLimiter

type RequestLimiter interface {
	Allow(r *http.Request) bool
	AllowWithConfig(r *http.Request, config *RateLimitConfig) bool
	Cleanup(maxAge time.Duration)
}

RequestLimiter handles request rate limiting.

type ResponseCache

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

ResponseCache provides HTTP response caching for the gateway. This is a thin wrapper around middleware.ResponseCache that adapts the root-level Route type to the middleware-local Route type.

func NewResponseCache

func NewResponseCache(config CachingConfig, logger forge.Logger, store CacheStore) *ResponseCache

NewResponseCache creates a new response cache.

func (*ResponseCache) Get

func (rc *ResponseCache) Get(r *http.Request, route *Route) *CachedResponse

Get attempts to retrieve a cached response for the given request.

func (*ResponseCache) Invalidate

func (rc *ResponseCache) Invalidate(ctx context.Context, method, path string) error

Invalidate removes a cached entry for the given request.

func (*ResponseCache) Set

func (rc *ResponseCache) Set(r *http.Request, route *Route, statusCode int, headers http.Header, body []byte)

Set stores a response in the cache.

func (*ResponseCache) Stats

func (rc *ResponseCache) Stats() *CacheStats

Stats returns the cache statistics.

func (*ResponseCache) WriteCachedResponse

func (rc *ResponseCache) WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)

WriteCachedResponse writes a cached response to the client.

type ResponseCacher

type ResponseCacher interface {
	Get(r *http.Request, route *Route) *CachedResponse
	Set(r *http.Request, route *Route, statusCode int, headers http.Header, body []byte)
	WriteCachedResponse(w http.ResponseWriter, cached *CachedResponse)
	Invalidate(ctx context.Context, method, path string) error
	Stats() CacheStatsReader
}

ResponseCacher handles HTTP response caching.

type ResponseHook

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 RetryPolicy

type RetryPolicy interface {
	ShouldRetry(method string, statusCode int, attempt int, routeConfig *RetryConfig) bool
	Delay(attempt int, routeConfig *RetryConfig) time.Duration
}

RetryPolicy determines retry behavior for failed requests.

type Route

type Route struct {
	ID          string        `json:"id"`
	Path        string        `json:"path"`
	Methods     []string      `json:"methods,omitempty"`
	Targets     []*Target     `json:"targets"`
	StripPrefix bool          `json:"stripPrefix"`
	AddPrefix   string        `json:"addPrefix,omitempty"`
	RewritePath string        `json:"rewritePath,omitempty"`
	Headers     HeaderPolicy  `json:"headers"`
	Protocol    RouteProtocol `json:"protocol"`
	Source      RouteSource   `json:"source"`
	ServiceName string        `json:"serviceName,omitempty"`
	Priority    int           `json:"priority"`
	Version     int64         `json:"version"`
	Enabled     bool          `json:"enabled"`

	// Per-route overrides (nil = use global defaults)
	Retry          *RetryConfig      `json:"retry,omitempty"`
	Timeout        *TimeoutConfig    `json:"timeout,omitempty"`
	RateLimit      *RateLimitConfig  `json:"rateLimit,omitempty"`
	Auth           *RouteAuthConfig  `json:"auth,omitempty"`
	CircuitBreaker *CBConfig         `json:"circuitBreaker,omitempty"`
	Cache          *RouteCacheConfig `json:"cache,omitempty"`
	TrafficPolicy  *TrafficPolicy    `json:"trafficPolicy,omitempty"`
	Transform      *TransformConfig  `json:"transform,omitempty"`

	Metadata  map[string]any `json:"metadata,omitempty"`
	CreatedAt time.Time      `json:"createdAt"`
	UpdatedAt time.Time      `json:"updatedAt"`
}

Route represents a configured gateway route with full policy support.

func (*Route) GetAuth

func (r *Route) GetAuth() *RouteAuthConfig

GetAuth returns the per-route auth config (implements security.Route).

func (*Route) GetID

func (r *Route) GetID() string

GetID returns the route ID (implements security.Route).

type RouteAuthConfig

type RouteAuthConfig = security.RouteAuthConfig

RouteAuthConfig defines per-route auth requirements.

Canonical definition: security.RouteAuthConfig

type RouteCacheConfig

type RouteCacheConfig = middleware.RouteCacheConfig

RouteCacheConfig defines per-route caching policy.

Canonical definition: middleware.RouteCacheConfig

type RouteChangeHook

type RouteChangeHook func(event RouteEvent)

RouteChangeHook is called when the route table changes.

type RouteConfig

type RouteConfig struct {
	Path          string            `json:"path" yaml:"path"`
	Methods       []string          `json:"methods,omitempty" yaml:"methods"`
	Targets       []TargetConfig    `json:"targets" yaml:"targets"`
	StripPrefix   bool              `json:"stripPrefix" yaml:"strip_prefix"`
	AddPrefix     string            `json:"addPrefix,omitempty" yaml:"add_prefix"`
	RewritePath   string            `json:"rewritePath,omitempty" yaml:"rewrite_path"`
	Headers       HeaderPolicy      `json:"headers" yaml:"headers"`
	Protocol      RouteProtocol     `json:"protocol" yaml:"protocol"`
	Priority      int               `json:"priority" yaml:"priority"`
	Enabled       bool              `json:"enabled" yaml:"enabled"`
	Retry         *RetryConfig      `json:"retry,omitempty" yaml:"retry"`
	Timeout       *TimeoutConfig    `json:"timeout,omitempty" yaml:"timeout"`
	RateLimit     *RateLimitConfig  `json:"rateLimit,omitempty" yaml:"rate_limit"`
	Auth          *RouteAuthConfig  `json:"auth,omitempty" yaml:"auth"`
	Cache         *RouteCacheConfig `json:"cache,omitempty" yaml:"cache"`
	TrafficPolicy *TrafficPolicy    `json:"trafficPolicy,omitempty" yaml:"traffic_policy"`
	Metadata      map[string]any    `json:"metadata,omitempty" yaml:"metadata"`

	// ServiceName associates this route with a logical service name.
	// When set, the route can contribute to the aggregated OpenAPI spec.
	ServiceName string `json:"serviceName,omitempty" yaml:"service_name"`

	// OpenAPISpec is the URL to the OpenAPI spec for this route's upstream service.
	// When set (along with ServiceName), the aggregator will fetch and include
	// this spec in the merged gateway documentation.
	OpenAPISpec string `json:"openapiSpec,omitempty" yaml:"openapi_spec"`
}

RouteConfig defines a static route in configuration.

type RouteDTO

type RouteDTO struct {
	Path        string        `json:"path"`
	Methods     []string      `json:"methods,omitempty"`
	Targets     []TargetDTO   `json:"targets"`
	StripPrefix bool          `json:"stripPrefix"`
	AddPrefix   string        `json:"addPrefix,omitempty"`
	RewritePath string        `json:"rewritePath,omitempty"`
	Headers     HeaderPolicy  `json:"headers"`
	Protocol    RouteProtocol `json:"protocol"`
	Priority    int           `json:"priority"`
	Enabled     bool          `json:"enabled"`

	Retry          *RetryConfig      `json:"retry,omitempty"`
	Timeout        *TimeoutConfig    `json:"timeout,omitempty"`
	RateLimit      *RateLimitConfig  `json:"rateLimit,omitempty"`
	Auth           *RouteAuthConfig  `json:"auth,omitempty"`
	CircuitBreaker *CBConfig         `json:"circuitBreaker,omitempty"`
	Cache          *RouteCacheConfig `json:"cache,omitempty"`
	TrafficPolicy  *TrafficPolicy    `json:"trafficPolicy,omitempty"`
	Transform      *TransformConfig  `json:"transform,omitempty"`
	Metadata       map[string]any    `json:"metadata,omitempty"`
}

RouteDTO is the API request body for creating/updating a route.

type RouteEvent

type RouteEvent struct {
	Type      RouteEventType `json:"type"`
	Route     *Route         `json:"route"`
	Timestamp time.Time      `json:"timestamp"`
}

RouteEvent represents a change in the route table.

type RouteEventType

type RouteEventType string

RouteEventType represents types of route events.

const (
	// RouteEventAdded indicates a new route was added.
	RouteEventAdded RouteEventType = "added"

	// RouteEventUpdated indicates a route was updated.
	RouteEventUpdated RouteEventType = "updated"

	// RouteEventRemoved indicates a route was removed.
	RouteEventRemoved RouteEventType = "removed"
)

type RouteProtocol

type RouteProtocol string

RouteProtocol defines the protocol type for a gateway route.

const (
	// ProtocolHTTP is standard HTTP/HTTPS proxying.
	ProtocolHTTP RouteProtocol = "http"

	// ProtocolWebSocket is WebSocket proxying.
	ProtocolWebSocket RouteProtocol = "websocket"

	// ProtocolSSE is Server-Sent Events proxying.
	ProtocolSSE RouteProtocol = "sse"

	// ProtocolGRPC is gRPC proxying.
	ProtocolGRPC RouteProtocol = "grpc"

	// ProtocolGraphQL is GraphQL proxying (HTTP-based with special handling).
	ProtocolGraphQL RouteProtocol = "graphql"
)

type RouteRegistry

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

RouteRegistry manages gateway route configuration and matching.

type RouteSource

type RouteSource string

RouteSource indicates how a route was created.

const (
	// SourceManual indicates a manually configured route.
	SourceManual RouteSource = "manual"

	// SourceFARP indicates a route auto-generated from FARP schemas.
	SourceFARP RouteSource = "farp"

	// SourceDiscovery indicates a route from service discovery.
	SourceDiscovery RouteSource = "discovery"
)

type RouteStats

type RouteStats struct {
	RouteID       string `json:"routeId"`
	Path          string `json:"path"`
	TotalRequests int64  `json:"totalRequests"`
	TotalErrors   int64  `json:"totalErrors"`
	// AvgLatencyMs is the mean over every answered upstream request since start.
	AvgLatencyMs float64 `json:"avgLatencyMs"`
	// P99LatencyMs is the nearest-rank p99 over the most recent LatencySamples responses.
	P99LatencyMs float64 `json:"p99LatencyMs"`
	// LatencySamples is how many recent responses P99LatencyMs covers.
	LatencySamples int   `json:"latencySamples"`
	CacheHits      int64 `json:"cacheHits"`
	CacheMisses    int64 `json:"cacheMisses"`
	RateLimited    int64 `json:"rateLimited"`
}

RouteStats holds per-route traffic statistics.

type RouteStore

type RouteStore interface {
	// ListRoutes returns all persisted routes.
	ListRoutes(ctx context.Context) ([]*Route, error)

	// GetRoute returns a single route by ID.
	GetRoute(ctx context.Context, routeID string) (*Route, error)

	// SaveRoute creates or updates a route.
	SaveRoute(ctx context.Context, route *Route) error

	// DeleteRoute removes a route by ID.
	DeleteRoute(ctx context.Context, routeID string) error
}

RouteStore persists gateway route configuration.

type SSEConfig

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

SSEConfig holds SSE proxy settings.

type ServiceDiscoverer

type ServiceDiscoverer interface {
	Start(ctx context.Context) error
	Stop()
	Refresh(ctx context.Context) error
	DiscoveredServices() []*DiscoveredService
}

ServiceDiscoverer manages automatic service discovery integration.

type ServiceDiscovery

type ServiceDiscovery = disc.Manager

ServiceDiscovery is a backward-compatible alias for discovery.Manager.

func NewServiceDiscovery

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

NewServiceDiscovery creates a new service discovery integration. The RouteRegistry is adapted to satisfy discovery.RouteRegistry.

type ServiceFilter

type ServiceFilter = disc.ServiceFilter

ServiceFilter defines a filter for discovered services.

Canonical definition: discovery.ServiceFilter

type ServiceInstanceInfo

type ServiceInstanceInfo = disc.ServiceInstanceInfo

ServiceInstanceInfo represents a discovered service instance.

Canonical definition: discovery.ServiceInstanceInfo

type ServiceOpenAPISpec

type ServiceOpenAPISpec = disc.ServiceOpenAPISpec

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

Canonical definition: discovery.ServiceOpenAPISpec

type StatsRecorder

type StatsRecorder interface {
	Snapshot(routes []*Route) *GatewayStats
	RecordRequest(routeID, path string)
	RecordError(routeID string)
	RecordLatency(routeID string, d time.Duration)
	RecordRateLimited()
	RecordCircuitBreak()
	RecordRetryAttempt()
	RecordCacheHit()
	RecordCacheMiss()
}

StatsRecorder collects and reports gateway traffic statistics.

type TLSConfig

type TLSConfig = security.TLSConfig

TLSConfig holds upstream TLS settings.

Canonical definition: security.TLSConfig

type TLSManager

type TLSManager = security.TLSManager

TLSManager is a backward-compatible alias for security.TLSManager.

func NewTLSManager

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

NewTLSManager creates a new TLS manager. Deprecated: Use security.NewTLSManager directly.

type TLSProvider

type TLSProvider interface {
	GlobalTLSConfig() *tls.Config
	TargetTLSConfig(target *Target) *tls.Config
	TransportForTarget(baseTransport *http.Transport, target *Target) *http.Transport
	Start()
	Stop()
	Reload() error
	LastReload() time.Time
}

TLSProvider manages TLS certificates and transport configuration.

type Target

type Target struct {
	ID           string            `json:"id"`
	URL          string            `json:"url"`
	Weight       int               `json:"weight"`
	Healthy      bool              `json:"healthy"`
	ActiveConns  int64             `json:"activeConns"`
	CircuitState CircuitState      `json:"circuitState"`
	TLS          *TargetTLSConfig  `json:"tls,omitempty"`
	Metadata     map[string]string `json:"metadata,omitempty"`
	Tags         []string          `json:"tags,omitempty"`

	// Stats
	TotalRequests int64   `json:"totalRequests"`
	TotalErrors   int64   `json:"totalErrors"`
	AvgLatencyMs  float64 `json:"avgLatencyMs"`
	P99LatencyMs  float64 `json:"p99LatencyMs"`
	// contains filtered or unexported fields
}

Target represents an upstream service endpoint.

func (*Target) DecrConns

func (t *Target) DecrConns()

DecrConns decrements active connections.

func (*Target) GetID

func (t *Target) GetID() string

GetID returns the target ID (implements health.Target).

func (*Target) GetTLS

func (t *Target) GetTLS() *TargetTLSConfig

GetTLS returns the per-target TLS config (implements security.Target).

func (*Target) GetURL

func (t *Target) GetURL() string

GetURL returns the target URL (implements health.Target).

func (*Target) HealthPath

func (t *Target) HealthPath() string

HealthPath returns a custom health check path for this target, if one is set in its metadata (key "health_check_path"). Returns empty string to use the monitor's default path. Implements health.HealthPathProvider.

func (*Target) 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) IsHealthy

func (t *Target) IsHealthy() bool

IsHealthy returns whether the target is healthy (implements health.Target).

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

func (t *Target) SetHealthy(healthy bool)

SetHealthy sets the target health status (implements health.Target).

func (*Target) Snapshot

func (t *Target) Snapshot()

Snapshot populates the exported stats fields from atomics. It writes to the shared target and races the proxy; new code uses Stats.

func (*Target) Stats

func (t *Target) Stats() TargetStats

Stats reads the target's counters without writing to the target, unlike Snapshot, which fills the exported fields in place and races the proxy.

type TargetConfig

type TargetConfig struct {
	URL      string            `json:"url" yaml:"url"`
	Weight   int               `json:"weight" yaml:"weight"`
	Tags     []string          `json:"tags,omitempty" yaml:"tags"`
	Metadata map[string]string `json:"metadata,omitempty" yaml:"metadata"`
	TLS      *TargetTLSConfig  `json:"tls,omitempty" yaml:"tls"`
}

TargetConfig defines a target in configuration.

type TargetDTO

type TargetDTO struct {
	URL      string            `json:"url"`
	Weight   int               `json:"weight"`
	Tags     []string          `json:"tags,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
	TLS      *TargetTLSConfig  `json:"tls,omitempty"`
}

TargetDTO is the API representation of a target.

type TargetStats

type TargetStats struct {
	ActiveConns   int64   `json:"activeConns"`
	TotalRequests int64   `json:"totalRequests"`
	TotalErrors   int64   `json:"totalErrors"`
	AvgLatencyMs  float64 `json:"avgLatencyMs"`
}

TargetStats is a point-in-time copy of a target's counters.

type TargetTLSConfig

type TargetTLSConfig = security.TargetTLSConfig

TargetTLSConfig holds per-target TLS configuration.

Canonical definition: security.TargetTLSConfig

type TimeoutConfig

type TimeoutConfig struct {
	Connect time.Duration `json:"connect" yaml:"connect"`
	Read    time.Duration `json:"read" yaml:"read"`
	Write   time.Duration `json:"write" yaml:"write"`
	Idle    time.Duration `json:"idle" yaml:"idle"`
}

TimeoutConfig holds timeout settings.

type TracingConfig

type TracingConfig struct {
	Enabled         bool    `json:"enabled" yaml:"enabled"`
	PropagateFormat string  `json:"propagateFormat,omitempty" yaml:"propagate_format"`
	SampleRate      float64 `json:"sampleRate" yaml:"sample_rate"`
}

TracingConfig holds tracing settings. The gateway doesn't read it: tracing, sampling and propagation are set on the Forge app, and bastion's spans follow that. It is kept so existing config and code keep working.

type TrafficMatch

type TrafficMatch struct {
	Type   TrafficMatchType `json:"type"`
	Key    string           `json:"key,omitempty"`
	Value  string           `json:"value,omitempty"`
	Negate bool             `json:"negate,omitempty"`
}

TrafficMatch defines traffic matching criteria.

type TrafficMatchType

type TrafficMatchType string

TrafficMatchType defines how traffic rules are matched.

const (
	// MatchHeader matches on request header value.
	MatchHeader TrafficMatchType = "header"

	// MatchCookie matches on cookie value.
	MatchCookie TrafficMatchType = "cookie"

	// MatchWeight matches by random weight percentage.
	MatchWeight TrafficMatchType = "weight"

	// MatchIPRange matches by client IP range.
	MatchIPRange TrafficMatchType = "ipRange"
)

type TrafficPolicy

type TrafficPolicy struct {
	Type         TrafficSplitType `json:"type"`
	Rules        []TrafficRule    `json:"rules"`
	MirrorTarget string           `json:"mirrorTarget,omitempty"`
}

TrafficPolicy defines traffic splitting rules for a route.

type TrafficRouter

type TrafficRouter interface {
	FilterTargets(r *http.Request, route *Route) []*Target
	ShouldMirror(route *Route) string
}

TrafficRouter handles traffic splitting and mirroring.

type TrafficRule

type TrafficRule struct {
	Match      TrafficMatch `json:"match"`
	TargetTags []string     `json:"targetTags"`
	Weight     int          `json:"weight"`
}

TrafficRule defines a single traffic routing rule.

type TrafficSplitConfig

type TrafficSplitConfig struct {
	Enabled bool `json:"enabled" yaml:"enabled"`
}

TrafficSplitConfig holds global traffic split settings.

type TrafficSplitType

type TrafficSplitType string

TrafficSplitType defines the traffic splitting strategy.

const (
	// TrafficCanary routes a percentage of traffic to canary targets.
	TrafficCanary TrafficSplitType = "canary"

	// TrafficBlueGreen switches between two target groups.
	TrafficBlueGreen TrafficSplitType = "blueGreen"

	// TrafficABTest routes based on header/cookie matching.
	TrafficABTest TrafficSplitType = "abTest"

	// TrafficMirror duplicates requests to a mirror target.
	TrafficMirror TrafficSplitType = "mirror"

	// TrafficWeighted uses explicit weight distribution.
	TrafficWeighted TrafficSplitType = "weighted"
)

type TransformConfig

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

TransformConfig defines request/response transformation.

type UpstreamHealthEvent

type UpstreamHealthEvent struct {
	TargetID  string    `json:"targetId"`
	TargetURL string    `json:"targetUrl"`
	Healthy   bool      `json:"healthy"`
	Previous  bool      `json:"previous"`
	RouteID   string    `json:"routeId"`
	Timestamp time.Time `json:"timestamp"`
}

UpstreamHealthEvent represents an upstream health change.

type UpstreamHealthHook

type UpstreamHealthHook func(event UpstreamHealthEvent)

UpstreamHealthHook is called when upstream health changes.

type ValidationError

type ValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

ValidationError represents a configuration validation error.

func (*ValidationError) Error

func (e *ValidationError) Error() string

type ValidationErrors

type ValidationErrors []ValidationError

ValidationErrors is a collection of validation errors.

func (ValidationErrors) Error

func (ve ValidationErrors) Error() string

type WAF

type WAF = security.WAF

WAF is a backward-compatible alias for security.WAF.

func NewWAF

func NewWAF(cfg WAFConfig) *WAF

NewWAF creates a WAF with the given configuration. Deprecated: Use security.NewWAF directly.

type WAFConfig

type WAFConfig = security.WAFConfig

WAFConfig is a backward-compatible alias for security.WAFConfig.

type WAFPlugin

type WAFPlugin struct {
	BasePlugin
	// contains filtered or unexported fields
}

WAFPlugin wraps security.WAFPlugin as a root-level GatewayPlugin.

func NewWAFPlugin

func NewWAFPlugin(cfg WAFConfig) *WAFPlugin

NewWAFPlugin creates a WAF plugin that implements GatewayPlugin. Deprecated: Use security.NewWAFPlugin directly.

func (*WAFPlugin) OnRequest

func (p *WAFPlugin) OnRequest(r *http.Request, _ *Route) error

OnRequest checks the request against WAF rules.

type WAFRule

type WAFRule = security.WAFRule

WAFRule is a backward-compatible alias for security.WAFRule.

type WAFViolation

type WAFViolation = security.WAFViolation

WAFViolation is a backward-compatible alias for security.WAFViolation.

type WSBroadcaster

type WSBroadcaster interface {
	Run()
	Broadcast(data any) error
	ClientCount() int
}

WSBroadcaster manages WebSocket connections for real-time updates.

type WebSocketConfig

type WebSocketConfig struct {
	ReadBufferSize   int           `json:"readBufferSize" yaml:"read_buffer_size"`
	WriteBufferSize  int           `json:"writeBufferSize" yaml:"write_buffer_size"`
	HandshakeTimeout time.Duration `json:"handshakeTimeout" yaml:"handshake_timeout"`
	PingInterval     time.Duration `json:"pingInterval" yaml:"ping_interval"`
	PongTimeout      time.Duration `json:"pongTimeout" yaml:"pong_timeout"`
}

WebSocketConfig holds WebSocket proxy settings.

Directories

Path Synopsis
Package admin owns the gateway's operator writes and the read models that the REST API and the dashboard contract share.
Package admin owns the gateway's operator writes and the read models that the REST API and the dashboard contract share.
Package api provides WebSocket hub and client types for real-time dashboard communication.
Package api provides WebSocket hub and client types for real-time dashboard communication.
Package discovery provides FARP-based service discovery and OpenAPI specification aggregation for the Bastion API gateway.
Package discovery provides FARP-based service discovery and OpenAPI specification aggregation for the Bastion API gateway.
contract
Package contract wires Bastion into the Forge dashboard's contract path.
Package contract wires Bastion into the Forge dashboard's contract path.
Package gateway builds a Bastion gateway that proxies on its own.
Package gateway builds a Bastion gateway that proxies on its own.
Package health provides upstream health monitoring with active probes, passive failure tracking, and health check history.
Package health provides upstream health monitoring with active probes, passive failure tracking, and health check history.
internal
telemetry
Package telemetry holds bastion's tracing helpers: the tracer, root spans for background work, error recording that never copies an error's text, and the client span every outbound HTTP call gets.
Package telemetry holds bastion's tracing helpers: the tracer, root spans for background work, error recording that never copies an error's text, and the client span every outbound HTTP call gets.
telemetry/telemetrytest
Package telemetrytest records bastion's spans and scrapes its metrics in tests.
Package telemetrytest records bastion's spans and scrapes its metrics in tests.
Package middleware provides HTTP middleware including response caching, rate limiting, and compression for the gateway.
Package middleware provides HTTP middleware including response caching, rate limiting, and compression for the gateway.
Package observability provides metrics, access logging, and audit logging for the gateway.
Package observability provides metrics, access logging, and audit logging for the gateway.
Package plugin provides the gateway plugin system for extending the proxy pipeline with custom request/response processing logic.
Package plugin provides the gateway plugin system for extending the proxy pipeline with custom request/response processing logic.
Package proxy provides the core reverse proxy engine with support for HTTP, gRPC, WebSocket, and SSE protocols.
Package proxy provides the core reverse proxy engine with support for HTTP, gRPC, WebSocket, and SSE protocols.
Package resilience provides circuit breakers, retry logic, bulkheading, request coalescing, and graceful drain for the gateway proxy pipeline.
Package resilience provides circuit breakers, retry logic, bulkheading, request coalescing, and graceful drain for the gateway proxy pipeline.
Package routing manages gateway route configuration, matching, load balancing, traffic splitting, and API versioning.
Package routing manages gateway route configuration, matching, load balancing, traffic splitting, and API versioning.
Package security provides authentication, TLS management, admin auth, and web application firewall (WAF) for the gateway.
Package security provides authentication, TLS management, admin auth, and web application firewall (WAF) for the gateway.
Package store defines the composite store interface for Bastion.
Package store defines the composite store interface for Bastion.
memory
Package memory provides an in-memory implementation of the Bastion composite store.
Package memory provides an in-memory implementation of the Bastion composite store.
mongo
Package mongo provides a MongoDB implementation of the Bastion composite store using grove ORM.
Package mongo provides a MongoDB implementation of the Bastion composite store using grove ORM.
postgres
Package postgres provides a PostgreSQL implementation of the Bastion composite store using grove ORM with programmatic migrations.
Package postgres provides a PostgreSQL implementation of the Bastion composite store using grove ORM with programmatic migrations.
sqlite
Package sqlite provides a SQLite implementation of the Bastion composite store using grove ORM with programmatic migrations.
Package sqlite provides a SQLite implementation of the Bastion composite store using grove ORM with programmatic migrations.

Jump to

Keyboard shortcuts

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