Documentation
¶
Overview ¶
Package farp implements the Forge API Gateway Registration Protocol (FARP).
FARP is a protocol specification for enabling service instances to automatically register their API schemas, health information, and capabilities with API gateways and service meshes.
Overview ¶
FARP provides:
- Schema-aware service discovery (OpenAPI, AsyncAPI, gRPC, GraphQL)
- Dynamic gateway configuration based on registered schemas
- Multi-protocol support with extensibility
- Health and telemetry integration
- Backend-agnostic storage (Consul, etcd, Kubernetes, Redis, Memory)
- Push and pull models for schema distribution
- Zero-downtime schema updates with versioning
Basic Usage ¶
Creating a schema manifest:
manifest := farp.NewManifest("user-service", "v1.2.3", "instance-abc123")
manifest.AddSchema(farp.SchemaDescriptor{
Type: farp.SchemaTypeOpenAPI,
SpecVersion: "3.1.0",
Location: farp.SchemaLocation{
Type: farp.LocationTypeHTTP,
URL: "http://user-service:8080/openapi.json",
},
ContentType: "application/json",
})
manifest.AddCapability(farp.CapabilityREST.String())
manifest.Endpoints.Health = "/health"
manifest.UpdateChecksum()
Registering with a registry:
registry := memory.NewRegistry() err := registry.RegisterManifest(ctx, manifest)
Schema Providers ¶
Schema providers generate schemas from application code:
type MyProvider struct {
farp.BaseSchemaProvider
}
func (p *MyProvider) Generate(ctx context.Context, app farp.Application) (interface{}, error) {
// Generate schema from app
return schema, nil
}
farp.RegisterProvider(&MyProvider{})
Gateway Integration ¶
Gateways watch for schema changes:
registry.WatchManifests(ctx, "user-service", func(event *farp.ManifestEvent) {
if event.Type == farp.EventTypeAdded || event.Type == farp.EventTypeUpdated {
// Fetch schemas and reconfigure gateway routes
configureGatewayFromManifest(event.Manifest)
}
})
Protocol Version ¶
Current protocol version: 1.0.0
For full documentation, see: https://github.com/xraph/forge/tree/main/farp/docs
Index ¶
- Constants
- Variables
- func CalculateManifestChecksum(manifest *SchemaManifest) (string, error)
- func CalculateSchemaChecksum(schema any) (string, error)
- func HasProvider(schemaType SchemaType) bool
- func IsCompatible(manifestVersion string) bool
- func RegisterProvider(provider SchemaProvider)
- func TestConflictStrategy_String(t *testing.T)
- func ValidateInstanceMetadata(im *InstanceMetadata) error
- func ValidateRoutingConfig(rc *RoutingConfig) error
- func ValidateSchemaDescriptor(sd *SchemaDescriptor) error
- type AccessRule
- type Application
- type AsyncAPIMetadata
- type AuthConfig
- type AuthScheme
- type AuthType
- type BaseSchemaProvider
- func (p *BaseSchemaProvider) ContentType() string
- func (p *BaseSchemaProvider) Endpoint() string
- func (p *BaseSchemaProvider) Hash(schema any) (string, error)
- func (p *BaseSchemaProvider) Serialize(schema any) ([]byte, error)
- func (p *BaseSchemaProvider) SpecVersion() string
- func (p *BaseSchemaProvider) Type() SchemaType
- func (p *BaseSchemaProvider) Validate(schema any) error
- type BreakingChange
- type Capability
- type ChangeSeverity
- type ChangeType
- type CommunicationRoute
- type CommunicationRouteType
- type CompatibilityMode
- type CompositionConfig
- type ConflictStrategy
- type DataSensitivity
- type DeploymentMetadata
- type DeploymentStrategy
- type Deprecation
- type EventType
- type FederatedEntity
- type FetchOptions
- type GRPCMetadata
- type GraphQLFederation
- type GraphQLMetadata
- type HTTPCommunicationRoutes
- type InstanceMetadata
- type InstanceRole
- type InstanceStatus
- type LatencyProfile
- type LocationType
- type ManifestChangeHandler
- type ManifestDiff
- type ManifestError
- type ManifestEvent
- type ManifestStorage
- func (s *ManifestStorage) Delete(ctx context.Context, serviceName, instanceID string) error
- func (s *ManifestStorage) DeleteSchema(ctx context.Context, path string) error
- func (s *ManifestStorage) Get(ctx context.Context, serviceName, instanceID string) (*SchemaManifest, error)
- func (s *ManifestStorage) GetSchema(ctx context.Context, path string) (any, error)
- func (s *ManifestStorage) List(ctx context.Context, serviceName string) ([]*SchemaManifest, error)
- func (s *ManifestStorage) Put(ctx context.Context, manifest *SchemaManifest) error
- func (s *ManifestStorage) PutSchema(ctx context.Context, path string, schema any) error
- type MountStrategy
- type ORPCMetadata
- type OpenAPIMetadata
- type OpenAPIServer
- type PathRewrite
- type PollingConfig
- type ProtocolMetadata
- type ProviderRegistry
- type ProvidesRelation
- type PublishOptions
- type RegistryConfig
- type RequiresRelation
- type RetryConfig
- type RouteMetadata
- type RoutingConfig
- type ScalingProfile
- type SchemaCache
- type SchemaChangeDiff
- type SchemaChangeHandler
- type SchemaCompatibility
- type SchemaDescriptor
- type SchemaEndpoints
- type SchemaError
- type SchemaEvent
- type SchemaLocation
- type SchemaManifest
- func (m *SchemaManifest) AddCapability(capability string)
- func (m *SchemaManifest) AddSchema(descriptor SchemaDescriptor)
- func (m *SchemaManifest) Clone() *SchemaManifest
- func (m *SchemaManifest) GetSchema(schemaType SchemaType) (*SchemaDescriptor, bool)
- func (m *SchemaManifest) HasCapability(capability string) bool
- func (m *SchemaManifest) ToJSON() ([]byte, error)
- func (m *SchemaManifest) ToPrettyJSON() ([]byte, error)
- func (m *SchemaManifest) UpdateChecksum() error
- func (m *SchemaManifest) Validate() error
- type SchemaProvider
- type SchemaRegistry
- type SchemaType
- type ServerVariable
- type ServiceDependency
- type ServiceHints
- type SizeHint
- type StorageBackend
- type StorageEvent
- type StorageHelper
- type ValidationError
- type VersionInfo
- type WebhookConfig
- type WebhookEventType
Constants ¶
const ( // ProtocolVersion is the current FARP protocol version (semver) ProtocolVersion = "1.0.2" // ProtocolMajor is the major version ProtocolMajor = 1 // ProtocolMinor is the minor version ProtocolMinor = 0 // ProtocolPatch is the patch version ProtocolPatch = 2 )
Protocol version constants
Variables ¶
var ( // ErrManifestNotFound is returned when a schema manifest is not found. ErrManifestNotFound = errors.New("schema manifest not found") // ErrSchemaNotFound is returned when a schema is not found. ErrSchemaNotFound = errors.New("schema not found") // ErrInvalidManifest is returned when a manifest has invalid format. ErrInvalidManifest = errors.New("invalid manifest format") // ErrInvalidSchema is returned when a schema has invalid format. ErrInvalidSchema = errors.New("invalid schema format") // ErrSchemaToLarge is returned when a schema exceeds size limits. ErrSchemaToLarge = errors.New("schema exceeds size limit") // ErrChecksumMismatch is returned when a schema checksum doesn't match. ErrChecksumMismatch = errors.New("schema checksum mismatch") // ErrUnsupportedType is returned when a schema type is not supported. ErrUnsupportedType = errors.New("unsupported schema type") ErrBackendUnavailable = errors.New("backend unavailable") // ErrIncompatibleVersion is returned when protocol versions are incompatible. ErrIncompatibleVersion = errors.New("incompatible protocol version") // ErrInvalidLocation is returned when a schema location is invalid. ErrInvalidLocation = errors.New("invalid schema location") // ErrProviderNotFound is returned when a schema provider is not found. ErrProviderNotFound = errors.New("schema provider not found") // ErrRegistryNotConfigured is returned when no registry is configured. ErrRegistryNotConfigured = errors.New("schema registry not configured") // ErrSchemaFetchFailed is returned when schema fetch fails. ErrSchemaFetchFailed = errors.New("failed to fetch schema") // ErrValidationFailed is returned when schema validation fails. ErrValidationFailed = errors.New("schema validation failed") )
Common errors.
Functions ¶
func CalculateManifestChecksum ¶
func CalculateManifestChecksum(manifest *SchemaManifest) (string, error)
CalculateManifestChecksum calculates the SHA256 checksum of a manifest by combining all schema hashes in a deterministic order.
func CalculateSchemaChecksum ¶
CalculateSchemaChecksum calculates the SHA256 checksum of a schema.
func HasProvider ¶
func HasProvider(schemaType SchemaType) bool
HasProvider checks if a provider exists in the global registry.
func IsCompatible ¶
IsCompatible checks if a manifest version is compatible with this protocol version Compatible means the major version matches and the manifest's minor version is less than or equal to the protocol's minor version
func RegisterProvider ¶
func RegisterProvider(provider SchemaProvider)
RegisterProvider registers a schema provider globally.
func ValidateInstanceMetadata ¶
func ValidateInstanceMetadata(im *InstanceMetadata) error
ValidateInstanceMetadata validates instance metadata.
func ValidateRoutingConfig ¶
func ValidateRoutingConfig(rc *RoutingConfig) error
ValidateRoutingConfig validates routing configuration.
func ValidateSchemaDescriptor ¶
func ValidateSchemaDescriptor(sd *SchemaDescriptor) error
ValidateSchemaDescriptor validates a schema descriptor.
Types ¶
type AccessRule ¶
type AccessRule struct {
// Path pattern (glob or regex)
Path string `json:"path"`
// HTTP methods
Methods []string `json:"methods"`
// Required roles
Roles []string `json:"roles,omitempty"`
// Required permissions
Permissions []string `json:"permissions,omitempty"`
// Allow anonymous access
AllowAnonymous bool `json:"allow_anonymous,omitempty"`
}
AccessRule defines an access control rule.
type Application ¶
type Application interface {
// Name returns the application/service name
Name() string
// Version returns the application version
Version() string
// Routes returns route information for schema generation
// The actual type depends on the framework (e.g., []forge.RouteInfo)
Routes() any
}
Application represents an application that can have schemas generated from it This is an abstraction to avoid direct dependency on Forge framework.
type AsyncAPIMetadata ¶
type AsyncAPIMetadata struct {
// Message broker type
Protocol string `json:"protocol"` // "kafka", "amqp", "mqtt", "ws"
// Channel bindings
ChannelBindings map[string]any `json:"channel_bindings,omitempty"`
// Message bindings
MessageBindings map[string]any `json:"message_bindings,omitempty"`
}
AsyncAPIMetadata provides AsyncAPI-specific metadata.
type AuthConfig ¶
type AuthConfig struct {
// Authentication schemes supported by service
Schemes []AuthScheme `json:"schemes"`
// Required permissions/scopes
RequiredScopes []string `json:"required_scopes,omitempty"`
// Access control rules
AccessControl []AccessRule `json:"access_control,omitempty"`
// Token validation endpoint
TokenValidationURL string `json:"token_validation_url,omitempty"`
// Public (unauthenticated) routes
PublicRoutes []string `json:"public_routes,omitempty"`
}
AuthConfig provides authentication and authorization configuration.
type AuthScheme ¶
type AuthScheme struct {
// Scheme type
Type AuthType `json:"type"`
// Scheme configuration (varies by type)
Config map[string]any `json:"config,omitempty"`
}
AuthScheme describes an authentication scheme.
type AuthType ¶
type AuthType string
AuthType represents an authentication type.
const ( // AuthTypeBearer indicates Bearer token authentication (JWT, opaque). AuthTypeBearer AuthType = "bearer" // AuthTypeAPIKey indicates API key authentication. AuthTypeAPIKey AuthType = "apikey" // AuthTypeBasic indicates Basic authentication. AuthTypeBasic AuthType = "basic" // AuthTypeMTLS indicates Mutual TLS authentication. AuthTypeMTLS AuthType = "mtls" // AuthTypeOAuth2 indicates OAuth 2.0 authentication. AuthTypeOAuth2 AuthType = "oauth2" // AuthTypeOIDC indicates OpenID Connect authentication. AuthTypeOIDC AuthType = "oidc" // AuthTypeCustom indicates custom authentication scheme. AuthTypeCustom AuthType = "custom" )
type BaseSchemaProvider ¶
type BaseSchemaProvider struct {
// contains filtered or unexported fields
}
BaseSchemaProvider provides common functionality for schema providers.
func (*BaseSchemaProvider) ContentType ¶
func (p *BaseSchemaProvider) ContentType() string
ContentType returns the content type.
func (*BaseSchemaProvider) Endpoint ¶
func (p *BaseSchemaProvider) Endpoint() string
Endpoint returns the HTTP endpoint.
func (*BaseSchemaProvider) Hash ¶
func (p *BaseSchemaProvider) Hash(schema any) (string, error)
Hash calculates SHA256 hash of the schema.
func (*BaseSchemaProvider) Serialize ¶
func (p *BaseSchemaProvider) Serialize(schema any) ([]byte, error)
Serialize converts schema to JSON bytes.
func (*BaseSchemaProvider) SpecVersion ¶
func (p *BaseSchemaProvider) SpecVersion() string
SpecVersion returns the specification version.
func (*BaseSchemaProvider) Type ¶
func (p *BaseSchemaProvider) Type() SchemaType
Type returns the schema type.
func (*BaseSchemaProvider) Validate ¶
func (p *BaseSchemaProvider) Validate(schema any) error
Validate validates the schema using custom validation function.
type BreakingChange ¶
type BreakingChange struct {
// Type of breaking change
Type ChangeType `json:"type"`
// Path in schema (e.g., "/paths/users/get", "User.email")
Path string `json:"path"`
// Human-readable description
Description string `json:"description"`
// Severity level
Severity ChangeSeverity `json:"severity"`
// Migration instructions
Migration string `json:"migration,omitempty"`
}
BreakingChange describes a breaking change in a schema.
type Capability ¶
type Capability string
Capability represents a protocol capability.
const ( // CapabilityREST indicates REST API support. CapabilityREST Capability = "rest" // CapabilityGRPC indicates gRPC support. CapabilityGRPC Capability = "grpc" // CapabilityWebSocket indicates WebSocket support. CapabilityWebSocket Capability = "websocket" // CapabilitySSE indicates Server-Sent Events support. CapabilitySSE Capability = "sse" // CapabilityGraphQL indicates GraphQL support. CapabilityGraphQL Capability = "graphql" // CapabilityMQTT indicates MQTT support. CapabilityMQTT Capability = "mqtt" // CapabilityAMQP indicates AMQP support. CapabilityAMQP Capability = "amqp" )
func (Capability) String ¶
func (c Capability) String() string
String returns the string representation of the capability.
type ChangeSeverity ¶
type ChangeSeverity string
ChangeSeverity defines the severity of a schema change.
const ( // SeverityCritical indicates immediate breakage. SeverityCritical ChangeSeverity = "critical" // SeverityHigh indicates likely breakage. SeverityHigh ChangeSeverity = "high" // SeverityMedium indicates possible breakage. SeverityMedium ChangeSeverity = "medium" // SeverityLow indicates minimal risk. SeverityLow ChangeSeverity = "low" )
func (ChangeSeverity) String ¶
func (cs ChangeSeverity) String() string
String returns the string representation of the change severity.
type ChangeType ¶
type ChangeType string
ChangeType defines types of schema changes.
const ( // ChangeTypeFieldRemoved indicates a field was removed. ChangeTypeFieldRemoved ChangeType = "field_removed" // ChangeTypeFieldTypeChanged indicates a field type was changed. ChangeTypeFieldTypeChanged ChangeType = "field_type_changed" // ChangeTypeFieldRequired indicates a field became required. ChangeTypeFieldRequired ChangeType = "field_required" // ChangeTypeEndpointRemoved indicates an endpoint was removed. ChangeTypeEndpointRemoved ChangeType = "endpoint_removed" // ChangeTypeEndpointChanged indicates an endpoint was changed. ChangeTypeEndpointChanged ChangeType = "endpoint_changed" // ChangeTypeEnumValueRemoved indicates an enum value was removed. ChangeTypeEnumValueRemoved ChangeType = "enum_value_removed" // ChangeTypeMethodRemoved indicates a method was removed. ChangeTypeMethodRemoved ChangeType = "method_removed" )
func (ChangeType) String ¶
func (ct ChangeType) String() string
String returns the string representation of the change type.
type CommunicationRoute ¶
type CommunicationRoute struct {
// Route identifier
ID string `json:"id"`
// Route path
Path string `json:"path"`
// HTTP method
Method string `json:"method"`
// Route purpose/type
Type CommunicationRouteType `json:"type"`
// Description
Description string `json:"description,omitempty"`
// Request schema (JSON Schema, OpenAPI schema, etc.)
RequestSchema any `json:"request_schema,omitempty"`
// Response schema
ResponseSchema any `json:"response_schema,omitempty"`
// Authentication required
AuthRequired bool `json:"auth_required"`
// Idempotent operation
Idempotent bool `json:"idempotent"`
// Expected timeout
Timeout string `json:"timeout,omitempty"`
}
CommunicationRoute defines a communication route.
type CommunicationRouteType ¶
type CommunicationRouteType string
CommunicationRouteType defines the type of communication route.
const ( // RouteTypeControl indicates control plane operations. RouteTypeControl CommunicationRouteType = "control" // RouteTypeAdmin indicates admin operations. RouteTypeAdmin CommunicationRouteType = "admin" // RouteTypeManagement indicates management operations. RouteTypeManagement CommunicationRouteType = "management" // RouteTypeLifecycleStart indicates lifecycle start hook. RouteTypeLifecycleStart CommunicationRouteType = "lifecycle.start" // RouteTypeLifecycleStop indicates lifecycle stop hook. RouteTypeLifecycleStop CommunicationRouteType = "lifecycle.stop" // RouteTypeLifecycleReload indicates lifecycle reload hook. RouteTypeLifecycleReload CommunicationRouteType = "lifecycle.reload" // RouteTypeConfigUpdate indicates config update. RouteTypeConfigUpdate CommunicationRouteType = "config.update" // RouteTypeConfigQuery indicates config query. RouteTypeConfigQuery CommunicationRouteType = "config.query" // RouteTypeEventPoll indicates event polling. RouteTypeEventPoll CommunicationRouteType = "event.poll" // RouteTypeEventAck indicates event acknowledgment. RouteTypeEventAck CommunicationRouteType = "event.ack" // RouteTypeHealthCheck indicates health check. RouteTypeHealthCheck CommunicationRouteType = "health.check" // RouteTypeStatusQuery indicates status query. RouteTypeStatusQuery CommunicationRouteType = "status.query" // RouteTypeSchemaQuery indicates schema query. RouteTypeSchemaQuery CommunicationRouteType = "schema.query" // RouteTypeSchemaValidate indicates schema validation. RouteTypeSchemaValidate CommunicationRouteType = "schema.validate" // RouteTypeMetricsQuery indicates metrics query. RouteTypeMetricsQuery CommunicationRouteType = "metrics.query" // RouteTypeTracingExport indicates tracing export. RouteTypeTracingExport CommunicationRouteType = "tracing.export" // RouteTypeCustom indicates custom route type. RouteTypeCustom CommunicationRouteType = "custom" )
func (CommunicationRouteType) String ¶
func (crt CommunicationRouteType) String() string
String returns the string representation of the communication route type.
type CompatibilityMode ¶
type CompatibilityMode string
CompatibilityMode defines schema compatibility guarantees.
const ( // CompatibilityBackward indicates new schema can read data written by old schema. CompatibilityBackward CompatibilityMode = "backward" // CompatibilityForward indicates old schema can read data written by new schema. CompatibilityForward CompatibilityMode = "forward" // CompatibilityFull indicates both backward and forward compatible. CompatibilityFull CompatibilityMode = "full" // CompatibilityNone indicates breaking changes, no compatibility guaranteed. CompatibilityNone CompatibilityMode = "none" // CompatibilityBackwardTransitive indicates transitive backward compatibility across N versions. CompatibilityBackwardTransitive CompatibilityMode = "backward_transitive" // CompatibilityForwardTransitive indicates transitive forward compatibility across N versions. CompatibilityForwardTransitive CompatibilityMode = "forward_transitive" )
func (CompatibilityMode) String ¶
func (cm CompatibilityMode) String() string
String returns the string representation of the compatibility mode.
type CompositionConfig ¶
type CompositionConfig struct {
// Include this schema in merged/federated API documentation
IncludeInMerged bool `json:"include_in_merged"`
// Prefix for component schemas to avoid naming conflicts
// If empty, defaults to service name
ComponentPrefix string `json:"component_prefix,omitempty"`
// Tag prefix for operation tags
TagPrefix string `json:"tag_prefix,omitempty"`
// Operation ID prefix to avoid conflicts
OperationIDPrefix string `json:"operation_id_prefix,omitempty"`
// Conflict resolution strategy when paths/components collide
ConflictStrategy ConflictStrategy `json:"conflict_strategy"`
// Whether to preserve x-extensions from this schema
PreserveExtensions bool `json:"preserve_extensions"`
// Custom servers to use in merged spec (overrides service defaults)
CustomServers []OpenAPIServer `json:"custom_servers,omitempty"`
}
CompositionConfig defines how this schema should be composed with others.
type ConflictStrategy ¶
type ConflictStrategy string
ConflictStrategy defines how to handle conflicts during composition.
const ( // ConflictStrategyPrefix adds service prefix to conflicting items. ConflictStrategyPrefix ConflictStrategy = "prefix" // ConflictStrategyError fails composition on conflicts. ConflictStrategyError ConflictStrategy = "error" // ConflictStrategySkip skips conflicting items from this service. ConflictStrategySkip ConflictStrategy = "skip" // ConflictStrategyOverwrite overwrites existing with this service's version. ConflictStrategyOverwrite ConflictStrategy = "overwrite" // ConflictStrategyMerge attempts to merge conflicting schemas. ConflictStrategyMerge ConflictStrategy = "merge" )
func (ConflictStrategy) String ¶
func (cs ConflictStrategy) String() string
String returns the string representation of the conflict strategy.
type DataSensitivity ¶
type DataSensitivity string
DataSensitivity defines data sensitivity levels.
const ( // SensitivityPublic indicates public data. SensitivityPublic DataSensitivity = "public" // SensitivityInternal indicates internal data. SensitivityInternal DataSensitivity = "internal" // SensitivityConfidential indicates confidential data. SensitivityConfidential DataSensitivity = "confidential" // SensitivityPII indicates personally identifiable information. SensitivityPII DataSensitivity = "pii" // SensitivityPHI indicates protected health information. SensitivityPHI DataSensitivity = "phi" // SensitivityPCI indicates payment card industry data. SensitivityPCI DataSensitivity = "pci" )
func (DataSensitivity) String ¶
func (ds DataSensitivity) String() string
String returns the string representation of the data sensitivity.
type DeploymentMetadata ¶
type DeploymentMetadata struct {
// Deployment ID
DeploymentID string `json:"deployment_id"`
// Deployment strategy
Strategy DeploymentStrategy `json:"strategy"`
// Traffic percentage (0-100)
TrafficPercent int `json:"traffic_percent,omitempty"`
// Deployment stage
Stage string `json:"stage,omitempty"` // "canary", "rollout", "stable"
// Deployment time
DeployedAt int64 `json:"deployed_at"`
}
DeploymentMetadata provides information about a deployment.
type DeploymentStrategy ¶
type DeploymentStrategy string
DeploymentStrategy represents the deployment strategy.
const ( // DeploymentStrategyRolling indicates a rolling update deployment. DeploymentStrategyRolling DeploymentStrategy = "rolling" // DeploymentStrategyCanary indicates a canary deployment. DeploymentStrategyCanary DeploymentStrategy = "canary" // DeploymentStrategyBlueGreen indicates a blue-green deployment. DeploymentStrategyBlueGreen DeploymentStrategy = "blue_green" // DeploymentStrategyShadow indicates a shadow deployment. DeploymentStrategyShadow DeploymentStrategy = "shadow" // DeploymentStrategyRecreate indicates a recreate deployment. DeploymentStrategyRecreate DeploymentStrategy = "recreate" )
func (DeploymentStrategy) String ¶
func (ds DeploymentStrategy) String() string
String returns the string representation of the deployment strategy.
type Deprecation ¶
type Deprecation struct {
// Path in schema
Path string `json:"path"`
// Deprecation date (ISO 8601)
DeprecatedAt string `json:"deprecated_at"`
// Planned removal date (ISO 8601)
RemovalDate string `json:"removal_date,omitempty"`
// Replacement recommendation
Replacement string `json:"replacement,omitempty"`
// Migration guide
Migration string `json:"migration,omitempty"`
// Reason for deprecation
Reason string `json:"reason,omitempty"`
}
Deprecation describes a deprecated schema element.
type FederatedEntity ¶
type FederatedEntity struct {
// Type name
TypeName string `json:"type_name"`
// Key fields for entity resolution
KeyFields []string `json:"key_fields"`
// Fields owned by this service
Fields []string `json:"fields"`
// Resolvable via this subgraph
Resolvable bool `json:"resolvable"`
}
FederatedEntity describes a federated GraphQL entity.
type FetchOptions ¶
type FetchOptions struct {
// UseCache indicates whether to use cache
UseCache bool
// ValidateChecksum verifies schema hash after fetch
ValidateChecksum bool
// ExpectedHash is the expected SHA256 hash (for validation)
ExpectedHash string
// Timeout for fetch operation (0 = no timeout)
Timeout int64
}
FetchOptions provides options for fetching schemas.
type GRPCMetadata ¶
type GRPCMetadata struct {
// Reflection enabled
ReflectionEnabled bool `json:"reflection_enabled"`
// Package names
Packages []string `json:"packages"`
// Service names
Services []string `json:"services"`
// gRPC-Web support
GRPCWebEnabled bool `json:"grpc_web_enabled,omitempty"`
// gRPC-Web protocol
GRPCWebProtocol string `json:"grpc_web_protocol,omitempty"` // "grpc-web", "grpc-web-text"
// Server streaming support
ServerStreamingEnabled bool `json:"server_streaming_enabled,omitempty"`
// Client streaming support
ClientStreamingEnabled bool `json:"client_streaming_enabled,omitempty"`
// Bidirectional streaming support
BidirectionalStreamingEnabled bool `json:"bidirectional_streaming_enabled,omitempty"`
}
GRPCMetadata provides gRPC-specific metadata.
type GraphQLFederation ¶
type GraphQLFederation struct {
// Federation version
Version string `json:"version"` // "v1", "v2"
// Subgraph name
SubgraphName string `json:"subgraph_name"`
// Entity types owned by this service
Entities []FederatedEntity `json:"entities,omitempty"`
// External types from other services
Extends []string `json:"extends,omitempty"`
// Provides relationships
Provides []ProvidesRelation `json:"provides,omitempty"`
// Requires relationships
Requires []RequiresRelation `json:"requires,omitempty"`
}
GraphQLFederation provides GraphQL Federation metadata.
type GraphQLMetadata ¶
type GraphQLMetadata struct {
// Federation configuration
Federation *GraphQLFederation `json:"federation,omitempty"`
// Subscription support
SubscriptionsEnabled bool `json:"subscriptions_enabled,omitempty"`
// Subscription protocol
SubscriptionProtocol string `json:"subscription_protocol,omitempty"` // "graphql-ws", "graphql-transport-ws"
// Query complexity limits
ComplexityLimit int `json:"complexity_limit,omitempty"`
// Query depth limits
DepthLimit int `json:"depth_limit,omitempty"`
}
GraphQLMetadata provides GraphQL-specific metadata.
type HTTPCommunicationRoutes ¶
type HTTPCommunicationRoutes struct {
// Service exposes these routes for gateway to call
ServiceRoutes []CommunicationRoute `json:"service_routes,omitempty"`
// Gateway exposes these routes for service to call
GatewayRoutes []CommunicationRoute `json:"gateway_routes,omitempty"`
// Polling configuration if HTTP polling is used
Polling *PollingConfig `json:"polling,omitempty"`
}
HTTPCommunicationRoutes defines HTTP communication routes.
type InstanceMetadata ¶
type InstanceMetadata struct {
// Instance address (host:port)
Address string `json:"address"`
// Instance region/zone/datacenter
Region string `json:"region,omitempty"`
Zone string `json:"zone,omitempty"`
// Instance labels for selection
Labels map[string]string `json:"labels,omitempty"`
// Instance weight for load balancing (0-100, default: 100)
Weight int `json:"weight,omitempty"`
// Instance status
Status InstanceStatus `json:"status"`
// Instance role in deployment
Role InstanceRole `json:"role,omitempty"`
// Canary/blue-green deployment metadata
Deployment *DeploymentMetadata `json:"deployment,omitempty"`
// Instance start time
StartedAt int64 `json:"started_at"` // Unix timestamp
// Expected schema checksum (for validation)
ExpectedSchemaChecksum string `json:"expected_schema_checksum,omitempty"`
}
InstanceMetadata provides information about a service instance.
type InstanceRole ¶
type InstanceRole string
InstanceRole represents the role of an instance in a deployment.
const ( // InstanceRolePrimary indicates the instance is primary/production. InstanceRolePrimary InstanceRole = "primary" // InstanceRoleCanary indicates the instance is a canary deployment. InstanceRoleCanary InstanceRole = "canary" // InstanceRoleBlue indicates the instance is part of blue deployment. InstanceRoleBlue InstanceRole = "blue" // InstanceRoleGreen indicates the instance is part of green deployment. InstanceRoleGreen InstanceRole = "green" // InstanceRoleShadow indicates the instance is a shadow deployment. InstanceRoleShadow InstanceRole = "shadow" )
func (InstanceRole) String ¶
func (ir InstanceRole) String() string
String returns the string representation of the instance role.
type InstanceStatus ¶
type InstanceStatus string
InstanceStatus represents the status of a service instance.
const ( // InstanceStatusStarting indicates the instance is starting. InstanceStatusStarting InstanceStatus = "starting" // InstanceStatusHealthy indicates the instance is healthy. InstanceStatusHealthy InstanceStatus = "healthy" // InstanceStatusDegraded indicates the instance is degraded. InstanceStatusDegraded InstanceStatus = "degraded" // InstanceStatusUnhealthy indicates the instance is unhealthy. InstanceStatusUnhealthy InstanceStatus = "unhealthy" // InstanceStatusDraining indicates the instance is draining connections. InstanceStatusDraining InstanceStatus = "draining" // InstanceStatusStopping indicates the instance is stopping. InstanceStatusStopping InstanceStatus = "stopping" )
func (InstanceStatus) String ¶
func (is InstanceStatus) String() string
String returns the string representation of the instance status.
type LatencyProfile ¶
type LatencyProfile struct {
// Median latency
P50 string `json:"p50,omitempty"` // e.g., "10ms"
// 95th percentile
P95 string `json:"p95,omitempty"` // e.g., "50ms"
// 99th percentile
P99 string `json:"p99,omitempty"` // e.g., "100ms"
// 99.9th percentile
P999 string `json:"p999,omitempty"` // e.g., "500ms"
}
LatencyProfile describes expected latency characteristics.
type LocationType ¶
type LocationType string
LocationType represents how schemas can be retrieved.
const ( // LocationTypeHTTP means fetch schema via HTTP GET. LocationTypeHTTP LocationType = "http" // LocationTypeRegistry means fetch schema from backend KV store. LocationTypeRegistry LocationType = "registry" // LocationTypeInline means schema is embedded in the manifest. LocationTypeInline LocationType = "inline" )
func (LocationType) IsValid ¶
func (lt LocationType) IsValid() bool
IsValid checks if the location type is valid.
func (LocationType) String ¶
func (lt LocationType) String() string
String returns the string representation of the location type.
type ManifestChangeHandler ¶
type ManifestChangeHandler func(event *ManifestEvent)
ManifestChangeHandler is called when a manifest changes.
type ManifestDiff ¶
type ManifestDiff struct {
// SchemasAdded are schemas present in new but not in old
SchemasAdded []SchemaDescriptor
// SchemasRemoved are schemas present in old but not in new
SchemasRemoved []SchemaDescriptor
// SchemasChanged are schemas present in both but with different hashes
SchemasChanged []SchemaChangeDiff
// CapabilitiesAdded are new capabilities
CapabilitiesAdded []string
// CapabilitiesRemoved are removed capabilities
CapabilitiesRemoved []string
// EndpointsChanged indicates if endpoints changed
EndpointsChanged bool
}
ManifestDiff represents the difference between two manifests.
func DiffManifests ¶
func DiffManifests(old, newManifest *SchemaManifest) *ManifestDiff
DiffManifests compares two manifests and returns the differences.
func (*ManifestDiff) HasChanges ¶
func (d *ManifestDiff) HasChanges() bool
HasChanges returns true if there are any changes.
type ManifestError ¶
ManifestError represents a manifest-specific error.
func (*ManifestError) Error ¶
func (e *ManifestError) Error() string
func (*ManifestError) Unwrap ¶
func (e *ManifestError) Unwrap() error
type ManifestEvent ¶
type ManifestEvent struct {
// Type of event (added, updated, removed)
Type EventType
// The manifest that changed
Manifest *SchemaManifest
// Timestamp of the event (Unix timestamp)
Timestamp int64
}
ManifestEvent represents a manifest change event.
type ManifestStorage ¶
type ManifestStorage struct {
// contains filtered or unexported fields
}
ManifestStorage provides high-level operations for manifest storage.
func NewManifestStorage ¶
func NewManifestStorage( backend StorageBackend, namespace string, compressionThreshold int64, maxSize int64, ) *ManifestStorage
NewManifestStorage creates a new manifest storage.
func (*ManifestStorage) Delete ¶
func (s *ManifestStorage) Delete(ctx context.Context, serviceName, instanceID string) error
Delete removes a manifest.
func (*ManifestStorage) DeleteSchema ¶
func (s *ManifestStorage) DeleteSchema(ctx context.Context, path string) error
DeleteSchema removes a schema.
func (*ManifestStorage) Get ¶
func (s *ManifestStorage) Get(ctx context.Context, serviceName, instanceID string) (*SchemaManifest, error)
Get retrieves a manifest.
func (*ManifestStorage) List ¶
func (s *ManifestStorage) List(ctx context.Context, serviceName string) ([]*SchemaManifest, error)
List lists all manifests for a service.
func (*ManifestStorage) Put ¶
func (s *ManifestStorage) Put(ctx context.Context, manifest *SchemaManifest) error
Put stores a manifest.
type MountStrategy ¶
type MountStrategy string
MountStrategy defines how routes are mounted in the gateway.
const ( // MountStrategyRoot merges service routes to gateway root (no prefix). MountStrategyRoot MountStrategy = "root" // MountStrategyInstance mounts under /instance-id/* (default). MountStrategyInstance MountStrategy = "instance" // MountStrategyService mounts under /service-name/*. MountStrategyService MountStrategy = "service" // MountStrategyVersioned mounts under /service-name/version/*. MountStrategyVersioned MountStrategy = "versioned" // MountStrategyCustom mounts under custom base path. MountStrategyCustom MountStrategy = "custom" // MountStrategySubdomain mounts on subdomain: service.gateway.com. MountStrategySubdomain MountStrategy = "subdomain" )
func (MountStrategy) IsValid ¶
func (ms MountStrategy) IsValid() bool
IsValid checks if the mount strategy is valid.
func (MountStrategy) String ¶
func (ms MountStrategy) String() string
String returns the string representation of the mount strategy.
type ORPCMetadata ¶
type ORPCMetadata struct {
// Batch operations supported
BatchEnabled bool `json:"batch_enabled,omitempty"`
// Streaming procedures
StreamingProcedures []string `json:"streaming_procedures,omitempty"`
}
ORPCMetadata provides oRPC-specific metadata.
type OpenAPIMetadata ¶
type OpenAPIMetadata struct {
// x-extension fields to preserve
Extensions map[string]any `json:"extensions,omitempty"`
// Server variables for URL templating
ServerVariables map[string]ServerVariable `json:"server_variables,omitempty"`
// Default security schemes
DefaultSecurity []string `json:"default_security,omitempty"`
// Composition settings for schema merging
Composition *CompositionConfig `json:"composition,omitempty"`
}
OpenAPIMetadata provides OpenAPI-specific metadata.
type OpenAPIServer ¶
type OpenAPIServer struct {
// Server URL
URL string `json:"url"`
// Server description
Description string `json:"description,omitempty"`
// Server variables
Variables map[string]ServerVariable `json:"variables,omitempty"`
}
OpenAPIServer represents an OpenAPI server definition.
type PathRewrite ¶
type PathRewrite struct {
// Pattern to match (regex)
Pattern string `json:"pattern"`
// Replacement string
Replacement string `json:"replacement"`
}
PathRewrite defines a path rewriting rule.
type PollingConfig ¶
type PollingConfig struct {
// Polling interval
Interval string `json:"interval"` // Duration string
// Polling timeout
Timeout string `json:"timeout,omitempty"`
// Long polling support
LongPolling bool `json:"long_polling,omitempty"`
// Long polling timeout
LongPollingTimeout string `json:"long_polling_timeout,omitempty"`
}
PollingConfig defines polling configuration.
type ProtocolMetadata ¶
type ProtocolMetadata struct {
// GraphQL-specific metadata
GraphQL *GraphQLMetadata `json:"graphql,omitempty"`
// gRPC-specific metadata
GRPC *GRPCMetadata `json:"grpc,omitempty"`
// OpenAPI-specific metadata
OpenAPI *OpenAPIMetadata `json:"openapi,omitempty"`
// AsyncAPI-specific metadata
AsyncAPI *AsyncAPIMetadata `json:"asyncapi,omitempty"`
// oRPC-specific metadata
ORPC *ORPCMetadata `json:"orpc,omitempty"`
}
ProtocolMetadata provides protocol-specific metadata.
type ProviderRegistry ¶
type ProviderRegistry struct {
// contains filtered or unexported fields
}
ProviderRegistry manages registered schema providers.
func NewProviderRegistry ¶
func NewProviderRegistry() *ProviderRegistry
NewProviderRegistry creates a new provider registry.
func (*ProviderRegistry) Get ¶
func (r *ProviderRegistry) Get(schemaType SchemaType) (SchemaProvider, bool)
Get retrieves a provider by schema type.
func (*ProviderRegistry) Has ¶
func (r *ProviderRegistry) Has(schemaType SchemaType) bool
Has checks if a provider exists for a schema type.
func (*ProviderRegistry) List ¶
func (r *ProviderRegistry) List() []SchemaType
List returns all registered schema types.
func (*ProviderRegistry) Register ¶
func (r *ProviderRegistry) Register(provider SchemaProvider)
Register registers a schema provider.
type ProvidesRelation ¶
type ProvidesRelation struct {
// Field path
Field string `json:"field"`
// Provided fields
Fields []string `json:"fields"`
}
ProvidesRelation describes a GraphQL @provides relationship.
type PublishOptions ¶
type PublishOptions struct {
// Compress indicates whether to compress the schema
Compress bool
// TTL is time-to-live in seconds (0 = no expiry)
TTL int64
// OverwriteExisting allows overwriting existing schemas
OverwriteExisting bool
}
PublishOptions provides options for publishing schemas.
type RegistryConfig ¶
type RegistryConfig struct {
// Backend type (consul, etcd, kubernetes, redis, memory)
Backend string
// Namespace/prefix for keys (optional)
Namespace string
// Backend-specific configuration (varies by implementation)
BackendConfig map[string]any
// Max schema size in bytes (default: 1MB)
MaxSchemaSize int64
// Enable compression for schemas > threshold
CompressionThreshold int64
// TTL for schemas (0 = no expiry)
TTL int64
}
RegistryConfig holds configuration for a schema registry.
func DefaultRegistryConfig ¶
func DefaultRegistryConfig() RegistryConfig
DefaultRegistryConfig returns default registry configuration.
type RequiresRelation ¶
type RequiresRelation struct {
// Field path
Field string `json:"field"`
// Required fields
Fields []string `json:"fields"`
}
RequiresRelation describes a GraphQL @requires relationship.
type RetryConfig ¶
type RetryConfig struct {
// Maximum retry attempts
MaxAttempts int `json:"max_attempts"`
// Initial retry delay
InitialDelay string `json:"initial_delay"` // Duration string
// Maximum retry delay
MaxDelay string `json:"max_delay"`
// Backoff multiplier
Multiplier float64 `json:"multiplier"`
}
RetryConfig defines retry configuration.
type RouteMetadata ¶
type RouteMetadata struct {
// Operation/route identifier
OperationID string `json:"operation_id"`
// Path pattern
Path string `json:"path"`
// HTTP method (for REST/OpenAPI)
Method string `json:"method,omitempty"`
// Is operation idempotent?
Idempotent bool `json:"idempotent"`
// Recommended timeout for this operation
TimeoutHint string `json:"timeout_hint,omitempty"`
// Operation cost/complexity (1-10 scale)
Cost int `json:"cost,omitempty"`
// Is result cacheable?
Cacheable bool `json:"cacheable,omitempty"`
// Cache TTL hint
CacheTTL string `json:"cache_ttl,omitempty"`
// Data sensitivity level
Sensitivity DataSensitivity `json:"sensitivity,omitempty"`
// Expected response size
ResponseSize SizeHint `json:"response_size,omitempty"`
// Rate limit hint (requests per second)
RateLimitHint int `json:"rate_limit_hint,omitempty"`
}
RouteMetadata provides per-route metadata.
type RoutingConfig ¶
type RoutingConfig struct {
// Mounting strategy
Strategy MountStrategy `json:"strategy"`
// Base path for mounting (used with path-based strategies)
BasePath string `json:"base_path,omitempty"`
// Subdomain for mounting (used with subdomain strategy)
Subdomain string `json:"subdomain,omitempty"`
// Path rewriting rules
Rewrite []PathRewrite `json:"rewrite,omitempty"`
// Strip prefix before forwarding to service
StripPrefix bool `json:"strip_prefix,omitempty"`
// Priority for conflict resolution (higher = higher priority)
Priority int `json:"priority,omitempty"`
// Tags for route grouping and filtering
Tags []string `json:"tags,omitempty"`
}
RoutingConfig provides gateway route mounting configuration.
type ScalingProfile ¶
type ScalingProfile struct {
// Auto-scaling enabled
AutoScale bool `json:"auto_scale"`
// Minimum instances
MinInstances int `json:"min_instances,omitempty"`
// Maximum instances
MaxInstances int `json:"max_instances,omitempty"`
// Target CPU utilization
TargetCPU float64 `json:"target_cpu,omitempty"` // 0.0-1.0
// Target memory utilization
TargetMemory float64 `json:"target_memory,omitempty"` // 0.0-1.0
}
ScalingProfile describes scaling characteristics.
type SchemaCache ¶
type SchemaCache interface {
// Get retrieves a cached schema by hash
Get(hash string) (any, bool)
// Set stores a schema in cache with its hash
Set(hash string, schema any) error
// Delete removes a schema from cache
Delete(hash string) error
// Clear removes all cached schemas
Clear() error
// Size returns the number of cached schemas
Size() int
}
SchemaCache provides caching for fetched schemas.
type SchemaChangeDiff ¶
type SchemaChangeDiff struct {
Type SchemaType
OldHash string
NewHash string
}
SchemaChangeDiff represents a changed schema.
type SchemaChangeHandler ¶
type SchemaChangeHandler func(event *SchemaEvent)
SchemaChangeHandler is called when a schema changes.
type SchemaCompatibility ¶
type SchemaCompatibility struct {
// Compatibility mode
Mode CompatibilityMode `json:"mode"`
// Previous schema versions (for lineage tracking)
PreviousVersions []string `json:"previous_versions,omitempty"`
// Breaking changes from previous version
BreakingChanges []BreakingChange `json:"breaking_changes,omitempty"`
// Deprecation notices
Deprecations []Deprecation `json:"deprecations,omitempty"`
}
SchemaCompatibility provides schema compatibility metadata.
type SchemaDescriptor ¶
type SchemaDescriptor struct {
// Type of schema (openapi, asyncapi, grpc, graphql, etc.)
Type SchemaType `json:"type"`
// Specification version (e.g., "3.1.0" for OpenAPI, "3.0.0" for AsyncAPI)
SpecVersion string `json:"spec_version"`
// How to retrieve the schema
Location SchemaLocation `json:"location"`
// Content type (e.g., "application/json", "application/x-protobuf")
ContentType string `json:"content_type"`
// Optional: Inline schema for small schemas (< 100KB recommended)
InlineSchema any `json:"inline_schema,omitempty"`
// Integrity validation
Hash string `json:"hash"` // SHA256 of schema content
Size int64 `json:"size"` // Size in bytes
// Schema compatibility metadata
Compatibility *SchemaCompatibility `json:"compatibility,omitempty"`
// Protocol-specific metadata
Metadata *ProtocolMetadata `json:"metadata,omitempty"`
}
SchemaDescriptor describes a single API schema/contract.
type SchemaEndpoints ¶
type SchemaEndpoints struct {
// Health check endpoint (required)
// Example: "/health" or "/healthz"
Health string `json:"health"`
// Prometheus metrics endpoint (optional)
// Example: "/metrics"
Metrics string `json:"metrics,omitempty"`
// OpenAPI spec endpoint (optional)
// Example: "/openapi.json"
OpenAPI string `json:"openapi,omitempty"`
// AsyncAPI spec endpoint (optional)
// Example: "/asyncapi.json"
AsyncAPI string `json:"asyncapi,omitempty"`
// Whether gRPC server reflection is enabled
GRPCReflection bool `json:"grpc_reflection,omitempty"`
// GraphQL introspection endpoint (optional)
// Example: "/graphql"
GraphQL string `json:"graphql,omitempty"`
}
SchemaEndpoints provides URLs for service introspection.
type SchemaError ¶
type SchemaError struct {
Type SchemaType
Path string
Err error
}
SchemaError represents a schema-specific error.
func (*SchemaError) Error ¶
func (e *SchemaError) Error() string
func (*SchemaError) Unwrap ¶
func (e *SchemaError) Unwrap() error
type SchemaEvent ¶
type SchemaEvent struct {
// Type of event (added, updated, removed)
Type EventType
// Path where the schema is stored
Path string
// The schema content (nil for removed events)
Schema any
// Timestamp of the event (Unix timestamp)
Timestamp int64
}
SchemaEvent represents a schema change event.
type SchemaLocation ¶
type SchemaLocation struct {
// Location type (http, registry, inline)
Type LocationType `json:"type"`
// HTTP URL (if Type == HTTP)
// Example: "http://user-service:8080/openapi.json"
URL string `json:"url,omitempty"`
// Registry path in backend KV store (if Type == Registry)
// Example: "/schemas/user-service/v1/openapi"
RegistryPath string `json:"registry_path,omitempty"`
// HTTP headers for authentication (if Type == HTTP)
// Example: {"Authorization": "Bearer token"}
Headers map[string]string `json:"headers,omitempty"`
}
SchemaLocation describes where and how to fetch a schema.
func (*SchemaLocation) Validate ¶
func (sl *SchemaLocation) Validate() error
Validate checks if the schema location is valid.
type SchemaManifest ¶
type SchemaManifest struct {
// Version of the FARP protocol (semver)
Version string `json:"version"`
// Service identity
ServiceName string `json:"service_name"`
ServiceVersion string `json:"service_version"`
InstanceID string `json:"instance_id"`
// Instance metadata
Instance *InstanceMetadata `json:"instance,omitempty"`
// Schemas exposed by this instance
Schemas []SchemaDescriptor `json:"schemas"`
// Capabilities/protocols supported (e.g., ["rest", "grpc", "websocket"])
Capabilities []string `json:"capabilities"`
// Endpoints for introspection and health
Endpoints SchemaEndpoints `json:"endpoints"`
// Routing configuration for gateway federation
Routing RoutingConfig `json:"routing"`
// Authentication configuration
Auth AuthConfig `json:"auth,omitempty"`
// Webhook for bidirectional communication
Webhook WebhookConfig `json:"webhook,omitempty"`
// Service operational hints (non-binding)
Hints *ServiceHints `json:"hints,omitempty"`
// Change tracking
UpdatedAt int64 `json:"updated_at"` // Unix timestamp
Checksum string `json:"checksum"` // SHA256 of all schemas combined
}
SchemaManifest describes all API contracts for a service instance.
func FromJSON ¶
func FromJSON(data []byte) (*SchemaManifest, error)
FromJSON deserializes a manifest from JSON.
func NewManifest ¶
func NewManifest(serviceName, serviceVersion, instanceID string) *SchemaManifest
NewManifest creates a new schema manifest with default values.
func (*SchemaManifest) AddCapability ¶
func (m *SchemaManifest) AddCapability(capability string)
AddCapability adds a capability to the manifest.
func (*SchemaManifest) AddSchema ¶
func (m *SchemaManifest) AddSchema(descriptor SchemaDescriptor)
AddSchema adds a schema descriptor to the manifest.
func (*SchemaManifest) Clone ¶
func (m *SchemaManifest) Clone() *SchemaManifest
Clone creates a deep copy of the manifest.
func (*SchemaManifest) GetSchema ¶
func (m *SchemaManifest) GetSchema(schemaType SchemaType) (*SchemaDescriptor, bool)
GetSchema retrieves a schema descriptor by type.
func (*SchemaManifest) HasCapability ¶
func (m *SchemaManifest) HasCapability(capability string) bool
HasCapability checks if the manifest includes a specific capability.
func (*SchemaManifest) ToJSON ¶
func (m *SchemaManifest) ToJSON() ([]byte, error)
ToJSON serializes the manifest to JSON.
func (*SchemaManifest) ToPrettyJSON ¶
func (m *SchemaManifest) ToPrettyJSON() ([]byte, error)
ToPrettyJSON serializes the manifest to pretty-printed JSON.
func (*SchemaManifest) UpdateChecksum ¶
func (m *SchemaManifest) UpdateChecksum() error
UpdateChecksum recalculates the manifest checksum based on all schema hashes.
func (*SchemaManifest) Validate ¶
func (m *SchemaManifest) Validate() error
Validate validates the manifest for correctness.
type SchemaProvider ¶
type SchemaProvider interface {
// Type returns the schema type this provider generates
Type() SchemaType
// Generate generates a schema from the application
// Returns the schema as interface{} (typically map[string]interface{} or struct)
Generate(ctx context.Context, app Application) (any, error)
// Validate validates a generated schema for correctness
Validate(schema any) error
// Hash calculates the SHA256 hash of a schema
Hash(schema any) (string, error)
// Serialize converts schema to bytes for storage/transmission
Serialize(schema any) ([]byte, error)
// Endpoint returns the HTTP endpoint where the schema is served
// Returns empty string if not served via HTTP
Endpoint() string
// SpecVersion returns the specification version (e.g., "3.1.0" for OpenAPI)
SpecVersion() string
// ContentType returns the content type for the schema
ContentType() string
}
SchemaProvider generates schemas from application code Implementations generate protocol-specific schemas (OpenAPI, AsyncAPI, gRPC, GraphQL).
func GetProvider ¶
func GetProvider(schemaType SchemaType) (SchemaProvider, bool)
GetProvider retrieves a provider from the global registry.
type SchemaRegistry ¶
type SchemaRegistry interface {
// RegisterManifest registers a new schema manifest
RegisterManifest(ctx context.Context, manifest *SchemaManifest) error
// GetManifest retrieves a schema manifest by instance ID
GetManifest(ctx context.Context, instanceID string) (*SchemaManifest, error)
// UpdateManifest updates an existing schema manifest
UpdateManifest(ctx context.Context, manifest *SchemaManifest) error
// DeleteManifest removes a schema manifest
DeleteManifest(ctx context.Context, instanceID string) error
// ListManifests lists all manifests for a service name
// Returns empty slice if serviceName is empty (list all services)
ListManifests(ctx context.Context, serviceName string) ([]*SchemaManifest, error)
// PublishSchema stores a schema in the registry
// path is the registry path (e.g., "/schemas/user-service/v1/openapi")
// schema is the schema content (typically map[string]interface{} or struct)
PublishSchema(ctx context.Context, path string, schema any) error
// FetchSchema retrieves a schema from the registry
// Returns the schema as interface{} (must be type-asserted by caller)
FetchSchema(ctx context.Context, path string) (any, error)
// DeleteSchema removes a schema from the registry
DeleteSchema(ctx context.Context, path string) error
// WatchManifests watches for manifest changes for a service
// onChange is called when a manifest is added, updated, or removed
// Returns an error if watch setup fails
// The watch continues until context is cancelled
WatchManifests(ctx context.Context, serviceName string, onChange ManifestChangeHandler) error
// WatchSchemas watches for schema changes at a specific path
// onChange is called when the schema at path changes
WatchSchemas(ctx context.Context, path string, onChange SchemaChangeHandler) error
// Close closes the registry and cleans up resources
Close() error
// Health checks if the registry backend is healthy
Health(ctx context.Context) error
}
SchemaRegistry manages schema manifests and schemas Implementations store data in various backends (Consul, etcd, Kubernetes, Redis, etc.)
type SchemaType ¶
type SchemaType string
SchemaType represents supported schema/protocol types.
const ( // SchemaTypeOpenAPI represents OpenAPI/Swagger specifications. SchemaTypeOpenAPI SchemaType = "openapi" // SchemaTypeAsyncAPI represents AsyncAPI specifications. SchemaTypeAsyncAPI SchemaType = "asyncapi" // SchemaTypeGRPC represents gRPC protocol buffer definitions. SchemaTypeGRPC SchemaType = "grpc" // SchemaTypeGraphQL represents GraphQL Schema Definition Language. SchemaTypeGraphQL SchemaType = "graphql" // SchemaTypeORPC represents oRPC (OpenAPI-based RPC) specifications. SchemaTypeORPC SchemaType = "orpc" // SchemaTypeThrift represents Apache Thrift IDL (future support). SchemaTypeThrift SchemaType = "thrift" // SchemaTypeAvro represents Apache Avro schemas (future support). SchemaTypeAvro SchemaType = "avro" // SchemaTypeCustom represents custom/proprietary schema types. SchemaTypeCustom SchemaType = "custom" )
func ListProviders ¶
func ListProviders() []SchemaType
ListProviders returns all registered schema types from the global registry.
func (SchemaType) IsValid ¶
func (st SchemaType) IsValid() bool
IsValid checks if the schema type is valid.
func (SchemaType) String ¶
func (st SchemaType) String() string
String returns the string representation of the schema type.
type ServerVariable ¶
type ServerVariable struct {
// Default value
Default string `json:"default"`
// Enum values
Enum []string `json:"enum,omitempty"`
// Description
Description string `json:"description,omitempty"`
}
ServerVariable describes an OpenAPI server variable.
type ServiceDependency ¶
type ServiceDependency struct {
// Service name
ServiceName string `json:"service_name"`
// Schema type
SchemaType SchemaType `json:"schema_type"`
// Version requirement (semver range)
VersionRange string `json:"version_range,omitempty"`
// Is dependency critical for operation?
Critical bool `json:"critical"`
// Types/operations used from dependency
UsedOperations []string `json:"used_operations,omitempty"`
}
ServiceDependency describes a service dependency.
type ServiceHints ¶
type ServiceHints struct {
// Recommended timeout for operations
RecommendedTimeout string `json:"recommended_timeout,omitempty"`
// Expected latency profile
ExpectedLatency *LatencyProfile `json:"expected_latency,omitempty"`
// Scaling characteristics
Scaling *ScalingProfile `json:"scaling,omitempty"`
// Dependencies on other services
Dependencies []ServiceDependency `json:"dependencies,omitempty"`
}
ServiceHints provides operational hints for the gateway.
type StorageBackend ¶
type StorageBackend interface {
// Put stores a value at the given key
Put(ctx context.Context, key string, value []byte) error
// Get retrieves a value by key
// Returns ErrSchemaNotFound if key doesn't exist
Get(ctx context.Context, key string) ([]byte, error)
// Delete removes a key
Delete(ctx context.Context, key string) error
// List lists all keys with the given prefix
List(ctx context.Context, prefix string) ([]string, error)
// Watch watches for changes to keys with the given prefix
// Returns a channel that receives change events
Watch(ctx context.Context, prefix string) (<-chan StorageEvent, error)
// Close closes the backend connection
Close() error
}
StorageBackend provides low-level key-value storage operations This abstracts the underlying storage mechanism (Consul KV, etcd, Redis, etc.)
type StorageEvent ¶
type StorageEvent struct {
// Type of event
Type EventType
// Key that changed
Key string
// Value (nil for delete events)
Value []byte
}
StorageEvent represents a storage change event.
type StorageHelper ¶
type StorageHelper struct {
// contains filtered or unexported fields
}
StorageHelper provides utility functions for storage operations.
func NewStorageHelper ¶
func NewStorageHelper(backend StorageBackend, compressionThreshold, maxSize int64) *StorageHelper
NewStorageHelper creates a new storage helper.
type ValidationError ¶
ValidationError represents a validation error.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type VersionInfo ¶
type VersionInfo struct {
// Version is the full semver string
Version string `json:"version"`
// Major version number
Major int `json:"major"`
// Minor version number
Minor int `json:"minor"`
// Patch version number
Patch int `json:"patch"`
}
VersionInfo provides version information about the protocol
func GetVersion ¶
func GetVersion() VersionInfo
GetVersion returns the current protocol version information
type WebhookConfig ¶
type WebhookConfig struct {
// Webhook endpoint on service for gateway notifications
ServiceWebhook string `json:"service_webhook,omitempty"`
// Webhook endpoint on gateway for service notifications
GatewayWebhook string `json:"gateway_webhook,omitempty"`
// Webhook secret for HMAC signature verification
Secret string `json:"secret,omitempty"`
// Event types service wants to receive from gateway
SubscribeEvents []WebhookEventType `json:"subscribe_events,omitempty"`
// Event types service will send to gateway
PublishEvents []WebhookEventType `json:"publish_events,omitempty"`
// Retry configuration
Retry RetryConfig `json:"retry,omitempty"`
// HTTP-based communication routes (alternative to push webhooks)
HTTPRoutes *HTTPCommunicationRoutes `json:"http_routes,omitempty"`
}
WebhookConfig provides bidirectional communication configuration.
type WebhookEventType ¶
type WebhookEventType string
WebhookEventType defines types of webhook events.
const ( // EventSchemaUpdated indicates schema was updated. EventSchemaUpdated WebhookEventType = "schema.updated" // EventHealthChanged indicates health status changed. EventHealthChanged WebhookEventType = "health.changed" // EventInstanceScaling indicates instance scaling event. EventInstanceScaling WebhookEventType = "instance.scaling" // EventMaintenanceMode indicates maintenance mode event. EventMaintenanceMode WebhookEventType = "maintenance.mode" // EventRateLimitChanged indicates rate limit changed. EventRateLimitChanged WebhookEventType = "ratelimit.changed" // EventCircuitBreakerOpen indicates circuit breaker opened. EventCircuitBreakerOpen WebhookEventType = "circuit.breaker.open" // EventCircuitBreakerClosed indicates circuit breaker closed. EventCircuitBreakerClosed WebhookEventType = "circuit.breaker.closed" // EventConfigUpdated indicates config was updated. EventConfigUpdated WebhookEventType = "config.updated" // EventTrafficShift indicates traffic shift event. EventTrafficShift WebhookEventType = "traffic.shift" )
func (WebhookEventType) String ¶
func (wet WebhookEventType) String() string
String returns the string representation of the webhook event type.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
|
|
|
composition
command
Package main demonstrates OpenAPI schema composition with FARP
|
Package main demonstrates OpenAPI schema composition with FARP |
|
mixed-routing
command
Package main demonstrates mixed routing strategies in OpenAPI composition
|
Package main demonstrates mixed routing strategies in OpenAPI composition |
|
security-merge
command
Package main demonstrates security/auth handling in OpenAPI composition
|
Package main demonstrates security/auth handling in OpenAPI composition |
|
Package gateway provides a REFERENCE IMPLEMENTATION for API gateway integration with FARP.
|
Package gateway provides a REFERENCE IMPLEMENTATION for API gateway integration with FARP. |
|
providers
|
|
|
registry
|
|