farp

package module
v0.0.0-...-ca67a76 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2025 License: MIT Imports: 11 Imported by: 0

README

FARP - Forge API Gateway Registration Protocol

Version: 1.0.0
Status: Draft Specification
Authors: Forge Core Team
Last Updated: 2025-11-01

Overview

FARP (Forge API Gateway Registration Protocol) is a protocol specification for enabling service instances to automatically register their API schemas, health information, and capabilities with API gateways and service meshes. It provides a standardized way for services to expose their contracts (OpenAPI, AsyncAPI, gRPC, GraphQL) and enable dynamic route configuration in API gateways.

Key Features

  • Schema-Aware Service Discovery: Services register with complete API contracts
  • Multi-Protocol Support: OpenAPI, AsyncAPI, gRPC, GraphQL, and extensible for future protocols
  • Dynamic Gateway Configuration: API gateways auto-configure routes based on registered schemas
  • Health & Telemetry Integration: Built-in health checks and metrics endpoints
  • Backend Agnostic: Works with Consul, etcd, Kubernetes, Eureka, and custom backends
  • Push & Pull Models: Flexible schema distribution strategies
  • Zero-Downtime Updates: Schema versioning and checksum validation

Repository Structure

farp/
├── README.md                    # This file - project overview
├── docs/
│   ├── SPECIFICATION.md         # Complete protocol specification
│   ├── ARCHITECTURE.md          # Architecture and design decisions
│   ├── IMPLEMENTATION_GUIDE.md  # Guide for implementers
│   └── GATEWAY_INTEGRATION.md   # Gateway integration guide
├── examples/
│   ├── basic/                   # Basic usage examples
│   ├── multi-protocol/          # Multi-protocol service example
│   └── gateway-client/          # Reference gateway client
├── types.go                     # Core protocol types
├── manifest.go                  # Schema manifest types
├── provider.go                  # Schema provider interface
├── registry.go                  # Schema registry interface
├── storage.go                   # Storage abstraction
└── version.go                   # Protocol version constants

Quick Start

Service Registration
import "github.com/xraph/forge/farp"

// Create schema manifest
manifest := &farp.SchemaManifest{
    Version:        farp.ProtocolVersion,
    ServiceName:    "user-service",
    ServiceVersion: "v1.2.3",
    InstanceID:     "user-service-abc123",
    Schemas: []farp.SchemaDescriptor{
        {
            Type:        farp.SchemaTypeOpenAPI,
            SpecVersion: "3.1.0",
            Location: farp.SchemaLocation{
                Type: farp.LocationTypeHTTP,
                URL:  "http://user-service:8080/openapi.json",
            },
        },
    },
    Capabilities: []string{"rest", "websocket"},
    Endpoints: farp.SchemaEndpoints{
        Health:   "/health",
        Metrics:  "/metrics",
        OpenAPI:  "/openapi.json",
    },
}

// Register with backend
registry.RegisterManifest(ctx, manifest)
Gateway Integration
import "github.com/xraph/forge/farp/gateway"

// Create gateway client
client := gateway.NewClient(backend)

// Watch for service schema changes
client.WatchServices(ctx, func(routes []gateway.ServiceRoute) {
    // Auto-configure gateway routes
    for _, route := range routes {
        gateway.AddRoute(route)
    }
})

Use Cases

  1. API Gateway Auto-Configuration: Gateways like Kong, Traefik, or Nginx automatically register routes based on service schemas
  2. Service Mesh Control Plane: Enable contract-aware routing and validation in service meshes
  3. Developer Portals: Auto-generate API documentation from registered schemas
  4. Multi-Protocol Systems: Unified discovery for REST, gRPC, GraphQL, and async protocols
  5. Contract Testing: Validate service contracts at deployment time
  6. Schema Versioning: Support multiple API versions with zero-downtime migrations

Protocol Status

  • ✅ Core protocol specification complete
  • ✅ Type definitions
  • 🚧 Reference implementation (in progress)
  • 🚧 Gateway client library (in progress)
  • ⏳ Community feedback and refinement

Documentation

Contributing

FARP is part of the Forge framework. Contributions are welcome! Please see the main Forge repository for contribution guidelines.

License

Apache License 2.0 - See LICENSE file in the Forge repository

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

View Source
const (
	// ProtocolVersion is the current FARP protocol version (semver)
	ProtocolVersion = "1.0.0"

	// ProtocolMajor is the major version
	ProtocolMajor = 1

	// ProtocolMinor is the minor version
	ProtocolMinor = 0

	// ProtocolPatch is the patch version
	ProtocolPatch = 0
)

Protocol version constants

Variables

View Source
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 is returned when the backend is unavailable
	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

func CalculateSchemaChecksum(schema interface{}) (string, error)

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

func IsCompatible(manifestVersion string) bool

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 ValidateSchemaDescriptor

func ValidateSchemaDescriptor(sd *SchemaDescriptor) error

ValidateSchemaDescriptor validates a schema descriptor

Types

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() interface{}
}

Application represents an application that can have schemas generated from it This is an abstraction to avoid direct dependency on Forge framework

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 interface{}) (string, error)

Hash calculates SHA256 hash of the schema

func (*BaseSchemaProvider) Serialize

func (p *BaseSchemaProvider) Serialize(schema interface{}) ([]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 interface{}) error

Validate validates the schema using custom validation function

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 EventType

type EventType string

EventType represents the type of change event

const (
	// EventTypeAdded indicates a resource was added
	EventTypeAdded EventType = "added"

	// EventTypeUpdated indicates a resource was updated
	EventTypeUpdated EventType = "updated"

	// EventTypeRemoved indicates a resource was removed
	EventTypeRemoved EventType = "removed"
)

func (EventType) String

func (et EventType) String() string

String returns the string representation of the event type

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 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, new *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

type ManifestError struct {
	ServiceName string
	InstanceID  string
	Err         error
}

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, 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) GetSchema

func (s *ManifestStorage) GetSchema(ctx context.Context, path string) (interface{}, error)

GetSchema retrieves a schema

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

func (*ManifestStorage) PutSchema

func (s *ManifestStorage) PutSchema(ctx context.Context, path string, schema interface{}) error

PutSchema stores a schema

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 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]interface{}

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

type SchemaCache interface {
	// Get retrieves a cached schema by hash
	Get(hash string) (interface{}, bool)

	// Set stores a schema in cache with its hash
	Set(hash string, schema interface{}) 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 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 interface{} `json:"inline_schema,omitempty"`

	// Integrity validation
	Hash string `json:"hash"` // SHA256 of schema content
	Size int64  `json:"size"` // Size in bytes
}

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 interface{}

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

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

	// 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) (interface{}, error)

	// Validate validates a generated schema for correctness
	Validate(schema interface{}) error

	// Hash calculates the SHA256 hash of a schema
	Hash(schema interface{}) (string, error)

	// Serialize converts schema to bytes for storage/transmission
	Serialize(schema interface{}) ([]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 interface{}) 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) (interface{}, 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"

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

func (*StorageHelper) GetJSON

func (h *StorageHelper) GetJSON(ctx context.Context, key string, target interface{}) error

GetJSON retrieves and deserializes a JSON value

func (*StorageHelper) PutJSON

func (h *StorageHelper) PutJSON(ctx context.Context, key string, value interface{}) error

PutJSON stores a JSON-serializable value

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

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

Directories

Path Synopsis
examples
basic command
providers
registry

Jump to

Keyboard shortcuts

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