gateway

package
v1.0.0-alpha.18 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package gateway provides bidirectional protocol bridging for SemStreams.

Gateway components enable external clients (HTTP, WebSocket, gRPC) to query and interact with the NATS-based SemStreams event bus using request/reply patterns.

Gateway vs Output

- Gateway: Bidirectional request/reply (External ↔ NATS ↔ External) - Output: Unidirectional push (NATS → External)

Architecture

Gateways translate between external protocols and NATS request/reply:

┌─────────────────┐
│  HTTP Client    │  GET /api/search/semantic?query=foo
└────────┬────────┘
         ↓
┌────────────────────────────────────────┐
│  ServiceManager (Port 8080)            │
│  /api-gateway/* → HTTPGateway handlers │
└────────┬───────────────────────────────┘
         ↓ NATS Request/Reply
┌────────────────────────────────────────┐
│  graph-processor Component             │
│  Subscribed to graph.query.semantic    │
└────────────────────────────────────────┘

Mutation Control

HTTP methods (GET, POST, PUT, DELETE) don't directly map to mutation semantics (e.g., POST is used for complex queries like semantic search). Mutation control should be enforced at the NATS subject/component level, not the HTTP gateway.

Protocol Support

Gateway implementations by protocol:

  • HTTP: REST/JSON request/reply (gateway/http/)
  • WebSocket: Bidirectional messaging (future)
  • gRPC: RPC request/reply (future)

Handler Registration

Gateways register HTTP handlers via ServiceManager's central HTTP server:

type Gateway interface {
    component.Discoverable
    RegisterHTTPHandlers(prefix string, mux *http.ServeMux)
}

ServiceManager discovers Gateway implementers and registers their handlers at startup using the component instance name as URL prefix.

Example Configuration

{
  "components": {
    "api-gateway": {
      "type": "gateway",
      "name": "http",
      "enabled": true,
      "config": {
        "routes": [
          {
            "path": "/search/semantic",
            "method": "POST",
            "nats_subject": "graph.query.semantic",
            "timeout": "5s"
          },
          {
            "path": "/entity/:id",
            "method": "GET",
            "nats_subject": "graph.query.entity",
            "timeout": "2s"
          }
        ]
      }
    }
  }
}

Usage

With the above configuration, external clients can query via HTTP:

# Semantic search
curl -X POST http://localhost:8080/api-gateway/search/semantic \
  -H "Content-Type: application/json" \
  -d '{"query": "emergency alert", "limit": 10}'

# Entity lookup
curl http://localhost:8080/api-gateway/entity/abc123

Security

Gateways support:

  • TLS encryption (via ServiceManager HTTP server)
  • CORS headers
  • Request timeout limits
  • Rate limiting (future)
  • Authentication/authorization (future)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// Routes defines external endpoint to NATS mappings
	Routes []RouteMapping `json:"routes" schema:"type:array,description:Route mappings,category:basic"`

	// EnableCORS enables CORS headers (default: false, requires explicit cors_origins)
	EnableCORS bool `json:"enable_cors" schema:"type:bool,description:Enable CORS,category:advanced"`

	// CORSOrigins lists allowed CORS origins (required when EnableCORS is true)
	// Use ["*"] for development only - production should specify exact origins
	// Example: ["https://app.example.com", "https://app-staging.example.com"]
	CORSOrigins []string `json:"cors_origins,omitempty" schema:"type:array,description:Allowed origins (required for CORS),category:advanced"`

	// MaxRequestSize limits request body size in bytes (default: 1MB)
	MaxRequestSize int64 `json:"max_request_size,omitempty" schema:"type:int,description:Max request size (bytes),category:advanced"`
}

Config holds configuration for gateway components

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns default gateway configuration

func (*Config) Validate

func (c *Config) Validate() error

Validate ensures the gateway configuration is valid

type Gateway

type Gateway interface {
	// Discoverable interface provides component metadata, ports, schema, health
	component.Discoverable

	// RegisterHTTPHandlers registers the gateway's HTTP routes with the
	// ServiceManager's central HTTP server.
	//
	// The prefix parameter is the URL path prefix for this gateway instance,
	// typically derived from the component instance name (e.g., "/api-gateway/").
	//
	// The mux parameter is ServiceManager's http.ServeMux where handlers are registered.
	//
	// Example registration:
	//   func (g *HTTPGateway) RegisterHTTPHandlers(prefix string, mux *http.ServeMux) {
	//       mux.HandleFunc(prefix + "search/semantic", g.handleSemanticSearch)
	//       mux.HandleFunc(prefix + "entity/:id", g.handleEntity)
	//   }
	RegisterHTTPHandlers(prefix string, mux *http.ServeMux)
}

Gateway defines the interface for protocol bridge components that enable external clients to interact with NATS-based services via request/reply.

Gateway components are bidirectional - they accept external requests, translate them to NATS requests, and return the NATS response to the client.

This differs from Output components which are unidirectional (NATS → External).

type HTTPHandler

type HTTPHandler interface {
	RegisterHTTPHandlers(prefix string, mux *http.ServeMux)
}

HTTPHandler is the interface for services/components that can register HTTP handlers with ServiceManager's central HTTP server.

This interface is used by ServiceManager to discover components that need HTTP endpoint exposure.

type OpenAPIProvider

type OpenAPIProvider interface {
	OpenAPISpec() *service.OpenAPISpec
}

OpenAPIProvider is an optional interface for gateways that can contribute their endpoint definitions to the OpenAPI specification.

Gateways with well-defined endpoints (like graph-gateway) implement this to document their HTTP API. Gateways with config-driven dynamic routes (like the generic http gateway) may skip this interface.

Example implementation:

func (g *GraphGateway) OpenAPISpec() *service.OpenAPISpec {
    return &service.OpenAPISpec{
        Paths: map[string]service.PathSpec{
            "/graphql": {POST: &service.OperationSpec{...}},
        },
    }
}

type RouteMapping

type RouteMapping struct {
	// Path is the HTTP route path (e.g., "/search/semantic", "/entity/:id")
	// Supports path parameters with colon notation (:id, :type)
	Path string `json:"path" schema:"type:string,description:HTTP route path,category:basic"`

	// Method is the HTTP method (GET, POST, PUT, DELETE)
	Method string `json:"method" schema:"type:string,description:HTTP method,category:basic"`

	// NATSSubject is the NATS subject to send requests to
	NATSSubject string `json:"nats_subject" schema:"type:string,description:NATS request subject,category:basic"`

	// TimeoutStr for NATS request/reply (default: "5s")
	TimeoutStr string `json:"timeout,omitempty" schema:"type:string,description:Request timeout,default:5s,category:advanced"`

	// Description for OpenAPI documentation
	Description string `json:"description,omitempty" schema:"type:string,description:Route description,category:advanced"`
	// contains filtered or unexported fields
}

RouteMapping defines how an external endpoint maps to a NATS subject

func (*RouteMapping) Timeout

func (r *RouteMapping) Timeout() time.Duration

Timeout returns the parsed timeout duration

func (*RouteMapping) Validate

func (r *RouteMapping) Validate() error

Validate ensures the route mapping is valid

Directories

Path Synopsis
Package graphgateway provides the graph-gateway component for exposing graph operations via HTTP.
Package graphgateway provides the graph-gateway component for exposing graph operations via HTTP.
Package http provides an HTTP gateway implementation for bridging REST APIs to NATS services.
Package http provides an HTTP gateway implementation for bridging REST APIs to NATS services.

Jump to

Keyboard shortcuts

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