Documentation
¶
Overview ¶
Package discovery provides FARP-based service discovery and OpenAPI specification aggregation for the Bastion API gateway.
Overview ¶
The discovery package automatically discovers upstream services, generates gateway routes, and aggregates OpenAPI specifications into a unified API documentation endpoint. It integrates with the FARP (Forge API Registration Protocol) for rich service metadata and routing configuration.
Service Discovery ¶
The Manager periodically polls a DiscoveryService for available services and automatically creates gateway routes. The discovery flow is:
- List all registered services from the discovery provider
- For each service, discover healthy instances
- Check for FARP metadata on instances (farp.enabled, farp.manifest, etc.)
- If FARP is enabled, fetch the full FARP [SchemaManifest] for rich routing config
- Fall back to flat FARP metadata keys if manifest fetch fails
- Create gateway routes with appropriate protocols, prefixes, and priorities
- Remove routes for services that are no longer registered
FARP Integration ¶
When a service publishes FARP metadata via the forge discovery extension, the following metadata keys are used:
- farp.enabled: "true" to indicate the service supports FARP
- farp.manifest: URL to the service's SchemaManifest endpoint
- farp.openapi: URL to the service's OpenAPI spec
- farp.openapi.path: Path to the OpenAPI spec (combined with service address)
- farp.asyncapi: URL to the service's AsyncAPI spec
- farp.graphql: URL to the service's GraphQL introspection endpoint
- farp.capabilities: Comma-separated list of capabilities (rest, grpc, websocket, etc.)
When the full manifest is available (via farp.manifest), the discovery manager uses the manifest's [RoutingConfig] to determine:
- Mount strategy: root, service, versioned, custom, instance, or subdomain
- Base path for custom mounting
- Route priority for conflict resolution
- Whether to strip the path prefix before forwarding
OpenAPI Aggregation ¶
The OpenAPIAggregator fetches OpenAPI specs from all discovered services and merges them into a unified OpenAPI 3.1.0 specification. It provides:
- Merged spec endpoint (default: /openapi.json) — all service specs combined
- Swagger UI endpoint (default: /swagger) — interactive API documentation
- Per-service spec endpoints — individual service specs
- Service list endpoint — summary of all services with spec status
- On-demand refresh endpoint — trigger immediate spec re-fetch
Configuration ¶
Service discovery is configured via DiscoveryConfig:
discovery.DiscoveryConfig{
Enabled: true,
PollInterval: 30 * time.Second,
AutoPrefix: true,
PrefixTemplate: "/{{.ServiceName}}",
StripPrefix: true,
FetchTimeout: 10 * time.Second,
}
OpenAPI aggregation is configured via OpenAPIConfig:
discovery.OpenAPIConfig{
Enabled: true,
Path: "/openapi.json",
UIPath: "/swagger",
Title: "API Gateway",
RefreshInterval: 30 * time.Second,
FetchTimeout: 10 * time.Second,
MergeStrategy: "prefix",
IncludeGatewayRoutes: true,
}
Index ¶
- type AsyncAPIAggregator
- func (aa *AsyncAPIAggregator) HandleMergedSpec(ctx forge.Context) error
- func (aa *AsyncAPIAggregator) LastRefresh() time.Time
- func (aa *AsyncAPIAggregator) MergedSpec() []byte
- func (aa *AsyncAPIAggregator) MergedSpecMap() map[string]any
- func (aa *AsyncAPIAggregator) Refresh(ctx context.Context)
- func (aa *AsyncAPIAggregator) RefreshDetached(ctx context.Context)
- func (aa *AsyncAPIAggregator) SetMetrics(m *observability.Metrics)
- func (aa *AsyncAPIAggregator) SpecPath() string
- func (aa *AsyncAPIAggregator) Start(ctx context.Context)
- type AsyncAPIConfig
- type AuthOverride
- type CacheOverride
- type DiscoveredService
- type DiscoveryConfig
- type DiscoveryDebugInfo
- type DiscoveryService
- type ExtensionPathFilter
- type FARPServiceDiscovery
- type FARPServiceInstance
- type FetchedSchema
- type Manager
- func (sd *Manager) BuildPrefix(serviceName string) string
- func (sd *Manager) DebugDiscovery(ctx context.Context) *DiscoveryDebugInfo
- func (sd *Manager) DeregisterService(ctx context.Context, serviceName string)
- func (sd *Manager) DiscoveredServices() []*DiscoveredService
- func (sd *Manager) GetInstanceChecksum(instanceID string) (string, int)
- func (sd *Manager) GetServicePrefix(serviceName string) string
- func (sd *Manager) OnServiceChange(fn ServiceChangeHook) func()
- func (sd *Manager) Refresh(ctx context.Context) error
- func (sd *Manager) RegisterService(ctx context.Context, info *ServiceInstanceInfo) error
- func (sd *Manager) ServiceManifest(name string) *farp.SchemaManifest
- func (sd *Manager) ServiceManifests() map[string]*farp.SchemaManifest
- func (sd *Manager) SetManifest(serviceName string, manifest *farp.SchemaManifest)
- func (sd *Manager) SetMetrics(m *observability.Metrics)
- func (sd *Manager) Start(ctx context.Context) error
- func (sd *Manager) Stop()
- type OpenAPIAggregator
- func (oa *OpenAPIAggregator) HandleGatewaySpec(ctx forge.Context) error
- func (oa *OpenAPIAggregator) HandleMergedSpec(ctx forge.Context) error
- func (oa *OpenAPIAggregator) HandleRefresh(ctx forge.Context) error
- func (oa *OpenAPIAggregator) HandleServiceList(ctx forge.Context) error
- func (oa *OpenAPIAggregator) HandleServiceSpec(ctx forge.Context) error
- func (oa *OpenAPIAggregator) HandleSwaggerUI(ctx forge.Context) error
- func (oa *OpenAPIAggregator) LastRefresh() time.Time
- func (oa *OpenAPIAggregator) MergedSpec() []byte
- func (oa *OpenAPIAggregator) MergedSpecMap() map[string]any
- func (oa *OpenAPIAggregator) Refresh(ctx context.Context)
- func (oa *OpenAPIAggregator) RefreshDetached(ctx context.Context)
- func (oa *OpenAPIAggregator) ServiceSpec(serviceName string) *ServiceOpenAPISpec
- func (oa *OpenAPIAggregator) ServiceSpecs() map[string]*ServiceOpenAPISpec
- func (oa *OpenAPIAggregator) SetMetrics(m *observability.Metrics)
- func (oa *OpenAPIAggregator) SpecPath() string
- func (oa *OpenAPIAggregator) Start(ctx context.Context)
- func (oa *OpenAPIAggregator) SwaggerUIHandler(specURL string) forge.Handler
- func (oa *OpenAPIAggregator) UIPath() string
- type OpenAPIConfig
- type RateLimitOverride
- type Route
- type RouteProtocol
- type RouteRegistry
- type RouteSource
- type SchemaFetcher
- type ServiceChangeHook
- type ServiceFilter
- type ServiceInstanceInfo
- type ServiceOpenAPISpec
- type Target
- type TimeoutOverride
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AsyncAPIAggregator ¶
type AsyncAPIAggregator struct {
// contains filtered or unexported fields
}
AsyncAPIAggregator fetches, caches, and merges AsyncAPI specs from all discovered upstream services that expose AsyncAPI schemas via FARP manifests. It exposes a unified merged AsyncAPI spec combining all service channels.
func NewAsyncAPIAggregator ¶
func NewAsyncAPIAggregator(config AsyncAPIConfig, logger forge.Logger, disc *Manager) *AsyncAPIAggregator
NewAsyncAPIAggregator creates a new AsyncAPI aggregator.
func (*AsyncAPIAggregator) HandleMergedSpec ¶
func (aa *AsyncAPIAggregator) HandleMergedSpec(ctx forge.Context) error
HandleMergedSpec serves the aggregated AsyncAPI spec as JSON.
func (*AsyncAPIAggregator) LastRefresh ¶
func (aa *AsyncAPIAggregator) LastRefresh() time.Time
LastRefresh returns the time of the last spec refresh.
func (*AsyncAPIAggregator) MergedSpec ¶
func (aa *AsyncAPIAggregator) MergedSpec() []byte
MergedSpec returns the pre-serialized merged AsyncAPI spec JSON.
func (*AsyncAPIAggregator) MergedSpecMap ¶
func (aa *AsyncAPIAggregator) MergedSpecMap() map[string]any
MergedSpecMap returns the merged spec as a map.
func (*AsyncAPIAggregator) Refresh ¶
func (aa *AsyncAPIAggregator) Refresh(ctx context.Context)
Refresh fetches all upstream AsyncAPI specs and rebuilds the merged spec. Its span is a child of whatever span ctx carries.
func (*AsyncAPIAggregator) RefreshDetached ¶
func (aa *AsyncAPIAggregator) RefreshDetached(ctx context.Context)
RefreshDetached is Refresh for a caller that doesn't wait for it. The refresh starts a trace of its own, linked to ctx's span.
func (*AsyncAPIAggregator) SetMetrics ¶
func (aa *AsyncAPIAggregator) SetMetrics(m *observability.Metrics)
SetMetrics sets where the aggregator records the duration of each refresh. Nil records none. Call it before Start.
func (*AsyncAPIAggregator) SpecPath ¶
func (aa *AsyncAPIAggregator) SpecPath() string
SpecPath returns the configured endpoint path for the aggregated AsyncAPI spec.
func (*AsyncAPIAggregator) Start ¶
func (aa *AsyncAPIAggregator) Start(ctx context.Context)
Start begins the periodic spec refresh loop and subscribes to service change events for reactive refresh. The refreshes it runs are each the root of their own trace.
type AsyncAPIConfig ¶
type AsyncAPIConfig struct {
// Enabled turns on/off the AsyncAPI aggregation feature
Enabled bool `json:"enabled" yaml:"enabled"`
// Path is the endpoint path to serve the aggregated AsyncAPI spec
Path string `json:"path" yaml:"path"`
// Title is the title for the aggregated spec
Title string `json:"title" yaml:"title"`
// Description is the description for the aggregated spec
Description string `json:"description" yaml:"description"`
// Version is the version for the aggregated spec
Version string `json:"version" yaml:"version"`
// RefreshInterval is how often to re-fetch upstream specs
RefreshInterval time.Duration `json:"refreshInterval" yaml:"refresh_interval"`
// FetchTimeout is the timeout for fetching a single upstream spec
FetchTimeout time.Duration `json:"fetchTimeout" yaml:"fetch_timeout"`
// ExcludeServices is a list of service names to exclude from aggregation
ExcludeServices []string `json:"excludeServices,omitempty" yaml:"exclude_services"`
}
AsyncAPIConfig holds configuration for the AsyncAPI aggregation feature.
func DefaultAsyncAPIConfig ¶
func DefaultAsyncAPIConfig() AsyncAPIConfig
DefaultAsyncAPIConfig returns defaults for AsyncAPI aggregation.
type AuthOverride ¶
type AuthOverride struct {
SkipAuth bool `json:"skipAuth,omitempty"`
Scopes []string `json:"scopes,omitempty"`
}
AuthOverride holds per-route auth overrides from FARP RouteDescriptor.
type CacheOverride ¶
type CacheOverride struct {
Enabled bool `json:"enabled"`
TTL time.Duration `json:"ttl,omitempty"`
VaryBy []string `json:"varyBy,omitempty"`
}
CacheOverride holds per-route cache overrides from FARP RouteDescriptor.
type DiscoveredService ¶
type DiscoveredService struct {
Name string `json:"name"`
Version string `json:"version"`
Address string `json:"address"`
Port int `json:"port"`
Protocols []string `json:"protocols"`
SchemaTypes []string `json:"schemaTypes"`
Capabilities []string `json:"capabilities"`
Healthy bool `json:"healthy"`
Metadata map[string]string `json:"metadata,omitempty"`
RouteCount int `json:"routeCount"`
DiscoveredAt time.Time `json:"discoveredAt"`
}
DiscoveredService represents a service found via FARP/discovery.
type DiscoveryConfig ¶
type DiscoveryConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
PollInterval time.Duration `json:"pollInterval" yaml:"poll_interval"`
WatchMode bool `json:"watchMode" yaml:"watch_mode"`
ServiceFilters []ServiceFilter `json:"serviceFilters,omitempty" yaml:"service_filters"`
AutoPrefix bool `json:"autoPrefix" yaml:"auto_prefix"`
PrefixTemplate string `json:"prefixTemplate,omitempty" yaml:"prefix_template"`
StripPrefix bool `json:"stripPrefix" yaml:"strip_prefix"`
// PrefixOverrides allows overriding the route prefix for specific services.
// The key is the service name (case-insensitive) and the value is the
// prefix to use. An empty string "" means mount at root (no prefix).
//
// Example: {"twinos": ""} mounts twinos at / instead of /twinos.
// Example: {"twinos": "/api"} mounts twinos at /api instead of /twinos.
//
// This takes precedence over AutoPrefix, PrefixTemplate, and the FARP
// manifest routing strategy.
PrefixOverrides map[string]string `json:"prefixOverrides,omitempty" yaml:"prefix_overrides"`
// FetchTimeout is the timeout for HTTP requests such as fetching
// FARP manifests from discovered services. Defaults to 10s.
FetchTimeout time.Duration `json:"fetchTimeout,omitempty" yaml:"fetch_timeout"`
// RemovalGracePeriod is how long to keep routes for a service that has
// disappeared from ListServices before actually removing them. This
// handles transient mDNS/discovery backend issues. Defaults to 60s.
RemovalGracePeriod time.Duration `json:"removalGracePeriod,omitempty" yaml:"removal_grace_period"`
// PushInstanceTTL is the time-to-live for push-registered service instances.
// If a pushed instance does not re-register within this duration, it is
// automatically evicted. Set to 0 to disable TTL (instances persist until
// explicitly deregistered). Defaults to 0 (disabled).
PushInstanceTTL time.Duration `json:"pushInstanceTTL,omitempty" yaml:"push_instance_ttl"`
}
DiscoveryConfig holds FARP auto-discovery settings.
type DiscoveryDebugInfo ¶
type DiscoveryDebugInfo struct {
ServiceNames []string `json:"service_names"`
Instances map[string][]*ServiceInstanceInfo `json:"instances"`
Config DiscoveryConfig `json:"config"`
Error string `json:"error,omitempty"`
}
DiscoveryDebugInfo contains diagnostic data from a discovery probe.
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.
type ExtensionPathFilter ¶
type ExtensionPathFilter struct {
// ServiceName is the name of a single service to filter (e.g., "portal").
// For filtering multiple services with the same rules, use ServiceNames.
// At least one of ServiceName or ServiceNames must be set.
ServiceName string `json:"serviceName,omitempty" yaml:"service_name"`
// ServiceNames lists multiple service names this filter applies to.
// This allows a single filter definition to cover several services
// (e.g., ["portal", "twinos", "admin-api"]).
ServiceNames []string `json:"serviceNames,omitempty" yaml:"service_names"`
// KnownExtensions lists ALL extension names loaded by this service.
// Any path segment matching a known extension triggers filtering.
// This handles both direct mounts (/{ext}/...) and nested mounts
// (/api/{ext}/v1/...). Paths with no segment matching any known
// extension are treated as native service paths and always pass through.
KnownExtensions []string `json:"knownExtensions" yaml:"known_extensions"`
// AllowedExtensions lists which of the known extensions should be
// included. All other known extensions are excluded.
// If empty and KnownExtensions is set, NO extension paths are included.
AllowedExtensions []string `json:"allowedExtensions,omitempty" yaml:"allowed_extensions"`
// ExcludePrefixes lists explicit upstream path prefixes to exclude.
// Use this for paths where the extension name does not appear as a
// path segment (e.g., "/v1/admin" for ctrlplane extension paths).
// Each entry must start with "/".
ExcludePrefixes []string `json:"excludePrefixes,omitempty" yaml:"exclude_prefixes"`
// IncludePrefixes lists explicit upstream path prefixes that should
// always be included, overriding both KnownExtensions and
// ExcludePrefixes. Use this to whitelist specific paths. Highest priority.
// Each entry must start with "/".
IncludePrefixes []string `json:"includePrefixes,omitempty" yaml:"include_prefixes"`
// BlockTraffic controls whether the gateway also blocks proxy traffic
// to excluded extension paths (returns 403), not just hides them from
// the OpenAPI spec. Default: false.
BlockTraffic bool `json:"blockTraffic" yaml:"block_traffic"`
}
ExtensionPathFilter defines per-service extension path filtering. When a service loads Forge extensions (e.g., "cortex", "dispatch"), their endpoints appear in the service's API under extension-specific base paths (e.g., /cortex/..., /api/dispatch/v1/...). This filter controls which extension paths the gateway exposes.
func (*ExtensionPathFilter) AllServiceNames ¶
func (f *ExtensionPathFilter) AllServiceNames() []string
AllServiceNames returns the deduplicated list of service names this filter applies to (combining ServiceName and ServiceNames).
func (*ExtensionPathFilter) MatchesService ¶
func (f *ExtensionPathFilter) MatchesService(name string) bool
MatchesService reports whether this filter applies to the given service name. It checks both the singular ServiceName and the ServiceNames list (case-insensitive).
type FARPServiceDiscovery ¶
type FARPServiceDiscovery = farpdiscovery.ServiceDiscovery
FARPServiceDiscovery is FARP's native service discovery interface. This is the preferred way to provide discovery backends to the gateway.
type FARPServiceInstance ¶
type FARPServiceInstance = farpdiscovery.ServiceInstance
FARPServiceInstance is FARP's native service instance type.
type FetchedSchema ¶
type FetchedSchema struct {
// Schema is the parsed schema content.
Schema map[string]any
// SchemaType is the type of the schema (openapi, asyncapi, etc.).
SchemaType farp.SchemaType
// ServiceName is the service that owns this schema.
ServiceName string
// SpecURL is the URL the schema was fetched from (empty for inline schemas).
SpecURL string
// FetchedAt is when the schema was retrieved.
FetchedAt time.Time
// Error is non-empty if the fetch failed.
Error string
// Healthy indicates whether the schema was successfully retrieved.
Healthy bool
// PathCount is the number of paths in the schema (for OpenAPI).
PathCount int
}
FetchedSchema holds the result of fetching a schema from a descriptor.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager integrates FARP and service discovery for automatic route generation.
func NewManager ¶
func NewManager( config DiscoveryConfig, logger forge.Logger, rm RouteRegistry, discService DiscoveryService, ) *Manager
NewManager creates a new service discovery integration.
func (*Manager) BuildPrefix ¶
BuildPrefix builds the route prefix for a service name. The service name is normalized to lowercase kebab-case for URL friendliness. PrefixOverrides take precedence over AutoPrefix and PrefixTemplate.
func (*Manager) DebugDiscovery ¶
func (sd *Manager) DebugDiscovery(ctx context.Context) *DiscoveryDebugInfo
DebugDiscovery performs a one-shot discovery probe and returns raw results without modifying any routes. Useful for diagnosing mDNS issues.
func (*Manager) DeregisterService ¶
DeregisterService removes a previously pushed service and all its routes.
func (*Manager) DiscoveredServices ¶
func (sd *Manager) DiscoveredServices() []*DiscoveredService
DiscoveredServices returns all discovered services.
func (*Manager) GetInstanceChecksum ¶
GetInstanceChecksum returns the routes_checksum and schema count for a service instance. Used by the heartbeat handler for reconciliation.
func (*Manager) GetServicePrefix ¶
GetServicePrefix returns the resolved route prefix for a discovered service. It checks in order: PrefixOverrides → cached FARP prefix → BuildPrefix.
func (*Manager) OnServiceChange ¶
func (sd *Manager) OnServiceChange(fn ServiceChangeHook) func()
OnServiceChange registers a callback that fires when a service is registered or deregistered. This allows dependent components (e.g., the OpenAPI aggregator) to react immediately to topology changes. Returns an unsubscribe function that removes the listener.
func (*Manager) RegisterService ¶
func (sd *Manager) RegisterService(ctx context.Context, info *ServiceInstanceInfo) error
RegisterService accepts a pushed service registration and immediately processes it to generate routes. This is called by the gateway's HTTP handler when a service pushes its registration info.
func (*Manager) ServiceManifest ¶
func (sd *Manager) ServiceManifest(name string) *farp.SchemaManifest
ServiceManifest returns the cached FARP manifest for a specific service.
func (*Manager) ServiceManifests ¶
func (sd *Manager) ServiceManifests() map[string]*farp.SchemaManifest
ServiceManifests returns a copy of all cached FARP manifests.
func (*Manager) SetManifest ¶
func (sd *Manager) SetManifest(serviceName string, manifest *farp.SchemaManifest)
SetManifest stores a pre-fetched manifest for a service, so that processService uses it instead of making an HTTP fetch. This supports inline manifests in the FARP v1 push registration protocol.
func (*Manager) SetMetrics ¶
func (sd *Manager) SetMetrics(m *observability.Metrics)
SetMetrics sets where discovery records the duration of each pass. Nil records none. Call it before Start.
type OpenAPIAggregator ¶
type OpenAPIAggregator struct {
// contains filtered or unexported fields
}
OpenAPIAggregator fetches, caches, and merges OpenAPI specs from all discovered upstream services (via FARP metadata). It exposes:
- A unified merged OpenAPI spec combining all service paths under gateway prefixes
- Per-service OpenAPI specs fetched and cached from upstream endpoints
- A Swagger UI for browsing the aggregated spec
Schema fetching uses the `farp.openapi` metadata key set by the discovery extension's SchemaPublisher. The aggregator periodically refreshes specs and supports on-demand refresh.
func NewAggregator ¶
func NewAggregator(config OpenAPIConfig, logger forge.Logger, rm RouteRegistry, disc *Manager) *OpenAPIAggregator
NewAggregator creates a new OpenAPI aggregator.
func (*OpenAPIAggregator) HandleGatewaySpec ¶
func (oa *OpenAPIAggregator) HandleGatewaySpec(ctx forge.Context) error
HandleGatewaySpec serves an OpenAPI spec containing only the gateway's own admin API routes (route management, stats, discovery, etc.). This is separate from the aggregated upstream service spec.
func (*OpenAPIAggregator) HandleMergedSpec ¶
func (oa *OpenAPIAggregator) HandleMergedSpec(ctx forge.Context) error
HandleMergedSpec serves the aggregated OpenAPI spec as JSON.
func (*OpenAPIAggregator) HandleRefresh ¶
func (oa *OpenAPIAggregator) HandleRefresh(ctx forge.Context) error
HandleRefresh triggers an immediate spec refresh.
func (*OpenAPIAggregator) HandleServiceList ¶
func (oa *OpenAPIAggregator) HandleServiceList(ctx forge.Context) error
HandleServiceList returns a summary of all services with their OpenAPI spec status.
func (*OpenAPIAggregator) HandleServiceSpec ¶
func (oa *OpenAPIAggregator) HandleServiceSpec(ctx forge.Context) error
HandleServiceSpec serves the OpenAPI spec for a specific service.
func (*OpenAPIAggregator) HandleSwaggerUI ¶
func (oa *OpenAPIAggregator) HandleSwaggerUI(ctx forge.Context) error
HandleSwaggerUI serves a Swagger UI page for the aggregated spec. Deprecated: Use SwaggerUIHandler with an explicit spec URL instead.
func (*OpenAPIAggregator) LastRefresh ¶
func (oa *OpenAPIAggregator) LastRefresh() time.Time
LastRefresh returns the time of the last spec refresh.
func (*OpenAPIAggregator) MergedSpec ¶
func (oa *OpenAPIAggregator) MergedSpec() []byte
MergedSpec returns the pre-serialized merged OpenAPI spec JSON.
func (*OpenAPIAggregator) MergedSpecMap ¶
func (oa *OpenAPIAggregator) MergedSpecMap() map[string]any
MergedSpecMap returns the merged spec as a map.
func (*OpenAPIAggregator) Refresh ¶
func (oa *OpenAPIAggregator) Refresh(ctx context.Context)
Refresh fetches all upstream OpenAPI specs and rebuilds the merged spec. Its span is a child of whatever span ctx carries.
func (*OpenAPIAggregator) RefreshDetached ¶
func (oa *OpenAPIAggregator) RefreshDetached(ctx context.Context)
RefreshDetached is Refresh for a caller that doesn't wait for it, such as a request handler that answers before the refresh is done. The refresh starts a trace of its own, linked to ctx's span, instead of hanging off a span that ends first.
func (*OpenAPIAggregator) ServiceSpec ¶
func (oa *OpenAPIAggregator) ServiceSpec(serviceName string) *ServiceOpenAPISpec
ServiceSpec returns the cached spec for a specific service.
func (*OpenAPIAggregator) ServiceSpecs ¶
func (oa *OpenAPIAggregator) ServiceSpecs() map[string]*ServiceOpenAPISpec
ServiceSpecs returns all cached service specs.
func (*OpenAPIAggregator) SetMetrics ¶
func (oa *OpenAPIAggregator) SetMetrics(m *observability.Metrics)
SetMetrics sets where the aggregator records the duration of each refresh. Nil records none. Call it before Start.
func (*OpenAPIAggregator) SpecPath ¶
func (oa *OpenAPIAggregator) SpecPath() string
SpecPath returns the configured endpoint path for the aggregated OpenAPI spec.
func (*OpenAPIAggregator) Start ¶
func (oa *OpenAPIAggregator) Start(ctx context.Context)
Start begins the periodic spec refresh loop and subscribes to service change events for reactive refresh. The refreshes it runs are each the root of their own trace.
func (*OpenAPIAggregator) SwaggerUIHandler ¶
func (oa *OpenAPIAggregator) SwaggerUIHandler(specURL string) forge.Handler
SwaggerUIHandler returns a handler that serves a Swagger UI page pointing to the given spec URL. Use this to create handlers at different paths that all point to the correct aggregated spec location.
func (*OpenAPIAggregator) UIPath ¶
func (oa *OpenAPIAggregator) UIPath() string
UIPath returns the configured endpoint path for the Swagger UI.
type OpenAPIConfig ¶
type OpenAPIConfig struct {
// Enabled turns on/off the OpenAPI aggregation feature
Enabled bool `json:"enabled" yaml:"enabled"`
// Path is the endpoint path to serve the aggregated OpenAPI spec
Path string `json:"path" yaml:"path"`
// UIPath is the endpoint path to serve the Swagger UI
UIPath string `json:"uiPath" yaml:"ui_path"`
// Title is the title for the aggregated spec
Title string `json:"title" yaml:"title"`
// Description is the description for the aggregated spec
Description string `json:"description" yaml:"description"`
// Version is the version for the aggregated spec
Version string `json:"version" yaml:"version"`
// RefreshInterval is how often to re-fetch upstream specs
RefreshInterval time.Duration `json:"refreshInterval" yaml:"refresh_interval"`
// FetchTimeout is the timeout for fetching a single upstream spec
FetchTimeout time.Duration `json:"fetchTimeout" yaml:"fetch_timeout"`
// StripServicePrefix controls whether service prefixes are included in paths
StripServicePrefix bool `json:"stripServicePrefix" yaml:"strip_service_prefix"`
// MergeStrategy controls how conflicting paths are handled:
// "prefix" (default) - prefix all paths with /{serviceName}
// "flat" - merge paths as-is, last wins on conflict
MergeStrategy string `json:"mergeStrategy" yaml:"merge_strategy"`
// IncludeGatewayRoutes includes the gateway's own admin routes in the spec
IncludeGatewayRoutes bool `json:"includeGatewayRoutes" yaml:"include_gateway_routes"`
// ExcludeServices is a list of service names to exclude from aggregation
ExcludeServices []string `json:"excludeServices,omitempty" yaml:"exclude_services"`
// ContactName is the contact name for the spec info
ContactName string `json:"contactName,omitempty" yaml:"contact_name"`
// ContactEmail is the contact email for the spec info
ContactEmail string `json:"contactEmail,omitempty" yaml:"contact_email"`
// EnableRootDocs registers the aggregated spec and Swagger UI at root-level
// paths (/openapi.json and /docs) in addition to the dashboard-prefixed paths.
// Use this when the gateway should be the primary API documentation surface.
EnableRootDocs bool `json:"enableRootDocs" yaml:"enable_root_docs"`
// RootUIPath is the root-level Swagger UI path (default: "/docs").
// Only used when EnableRootDocs is true.
RootUIPath string `json:"rootUiPath,omitempty" yaml:"root_ui_path"`
// EnableGatewayDocs serves the gateway's own admin API documentation
// at the dashboard-prefixed swagger path (e.g., /gateway/swagger).
// Disabled by default.
EnableGatewayDocs bool `json:"enableGatewayDocs" yaml:"enable_gateway_docs"`
// DisableServiceTags disables automatic per-service tag creation and
// per-operation tag injection in the merged spec. When true, the
// aggregator will not add service-name tags to operations or create
// top-level service tags. Existing tags from upstream specs are preserved.
DisableServiceTags bool `json:"disableServiceTags,omitempty" yaml:"disable_service_tags"`
// ServiceTagOnly replaces all upstream operation tags with just the
// service-name tag. When true, existing tags from upstream specs are
// stripped and only the service-level tag remains on each operation.
// The top-level tags array will only contain service tags.
// This option is ignored when DisableServiceTags is true.
ServiceTagOnly bool `json:"serviceTagOnly,omitempty" yaml:"service_tag_only"`
// ExtensionFilters defines per-service extension path filtering rules.
// When a service loads Forge extensions, their paths appear as
// /{extension-name}/... in the service's OpenAPI spec. These filters
// control which extension paths are exposed through the gateway.
ExtensionFilters []ExtensionPathFilter `json:"extensionFilters,omitempty" yaml:"extension_filters"`
}
OpenAPIConfig holds configuration for the OpenAPI aggregation feature.
func DefaultOpenAPIConfig ¶
func DefaultOpenAPIConfig() OpenAPIConfig
DefaultOpenAPIConfig returns defaults for OpenAPI aggregation.
type RateLimitOverride ¶
type RateLimitOverride struct {
RequestsPerSec float64 `json:"requestsPerSec,omitempty"`
Burst int `json:"burst,omitempty"`
PerClient bool `json:"perClient,omitempty"`
}
RateLimitOverride holds per-route rate limit overrides from FARP RouteDescriptor.
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"`
Protocol RouteProtocol `json:"protocol"`
Source RouteSource `json:"source"`
ServiceName string `json:"serviceName,omitempty"`
Priority int `json:"priority"`
Enabled bool `json:"enabled"`
UpdatedAt time.Time `json:"updatedAt"`
// Per-route overrides from FARP RouteDescriptor (nil = use global defaults).
Timeout *TimeoutOverride `json:"timeout,omitempty"`
RateLimit *RateLimitOverride `json:"rateLimit,omitempty"`
Cache *CacheOverride `json:"cache,omitempty"`
Auth *AuthOverride `json:"auth,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
Route represents a configured gateway route (local copy of the root type).
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 adds a new route to the table.
AddRoute(route *Route) error
// RemoveRoute removes a single route by ID.
RemoveRoute(id string) error
// UpdateRoute updates an existing route.
UpdateRoute(route *Route) error
// GetRoute returns a route by ID.
GetRoute(id string) (*Route, bool)
// RemoveByServiceName removes all routes for a service.
RemoveByServiceName(serviceName string)
// ListRoutes returns all routes.
ListRoutes() []*Route
}
RouteRegistry is the interface for route management operations used by the discovery package. This avoids importing the root bastion package.
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 SchemaFetcher ¶
type SchemaFetcher struct {
// contains filtered or unexported fields
}
SchemaFetcher resolves raw schema content from FARP SchemaDescriptors. It supports inline schemas (embedded in manifests) and HTTP-located schemas, with retry logic and size limits.
func NewSchemaFetcher ¶
func NewSchemaFetcher(httpClient *http.Client, logger forge.Logger) *SchemaFetcher
NewSchemaFetcher creates a new schema fetcher with the given HTTP client and logger.
func (*SchemaFetcher) FetchFromURL ¶
func (sf *SchemaFetcher) FetchFromURL(ctx context.Context, specURL, serviceName string) *FetchedSchema
FetchFromURL fetches a schema directly from a URL (for non-FARP services that only have flat metadata keys like farp.openapi).
func (*SchemaFetcher) FetchSchema ¶
func (sf *SchemaFetcher) FetchSchema(ctx context.Context, desc farp.SchemaDescriptor, serviceName string) *FetchedSchema
FetchSchema resolves a schema from a SchemaDescriptor, checking inline first then falling back to HTTP. Returns the parsed JSON schema.
type ServiceChangeHook ¶
ServiceChangeHook is called when a service is registered or deregistered. serviceName identifies the service; registered is true for registrations, false for deregistrations.
type ServiceFilter ¶
type ServiceFilter struct {
IncludeNames []string `json:"includeNames,omitempty" yaml:"include_names"`
ExcludeNames []string `json:"excludeNames,omitempty" yaml:"exclude_names"`
IncludeTags []string `json:"includeTags,omitempty" yaml:"include_tags"`
ExcludeTags []string `json:"excludeTags,omitempty" yaml:"exclude_tags"`
RequireMetadata map[string]string `json:"requireMetadata,omitempty" yaml:"require_metadata"`
}
ServiceFilter defines a filter for discovered services.
type ServiceInstanceInfo ¶
type ServiceInstanceInfo struct {
ID string
Name string
Version string
Address string
Port int
Tags []string
Metadata map[string]string
Healthy bool
}
ServiceInstanceInfo represents a discovered service instance.
func FARPInstanceToInfo ¶
func FARPInstanceToInfo(inst farpdiscovery.ServiceInstance) *ServiceInstanceInfo
FARPInstanceToInfo converts a FARP ServiceInstance to bastion's ServiceInstanceInfo.
func (*ServiceInstanceInfo) IsHealthy ¶
func (si *ServiceInstanceInfo) IsHealthy() bool
IsHealthy returns whether the instance is healthy.
func (*ServiceInstanceInfo) URL ¶
func (si *ServiceInstanceInfo) URL(scheme string) string
URL returns the full URL for the service instance.
type ServiceOpenAPISpec ¶
type ServiceOpenAPISpec struct {
ServiceName string `json:"serviceName"`
Version string `json:"version"`
SpecURL string `json:"specUrl"`
Spec map[string]any `json:"spec,omitempty"`
FetchedAt time.Time `json:"fetchedAt"`
Error string `json:"error,omitempty"`
Healthy bool `json:"healthy"`
PathCount int `json:"pathCount"`
}
ServiceOpenAPISpec holds a cached OpenAPI spec for a single upstream service.
type Target ¶
type Target struct {
ID string `json:"id"`
URL string `json:"url"`
Weight int `json:"weight"`
Healthy bool `json:"healthy"`
Tags []string `json:"tags,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}
Target represents an upstream service endpoint (local copy of the root type).