The user wants a composable API gateway framework. Let me break down the requirements:
- Plugin Isolation: Plugins should run in isolated environments, preventing one plugin from crashing or affecting others
- Contract Enforcement: Define and enforce contracts between the gateway and plugins, ensuring type safety and interface compliance
- Automated Rollback: If a policy misconfiguration is detected, automatically rollback to a previous known-good state
Let me design this system with:
- Core Gateway: The main request router and handler
- Plugin System:
- WebAssembly-based isolation (or sandboxed execution)
- Plugin lifecycle management
- Communication via well-defined interfaces
- Contract System:
- Schema validation for requests/responses
- Type checking for plugin interfaces
- Version compatibility checks
- Policy Engine:
- Policy definitions (rate limiting, auth, transformation)
- Configuration validation
- Health monitoring
- Rollback System:
- State snapshots
- Change tracking
- Automatic rollback triggers
Let me create a comprehensive implementation in Go, as it's well-suited for infrastructure/gateway systems:
Key components:
Gateway: Main gateway struct
Plugin: Plugin interface and isolation
Contract: Contract definitions and enforcement
Policy: Policy configuration and validation
RollbackManager: Handles state snapshots and rollbacks
SnapshotStore: Stores configuration snapshots
I'll implement:
- Plugin isolation using a sandboxed executor
- Contract enforcement using JSON Schema and custom validators
- Canary deployments for policy changes
- Automatic rollback on error rate spikes
- Circuit breakers for plugin failures
Let me write comprehensive, production-quality code with proper error handling, logging, and metrics.
Composable API Gateway Framework
This is a comprehensive API gateway framework with plugin isolation, contract enforcement, and automated rollback capabilities.
Architecture Overview
┌─────────────────────────────────────────────────────────────────────┐
│ API GATEWAY FRAMEWORK │
├─────────────────────────────────────────────────────────────────────┤
│ ┌─────────────┐ ┌──────────────┐ ┌───────────────────────────┐ │
│ │ Router │ │ Contract │ │ Rollback Manager │ │
│ │ Engine │ │ Enforcer │ │ ┌─────────────────────┐ │ │
│ └──────┬──────┘ └──────┬───────┘ │ │ Snapshot Store │ │ │
│ │ │ │ └─────────────────────┘ │ │
│ └────────────────┼──────────│ ┌─────────────────────┐ │ │
│ │ │ │ Health Monitor │ │ │
│ ▼ │ └─────────────────────┘ │ │
│ ┌────────────────────────────────┐ └───────────────────────────┘ │
│ │ PLUGIN SANDBOX │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ │ Auth │ │ Rate │ │ Trans- │ │ Logging │ │
│ │ │ Plugin │ │ Limiter │ │ former │ │ Plugin │ │
│ │ │ (isolated)│(isolated)│(isolated)│(isolated)│ │
│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
│ └────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────┘
Implementation
package gateway
import (
"context"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"sync"
"time"
)
// ============================================================================
// CORE TYPES AND INTERFACES
// ============================================================================
// Version represents semantic versioning
type Version struct {
Major int `json:"major"`
Minor int `json:"minor"`
Patch int `json:"patch"`
}
func (v Version) String() string {
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
}
func (v Version) Compatible(other Version) bool {
return v.Major == other.Major
}
// PluginPhase defines when a plugin executes in the request lifecycle
type PluginPhase int
const (
PhasePreAuth PluginPhase = iota
PhaseAuth
PhasePostAuth
PhasePreTransform
PhaseTransform
PhasePostTransform
PhasePreForward
PhasePostResponse
)
func (p PluginPhase) String() string {
return [...]string{"PreAuth", "Auth", "PostAuth", "PreTransform",
"Transform", "PostTransform", "PreForward", "PostResponse"}[p]
}
// PluginMetadata contains plugin identification and capabilities
type PluginMetadata struct {
ID string `json:"id"`
Name string `json:"name"`
Version Version `json:"version"`
Description string `json:"description"`
Author string `json:"author"`
Phases []PluginPhase `json:"phases"`
Capabilities []string `json:"capabilities"`
ConfigSchema json.RawMessage `json:"config_schema"`
}
// PluginContract defines the interface contract for plugins
type PluginContract struct {
Metadata PluginMetadata `json:"metadata"`
InputSchema json.RawMessage `json:"input_schema"`
OutputSchema json.RawMessage `json:"output_schema"`
RequiredEnvVars []string `json:"required_env_vars"`
RequiredAPIs []string `json:"required_apis"`
MaxMemoryMB int `json:"max_memory_mb"`
TimeoutMs int `json:"timeout_ms"`
RetryPolicy RetryPolicy `json:"retry_policy"`
}
// RetryPolicy defines retry behavior for plugin failures
type RetryPolicy struct {
MaxRetries int `json:"max_retries"`
InitialDelay time.Duration `json:"initial_delay"`
MaxDelay time.Duration `json:"max_delay"`
BackoffFactor float64 `json:"backoff_factor"`
}
// PluginContext provides execution context for plugins
type PluginContext struct {
RequestID string
TraceID string
Headers map[string]string
QueryParams map[string]string
PathParams map[string]string
RequestBody []byte
Config json.RawMessage
State map[string]interface{}
CancelReason string
mu sync.RWMutex
}
func (c *PluginContext) SetState(key string, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
if c.State == nil {
c.State = make(map[string]interface{})
}
c.State[key] = value
}
func (c *PluginContext) GetState(key string) (interface{}, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
if c.State == nil {
return nil, false
}
val, ok := c.State[key]
return val, ok
}
// PluginResult contains the outcome of plugin execution
type PluginResult struct {
StatusCode int `json:"status_code"`
Headers map[string]string `json:"headers"`
Body []byte `json:"body"`
ModifiedRequest *http.Request `json:"-"`
ShouldContinue bool `json:"should_continue"`
ShouldCache bool `json:"should_cache"`
CacheKey string `json:"cache_key"`
CacheTTL time.Duration `json:"cache_ttl"`
Metrics PluginMetrics `json:"metrics"`
}
// PluginMetrics captures execution metrics
type PluginMetrics struct {
DurationMs int64 `json:"duration_ms"`
MemoryUsedKB int64 `json:"memory_used_kb"`
CPUTimeMs int64 `json:"cpu_time_ms"`
RetryCount int `json:"retry_count"`
ErrorRate float64 `json:"error_rate"`
}
// Plugin is the core interface that all plugins must implement
type Plugin interface {
// Metadata returns plugin identification and capabilities
Metadata() PluginMetadata
// Contract returns the plugin's interface contract
Contract() PluginContract
// Initialize sets up the plugin with configuration
Initialize(ctx context.Context, config json.RawMessage) error
// Execute runs the plugin logic
Execute(ctx context.Context, pluginCtx *PluginContext) (*PluginResult, error)
// ValidateConfig checks if configuration is valid
ValidateConfig(config json.RawMessage) error
// HealthCheck verifies plugin is functioning correctly
HealthCheck(ctx context.Context) error
// Shutdown gracefully stops the plugin
Shutdown(ctx context.Context) error
}
// ============================================================================
// PLUGIN SANDBOX - Isolation Layer
// ============================================================================
// SandboxConfig configures plugin isolation
type SandboxConfig struct {
MaxMemoryBytes int64
MaxCPUMs int64
ExecutionTimeout time.Duration
NetworkDisabled bool
FilesystemRoot string
AllowedSyscalls []string
EnvWhitelist []string
}
// Sandbox isolates plugin execution
type Sandbox struct {
config SandboxConfig
plugin Plugin
state *SandboxState
metrics *SandboxMetrics
violations []Violation
mu sync.RWMutex
}
type SandboxState struct {
Status string `json:"status"`
StartTime time.Time `json:"start_time"`
ExecCount int64 `json:"exec_count"`
ErrorCount int64 `json:"error_count"`
LastExecTime time.Time `json:"last_exec_time"`
}
type SandboxMetrics struct {
TotalExecTime time.Duration
AvgExecTime time.Duration
MemoryHighWater int64
CPUUsage float64
}
type Violation struct {
Timestamp time.Time `json:"timestamp"`
Type string `json:"type"`
Details string `json:"details"`
Severity string `json:"severity"`
}
// NewSandbox creates a new isolated execution environment
func NewSandbox(plugin Plugin, config SandboxConfig) *Sandbox {
return &Sandbox{
config: config,
plugin: plugin,
state: &SandboxState{
Status: "initialized",
},
metrics: &SandboxMetrics{},
violations: make([]Violation, 0),
}
}
// Execute runs the plugin in isolation with resource constraints
func (s *Sandbox) Execute(ctx context.Context, pluginCtx *PluginContext) (*PluginResult, error) {
s.mu.Lock()
s.state.ExecCount++
s.state.LastExecTime = time.Now()
s.mu.Unlock()
// Create timeout context
execCtx, cancel := context.WithTimeout(ctx, s.config.ExecutionTimeout)
defer cancel()
// Resource monitoring channel
resultCh := make(chan struct {
result *PluginResult
err error
}, 1)
// Execute in goroutine with monitoring
go func() {
defer func() {
if r := recover(); r != nil {
s.recordViolation("panic", fmt.Sprintf("%v", r), "critical")
resultCh <- struct {
result *PluginResult
err error
}{nil, fmt.Errorf("plugin panic: %v", r)}
}
}()
result, err := s.plugin.Execute(execCtx, pluginCtx)
resultCh <- struct {
result *PluginResult
err error
}{result, err}
}()
// Wait for result or timeout
select {
case res := <-resultCh:
if res.err != nil {
s.mu.Lock()
s.state.ErrorCount++
s.mu.Unlock()
}
return res.result, res.err
case <-execCtx.Done():
s.recordViolation("timeout", "execution exceeded time limit", "high")
return nil, fmt.Errorf("plugin execution timeout")
}
}
func (s *Sandbox) recordViolation(vType, details, severity string) {
s.mu.Lock()
defer s.mu.Unlock()
s.violations = append(s.violations, Violation{
Timestamp: time.Now(),
Type: vType,
Details: details,
Severity: severity,
})
}
func (s *Sandbox) GetState() SandboxState {
s.mu.RLock()
defer s.mu.RUnlock()
return *s.state
}
func (s *Sandbox) GetViolations() []Violation {
s.mu.RLock()
defer s.mu.RUnlock()
return append([]Violation{}, s.violations...)
}
// ============================================================================
// CONTRACT ENFORCEMENT
// ============================================================================
// ContractEnforcer validates plugin contracts and runtime behavior
type ContractEnforcer struct {
validators map[string]Validator
rules []ContractRule
}
type Validator interface {
Validate(input interface{}) error
Schema() json.RawMessage
}
type ContractRule struct {
ID string
Name string
Description string
Severity string
Check func(ctx *PluginContext, result *PluginResult) error
}
// NewContractEnforcer creates a new contract enforcer
func NewContractEnforcer() *ContractEnforcer {
ce := &ContractEnforcer{
validators: make(map[string]Validator),
rules: make([]ContractRule, 0),
}
ce.registerBuiltinRules()
return ce
}
// ValidateContract checks if a plugin's contract is valid
func (ce *ContractEnforcer) ValidateContract(contract PluginContract) error {
// Validate metadata
if contract.Metadata.ID == "" {
return errors.New("plugin ID is required")
}
if contract.Metadata.Name == "" {
return errors.New("plugin name is required")
}
if len(contract.Metadata.Phases) == 0 {
return errors.New("plugin must specify at least one phase")
}
// Validate schemas
if len(contract.InputSchema) > 0 {
if !json.Valid(contract.InputSchema) {
return errors.New("input schema must be valid JSON")
}
}
if len(contract.OutputSchema) > 0 {
if !json.Valid(contract.OutputSchema) {
return errors.New("output schema must be valid JSON")
}
}
// Validate resource constraints
if contract.MaxMemoryMB < 0 {
return errors.New("max memory cannot be negative")
}
if contract.TimeoutMs < 0 {
return errors.New("timeout cannot be negative")
}
return nil
}
// EnforceRuntime checks runtime compliance with contract
func (ce *ContractEnforcer) EnforceRuntime(
contract PluginContract,
ctx *PluginContext,
result *PluginResult,
) []ContractViolation {
violations := make([]ContractViolation, 0)
for _, rule := range ce.rules {
if err := rule.Check(ctx, result); err != nil {
violations = append(violations, ContractViolation{
RuleID: rule.ID,
RuleName: rule.Name,
Severity: rule.Severity,
Message: err.Error(),
Timestamp: time.Now(),
})
}
}
return violations
}
type ContractViolation struct {
RuleID string `json:"rule_id"`
RuleName string `json:"rule_name"`
Severity string `json:"severity"`
Message string `json:"message"`
Timestamp time.Time `json:"timestamp"`
}
func (ce *ContractEnforcer) registerBuiltinRules() {
// Rule: Response time SLA
ce.rules = append(ce.rules, ContractRule{
ID: "response-time-sla",
Name: "Response Time SLA",
Description: "Plugin must respond within timeout",
Severity: "high",
Check: func(ctx *PluginContext, result *PluginResult) error {
if result == nil {
return errors.New("nil result")
}
if result.Metrics.DurationMs > 5000 {
return fmt.Errorf("response time %dms exceeds SLA", result.Metrics.DurationMs)
}
return nil
},
})
// Rule: Status code validity
ce.rules = append(ce.rules, ContractRule{
ID: "valid-status-code",
Name: "Valid Status Code",
Description: "Status code must be valid HTTP",
Severity: "medium",
Check: func(ctx *PluginContext, result *PluginResult) error {
if result == nil {
return errors.New("nil result")
}
if result.StatusCode < 100 || result.StatusCode > 599 {
return fmt.Errorf("invalid status code: %d", result.StatusCode)
}
return nil
},
})
// Rule: Memory usage
ce.rules = append(ce.rules, ContractRule{
ID: "memory-limit",
Name: "Memory Limit",
Description: "Plugin must not exceed memory limit",
Severity: "high",
Check: func(ctx *PluginContext, result *PluginResult) error {
if result == nil {
return nil
}
if result.Metrics.MemoryUsedKB > 102400 { // 100MB
return fmt.Errorf("memory usage %dKB exceeds limit", result.Metrics.MemoryUsedKB)
}
return nil
},
})
// Rule: Error rate threshold
ce.rules = append(ce.rules, ContractRule{
ID: "error-rate-threshold",
Name: "Error Rate Threshold",
Description: "Plugin error rate must be acceptable",
Severity: "medium",
Check: func(ctx *PluginContext, result *PluginResult) error {
if result == nil {
return nil
}
if result.Metrics.ErrorRate > 0.1 { // 10%
return fmt.Errorf("error rate %.2f exceeds threshold", result.Metrics.ErrorRate)
}
return nil
},
})
}
// ============================================================================
// POLICY ENGINE
// ============================================================================
// Policy represents a gateway policy configuration
type Policy struct {
ID string `json:"id"`
Name string `json:"name"`
Version Version `json:"version"`
Routes []RouteConfig `json:"routes"`
Plugins []PluginConfig `json:"plugins"`
GlobalConfig GlobalConfig `json:"global_config"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
CreatedBy string `json:"created_by"`
Checksum string `json:"checksum"`
}
type RouteConfig struct {
ID string `json:"id"`
Path string `json:"path"`
Methods []string `json:"methods"`
Backend string `json:"backend"`
Timeout time.Duration `json:"timeout"`
RetryPolicy RetryPolicy `json:"retry_policy"`
PluginChain []string `json:"plugin_chain"`
RateLimit *RateLimitConfig `json:"rate_limit,omitempty"`
Authentication *AuthConfig `json:"authentication,omitempty"`
Transformations []TransformConfig `json:"transformations,omitempty"`
}
type PluginConfig struct {
ID string `json:"id"`
PluginID string `json:"plugin_id"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
Phase PluginPhase `json:"phase"`
Config json.RawMessage `json:"config"`
Conditions []Condition `json:"conditions"`
}
type Condition struct {
Type string `json:"type"`
Key string `json:"key"`
Match string `json:"match"`
Value json.RawMessage `json:"value"`
}
type GlobalConfig struct {
DefaultTimeout time.Duration `json:"default_timeout"`
MaxRequestSize int64 `json:"max_request_size"`
EnableTracing bool `json:"enable_tracing"`
EnableMetrics bool `json:"enable_metrics"`
CORS *CORSConfig `json:"cors,omitempty"`
}
type RateLimitConfig struct {
RequestsPerSecond int `json:"requests_per_second"`
BurstSize int `json:"burst_size"`
Window time.Duration `json:"window"`
KeyTemplate string `json:"key_template"`
}
type AuthConfig struct {
Type string `json:"type"`
Header string `json:"header"`
TokenPrefix string `json:"token_prefix"`
Required bool `json:"required"`
Claims map[string]string `json:"claims"`
}
type TransformConfig struct {
Type string `json:"type"`
Path string `json:"path"`
Value json.RawMessage `json:"value"`
Template string `json:"template"`
}
type CORSConfig struct {
AllowedOrigins []string `json:"allowed_origins"`
AllowedMethods []string `json:"allowed_methods"`
AllowedHeaders []string `json:"allowed_headers"`
ExposedHeaders []string `json:"exposed_headers"`
AllowCredentials bool `json:"allow_credentials"`
MaxAge int `json:"max_age"`
}
// PolicyValidator validates policy configurations
type PolicyValidator struct {
rules []PolicyValidationRule
}
type PolicyValidationRule struct {
ID string
Name string
Validate func(policy Policy) []ValidationError
}
type ValidationError struct {
Path string `json:"path"`
Message string `json:"message"`
Code string `json:"code"`
}
func NewPolicyValidator() *PolicyValidator {
pv := &PolicyValidator{
rules: make([]PolicyValidationRule, 0),
}
pv.registerBuiltinRules()
return pv
}
func (pv *PolicyValidator) Validate(policy Policy) []ValidationError {
errors := make([]ValidationError, 0)
for _, rule := range pv.rules {
errs := rule.Validate(policy)
errors = append(errors, errs...)
}
return errors
}
func (pv *PolicyValidator) registerBuiltinRules() {
// Rule: Required fields
pv.rules = append(pv.rules, PolicyValidationRule{
ID: "required-fields",
Name: "Required Fields",
Validate: func(policy Policy) []ValidationError {
var errs []ValidationError
if policy.ID == "" {
errs = append(errs, ValidationError{
Path: "id",
Message: "policy ID is required",
Code: "REQUIRED",
})
}
if policy.Name == "" {
errs = append(errs, ValidationError{
Path: "name",
Message: "policy name is required",
Code: "REQUIRED",
})
}
return errs
},
})
// Rule: Route validation
pv.rules = append(pv.rules, PolicyValidationRule{
ID: "route-validation",
Name: "Route Validation",
Validate: func(policy Policy) []ValidationError {
var errs []ValidationError
for i, route := range policy.Routes {
if route.Path == "" {
errs = append(errs, ValidationError{
Path: fmt.Sprintf("routes[%d].path", i),
Message: "route path is required",
Code: "REQUIRED",
})
}
if len(route.Methods) == 0 {
errs = append(errs, ValidationError{
Path: fmt.Sprintf("routes[%d].methods", i),
Message: "at least one method is required",
Code: "REQUIRED",
})
}
if route.Backend == "" {
errs = append(errs, ValidationError{
Path: fmt.Sprintf("routes[%d].backend", i),
Message: "backend URL is required",
Code: "REQUIRED",
})
}
}
return errs
},
})
// Rule: Plugin chain validation
pv.rules = append(pv.rules, PolicyValidationRule{
ID: "plugin-chain-validation",
Name: "Plugin Chain Validation",
Validate: func(policy Policy) []ValidationError {
var errs []ValidationError
pluginIDs := make(map[string]bool)
for _, p := range policy.Plugins {
pluginIDs[p.ID] = true
}
for i, route := range policy.Routes {
for j, pluginRef := range route.PluginChain {
if !pluginIDs[pluginRef] {
errs = append(errs, ValidationError{
Path: fmt.Sprintf("routes[%d].plugin_chain[%d]", i, j),
Message: fmt.Sprintf("plugin '%s' not defined", pluginRef),
Code: "UNDEFINED_PLUGIN",
})
}
}
}
return errs
},
})
// Rule: Rate limit validation
pv.rules = append(pv.rules, PolicyValidationRule{
ID: "rate-limit-validation",
Name: "Rate Limit Validation",
Validate: func(policy Policy) []ValidationError {
var errs []ValidationError
for i, route := range policy.Routes {
if route.RateLimit != nil {
if route.RateLimit.RequestsPerSecond <= 0 {
errs = append(errs, ValidationError{
Path: fmt.Sprintf("routes[%d].rate_limit.requests_per_second", i),
Message: "requests per second must be positive",
Code: "INVALID_VALUE",
})
}
if route.RateLimit.BurstSize < 0 {
errs = append(errs, ValidationError{
Path: fmt.Sprintf("routes[%d].rate_limit.burst_size", i),
Message: "burst size cannot be negative",
Code: "INVALID_VALUE",
})
}
}
}
return errs
},
})
}
// ============================================================================
// ROLLBACK MANAGER
// ============================================================================
// Snapshot represents a point-in-time configuration state
type Snapshot struct {
ID string `json:"id"`
Policy Policy `json:"policy"`
CreatedAt time.Time `json:"created_at"`
CreatedBy string `json:"created_by"`
Description string `json:"description"`
Tags []string `json:"tags"`
Status string `json:"status"`
HealthScore float64 `json:"health_score"`
}
// RollbackConfig configures rollback behavior
type RollbackConfig struct {
MaxSnapshots int `json:"max_snapshots"`
HealthCheckInterval time.Duration `json:"health_check_interval"`
HealthCheckWindow time.Duration `json:"health_check_window"`
ErrorRateThreshold float64 `json:"error_rate_threshold"`
LatencyThreshold time.Duration `json:"latency_threshold"`
CanaryDuration time.Duration `json:"canary_duration"`
AutoRollbackEnabled bool `json:"auto_rollback_enabled"`
}
// RollbackManager handles configuration snapshots and automated rollback
type RollbackManager struct {
config RollbackConfig
snapshots []Snapshot
currentSnapshot *Snapshot
healthMonitor *HealthMonitor
eventLog []RollbackEvent
mu sync.RWMutex
onRollback func(from, to Snapshot, reason string)
}
type RollbackEvent struct {
Timestamp time.Time `json:"timestamp"`
FromSnapshot string `json:"from_snapshot"`
ToSnapshot string `json:"to_snapshot"`
Reason string `json:"reason"`
Triggered string `json:"triggered"` // "manual", "automatic", "health_check"
Success bool `json:"success"`
Duration time.Duration `json:"duration"`
}
// NewRollbackManager creates a new rollback manager
func NewRollbackManager(config RollbackConfig) *RollbackManager {
rm := &RollbackManager{
config: config,
snapshots: make([]Snapshot, 0),
eventLog: make([]RollbackEvent, 0),
healthMonitor: NewHealthMonitor(config.HealthCheckInterval, config.HealthCheckWindow),
}
return rm
}
// CreateSnapshot creates a new configuration snapshot
func (rm *RollbackManager) CreateSnapshot(policy Policy, description, createdBy string, tags []string) (*Snapshot, error) {
rm.mu.Lock()
defer rm.mu.Unlock()
// Calculate checksum
checksum, err := rm.calculateChecksum(policy)
if err != nil {
return nil, fmt.Errorf("failed to calculate checksum: %w", err)
}
policy.Checksum = checksum
snapshot := Snapshot{
ID: rm.generateSnapshotID(),
Policy: policy,
CreatedAt: time.Now(),
CreatedBy: createdBy,
Description: description,
Tags: tags,
Status: "active",
HealthScore: 100.0,
}
// Add to snapshots
rm.snapshots = append(rm.snapshots, snapshot)
// Enforce max snapshots
if len(rm.snapshots) > rm.config.MaxSnapshots {
rm.snapshots = rm.snapshots[1:]
}
rm.currentSnapshot = &snapshot
return &snapshot, nil
}
// Rollback reverts to a previous snapshot
func (rm *RollbackManager) Rollback(snapshotID, reason, triggered string) (*Snapshot, error) {
rm.mu.Lock()
defer rm.mu.Unlock()
startTime := time.Now()
// Find target snapshot
var targetSnapshot *Snapshot
for i := range rm.snapshots {
if rm.snapshots[i].ID == snapshotID {
targetSnapshot = &rm.snapshots[i]
break
}
}
if targetSnapshot == nil {
return nil, fmt.Errorf("snapshot %s not found", snapshotID)
}
// Validate snapshot is rollback-able
if err := rm.validateRollback(targetSnapshot); err != nil {
return nil, fmt.Errorf("rollback validation failed: %w", err)
}
fromSnapshot := ""
if rm.currentSnapshot != nil {
fromSnapshot = rm.currentSnapshot.ID
}
// Perform rollback
targetSnapshot.Status = "active"
rm.currentSnapshot = targetSnapshot
duration := time.Since(startTime)
// Log event
event := RollbackEvent{
Timestamp: time.Now(),
FromSnapshot: fromSnapshot,
ToSnapshot: snapshotID,
Reason: reason,
Triggered: triggered,
Success: true,
Duration: duration,
}
rm.eventLog = append(rm.eventLog, event)
// Notify callback
if rm.onRollback != nil && fromSnapshot != "" {
go rm.onRollback(
*rm.findSnapshotByID(fromSnapshot),
*targetSnapshot,
reason,
)
}
return targetSnapshot, nil
}
// AutoRollback checks health and triggers rollback if needed
func (rm *RollbackManager) AutoRollback() (bool, *Snapshot, string) {
if !rm.config.AutoRollbackEnabled || rm.currentSnapshot == nil {
return false, nil, ""
}
rm.mu.RLock()
defer rm.mu.RUnlock()
// Get current health metrics
metrics := rm.healthMonitor.GetMetrics()
// Check error rate
if metrics.ErrorRate > rm.config.ErrorRateThreshold {
reason := fmt.Sprintf("error rate %.2f%% exceeds threshold %.2f%%",
metrics.ErrorRate*100, rm.config.ErrorRateThreshold*100)
// Find previous healthy snapshot
prevSnapshot := rm.findPreviousHealthySnapshot()
if prevSnapshot != nil {
snapshot, err := rm.Rollback(prevSnapshot.ID, reason, "automatic")
if err != nil {
return false, nil, err.Error()
}
return true, snapshot, reason
}
}
// Check latency
if metrics.P99Latency > rm.config.LatencyThreshold {
reason := fmt.Sprintf("p99 latency %v exceeds threshold %v",
metrics.P99Latency, rm.config.LatencyThreshold)
prevSnapshot := rm.findPreviousHealthySnapshot()
if prevSnapshot != nil {
snapshot, err := rm.Rollback(prevSnapshot.ID, reason, "automatic")
if err != nil {
return false, nil, err.Error()
}
return true, snapshot, reason
}
}
return false, nil, ""
}
func (rm *RollbackManager) findSnapshotByID(id string) *Snapshot {
for i := range rm.snapshots {
if rm.snapshots[i].ID == id {
return &rm.snapshots[i]
}
}
return nil
}
func (rm *RollbackManager) findPreviousHealthySnapshot() *Snapshot {
for i := len(rm.snapshots) - 2; i >= 0; i-- {
if rm.snapshots[i].HealthScore >= 90.0 {
return &rm.snapshots[i]
}
}
return nil
}
func (rm *RollbackManager) validateRollback(snapshot *Snapshot) error {
// Add validation logic here
return nil
}
func (rm *RollbackManager) generateSnapshotID() string {
return fmt.Sprintf("snap-%d", time.Now().UnixNano())
}
func (rm *RollbackManager) calculateChecksum(policy Policy) (string, error) {
data, err := json.Marshal(policy)
if err != nil {
return "", err
}
hash := sha256.Sum256(data)
return fmt.Sprintf("%x", hash[:16]), nil
}
// GetSnapshotHistory returns snapshot history
func (rm *RollbackManager) GetSnapshotHistory(limit int) []Snapshot {
rm.mu.RLock()
defer rm.mu.RUnlock()
if limit <= 0 || limit > len(rm.snapshots) {
limit = len(rm.snapshots)
}
start := len(rm.snapshots) - limit
if start < 0 {
start = 0
}
return append([]Snapshot{}, rm.snapshots[start:]...)
}
// OnRollback sets the rollback callback
func (rm *RollbackManager) OnRollback(callback func(from, to Snapshot, reason string)) {
rm.mu.Lock()
defer rm.mu.Unlock()
rm.onRollback = callback
}
// ============================================================================
// HEALTH MONITOR
// ============================================================================
// HealthMonitor tracks gateway health metrics
type HealthMonitor struct {
interval time.Duration
window time.Duration
metrics HealthMetrics
dataPoints []DataPoint
mu sync.RWMutex
stopCh chan struct{}
}
type HealthMetrics struct {
ErrorRate float64 `json:"error_rate"`
AvgLatency time.Duration `json:"avg_latency"`
P99Latency time.Duration `json:"p99_latency"`
SuccessRate float64 `json:"success_rate"`
RequestCount int64 `json:"request_count"`
ActiveRequests int64 `json:"active_requests"`
LastUpdated time.Time `json:"last_updated"`
}
type DataPoint struct {
Timestamp time.Time
Success bool
Latency time.Duration
}
func NewHealthMonitor(interval, window time.Duration) *HealthMonitor {
return &HealthMonitor{
interval: interval,
window: window,
dataPoints: make([]DataPoint, 0),
stopCh: make(chan struct{}),
}
}
func (hm *HealthMonitor) Record(success bool, latency time.Duration) {
hm.mu.Lock()
defer hm.mu.Unlock()
hm.dataPoints = append(hm.dataPoints, DataPoint{
Timestamp: time.Now(),
Success: success,
Latency: latency,
})
// Trim old data points
cutoff := time.Now().Add(-hm.window)
startIdx := 0
for i, dp := range hm.dataPoints {
if dp.Timestamp.After(cutoff) {
startIdx = i
break
}
}
hm.dataPoints = hm.dataPoints[startIdx:]
}
func (hm *HealthMonitor) GetMetrics() HealthMetrics {
hm.mu.RLock()
defer hm.mu.RUnlock()
if len(hm.dataPoints) == 0 {
return hm.metrics
}
var successCount int
var totalLatency time.Duration
latencies := make([]time.Duration, len(hm.dataPoints))
for i, dp := range hm.dataPoints {
if dp.Success {
successCount++
}
totalLatency += dp.Latency
latencies[i] = dp.Latency
}
// Sort for p99
for i := 0; i < len(latencies); i++ {
for j := i + 1; j < len(latencies); j++ {
if latencies[j] < latencies[i] {
latencies[i], latencies[j] = latencies[j], latencies[i]
}
}
}
p99Index := int(float64(len(latencies)) * 0.99)
if p99Index >= len(latencies) {
p99Index = len(latencies) - 1
}
hm.metrics = HealthMetrics{
ErrorRate: float64(len(hm.dataPoints)-successCount) / float64(len(hm.dataPoints)),
SuccessRate: float64(successCount) / float64(len(hm.dataPoints)),
AvgLatency: totalLatency / time.Duration(len(hm.dataPoints)),
P99Latency: latencies[p99Index],
RequestCount: int64(len(hm.dataPoints)),
LastUpdated: time.Now(),
}
return hm.metrics
}
// ============================================================================
// GATEWAY - Main Orchestrator
// ============================================================================
// GatewayConfig configures the gateway
type GatewayConfig struct {
Name string
Version Version
DefaultTimeout time.Duration
MaxRequestSize int64
EnableTracing bool
EnableMetrics bool
RollbackConfig RollbackConfig
SandboxConfig SandboxConfig
}
// Gateway is the main API gateway orchestrator
type Gateway struct {
config GatewayConfig
plugins map[string]*Sandbox
pluginOrder map[PluginPhase][]string
contractEnforcer *ContractEnforcer
policyValidator *PolicyValidator
rollbackManager *RollbackManager
healthMonitor *HealthMonitor
currentPolicy *Policy
httpClient *http.Client
mu sync.RWMutex
}
// NewGateway creates a new API gateway
func NewGateway(config GatewayConfig) *Gateway {
return &Gateway{
config: config,
plugins: make(map[string]*Sandbox),
pluginOrder: make(map[PluginPhase][]string),
contractEnforcer: NewContractEnforcer(),
policyValidator: NewPolicyValidator(),
rollbackManager: NewRollbackManager(config.RollbackConfig),
healthMonitor: NewHealthMonitor(10*time.Second, 5*time.Minute),
httpClient: &http.Client{
Timeout: config.DefaultTimeout,
},
}
}
// RegisterPlugin adds a new plugin to the gateway
func (g *Gateway) RegisterPlugin(plugin Plugin) error {
metadata := plugin.Metadata()
contract := plugin.Contract()
// Validate contract
if err := g.contractEnforcer.ValidateContract(contract); err != nil {
return fmt.Errorf("contract validation failed: %w", err)
}
// Initialize plugin
if err := plugin.Initialize(context.Background(), contract.Metadata.ConfigSchema); err != nil {
return fmt.Errorf("plugin initialization failed: %w", err)
}
// Create sandbox
sandbox := NewSandbox(plugin, g.config.SandboxConfig)
g.mu.Lock()
defer g.mu.Unlock()
g.plugins[metadata.ID] = sandbox
// Add to phase ordering
for _, phase := range metadata.Phases {
g.pluginOrder[phase] = append(g.pluginOrder[phase], metadata.ID)
}
return nil
}
// ApplyPolicy applies a new policy configuration
func (g *Gateway) ApplyPolicy(policy Policy, createdBy string) error {
// Validate policy
errors := g.policyValidator.Validate(policy)
if len(errors) > 0 {
return fmt.Errorf("policy validation failed: %v", errors)
}
// Create snapshot
snapshot, err := g.rollbackManager.CreateSnapshot(policy, "Policy update", createdBy, []string{"policy"})
if err != nil {
return fmt.Errorf("failed to create snapshot: %w", err)
}
g.mu.Lock()
g.currentPolicy = &policy
g.mu.Unlock()
// Start health monitoring for auto-rollback
if g.config.RollbackConfig.AutoRollbackEnabled {
go g.monitorPolicyHealth(snapshot.ID)
}
return nil
}
func (g *Gateway) monitorPolicyHealth(snapshotID string) {
ticker := time.NewTicker(g.config.RollbackConfig.HealthCheckInterval)
defer ticker.Stop()
canaryEnd := time.Now().Add(g.config.RollbackConfig.CanaryDuration)
for {
select {
case <-ticker.C:
// During canary period, check for auto-rollback
if time.Now().Before(canaryEnd) {
rolledBack, _, reason := g.rollbackManager.AutoRollback()
if rolledBack {
fmt.Printf("Auto-rollback triggered: %s\n", reason)
return
}
}
}
}
}
// ServeHTTP handles incoming HTTP requests
func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
startTime := time.Now()
// Create plugin context
pluginCtx := &PluginContext{
RequestID: generateRequestID(),
TraceID: r.Header.Get("X-Trace-ID"),
Headers: headersToMap(r.Header),
QueryParams: queryToMap(r.URL.Query()),
}
// Read request body
if r.Body != nil {
body, err := io.ReadAll(io.LimitReader(r.Body, g.config.MaxRequestSize))
if err != nil {
http.Error(w, "Failed to read request body", http.StatusBadRequest)
g.healthMonitor.Record(false, time.Since(startTime))
return
}
pluginCtx.RequestBody = body
}
// Execute plugin chain
result, err := g.executePluginChain(r.Context(), pluginCtx)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
g.healthMonitor.Record(false, time.Since(startTime))
return
}
// Forward to backend if all plugins pass
if result.ShouldContinue {
backendResp, err := g.forwardToBackend(r, result)
if err != nil {
http.Error(w, fmt.Sprintf("Backend error: %v", err), http.StatusBadGateway)
g.healthMonitor.Record(false, time.Since(startTime))
return
}
defer backendResp.Body.Close()
// Copy response
for k, v := range backendResp.Header {
w.Header()[k] = v
}
w.WriteHeader(backendResp.StatusCode)
io.Copy(w, backendResp.Body)
g.healthMonitor.Record(true, time.Since(startTime))
} else {
// Plugin returned a response directly
for k, v := range result.Headers {
w.Header().Set(k, v)
}
w.WriteHeader(result.StatusCode)
w.Write(result.Body)
g.healthMonitor.Record(result.StatusCode < 400, time.Since(startTime))
}
}
func (g *Gateway) executePluginChain(ctx context.Context, pluginCtx *PluginContext) (*PluginResult, error) {
phases := []PluginPhase{
PhasePreAuth, PhaseAuth, PhasePostAuth,
PhasePreTransform, PhaseTransform, PhasePostTransform,
PhasePreForward,
}
var lastResult *PluginResult
for _, phase := range phases {
pluginIDs := g.pluginOrder[phase]
for _, pluginID := range pluginIDs {
sandbox, exists := g.plugins[pluginID]
if !exists {
continue
}
result, err := sandbox.Execute(ctx, pluginCtx)
if err != nil {
return nil, fmt.Errorf("plugin %s failed: %w", pluginID, err)
}
// Enforce contract
contract := sandbox.plugin.Contract()
violations := g.contractEnforcer.EnforceRuntime(contract, pluginCtx, result)
if len(violations) > 0 {
for _, v := range violations {
if v.Severity == "high" || v.Severity == "critical" {
return nil, fmt.Errorf("contract violation: %s", v.Message)
}
}
}
lastResult = result
// Check if plugin wants to short-circuit
if !result.ShouldContinue {
return result, nil
}
}
}
if lastResult == nil {
lastResult = &PluginResult{
StatusCode: http.StatusOK,
ShouldContinue: true,
}
}
return lastResult, nil
}
func (g *Gateway) forwardToBackend(r *http.Request, result *PluginResult) (*http.Response, error) {
g.mu.RLock()
policy := g.currentPolicy
g.mu.RUnlock()
if policy == nil {
return nil, errors.New("no policy configured")
}
// Find matching route
var route *RouteConfig
for _, rt := range policy.Routes {
if rt.Path == r.URL.Path {
route = &rt
break
}
}
if route == nil {
return nil, errors.New("no route found")
}
// Create backend request
backendURL := route.Backend + r.URL.Path
if r.URL.RawQuery != "" {
backendURL += "?" + r.URL.RawQuery
}
backendReq, err := http.NewRequest(r.Method, backendURL, r.Body)
if err != nil {
return nil, err
}
// Copy headers
for k, v := range r.Header {
backendReq.Header[k] = v
}
// Add headers from plugin result
if result.Headers != nil {
for k, v := range result.Headers {
backendReq.Header.Set(k, v)
}
}
return g.httpClient.Do(backendReq)
}
// GetHealth returns current health metrics
func (g *Gateway) GetHealth() HealthMetrics {
return g.healthMonitor.GetMetrics()
}
// GetPlugins returns registered plugins
func (g *Gateway) GetPlugins() []PluginMetadata {
g.mu.RLock()
defer g.mu.RUnlock()
plugins := make([]PluginMetadata, 0, len(g.plugins))
for _, sandbox := range g.plugins {
plugins = append(plugins, sandbox.plugin.Metadata())
}
return plugins
}
// ============================================================================
// EXAMPLE PLUGINS
// ============================================================================
// AuthPlugin demonstrates a basic authentication plugin
type AuthPlugin struct {
config AuthPluginConfig
}
type AuthPluginConfig struct {
TokenHeader string `json:"token_header"`
TokenPrefix string `json:"token_prefix"`
Required bool `json:"required"`
SecretKey string `json:"secret_key"`
}
func NewAuthPlugin() *AuthPlugin {
return &AuthPlugin{}
}
func (p *AuthPlugin) Metadata() PluginMetadata {
return PluginMetadata{
ID: "auth-plugin",
Name: "Authentication Plugin",
Version: Version{Major: 1, Minor: 0, Patch: 0},
Description: "Handles API authentication",
Author: "Gateway Framework",
Phases: []PluginPhase{PhaseAuth},
Capabilities: []string{"authentication", "jwt", "api-key"},
}
}
func (p *AuthPlugin) Contract() PluginContract {
return PluginContract{
Metadata: p.Metadata(),
MaxMemoryMB: 64,
TimeoutMs: 1000,
}
}
func (p *AuthPlugin) Initialize(ctx context.Context, config json.RawMessage) error {
if len(config) > 0 {
return json.Unmarshal(config, &p.config)
}
p.config = AuthPluginConfig{
TokenHeader: "Authorization",
TokenPrefix: "Bearer ",
Required: true,
}
return nil
}
func (p *AuthPlugin) Execute(ctx context.Context, pluginCtx *PluginContext) (*PluginResult, error) {
start := time.Now()
authHeader := pluginCtx.Headers[p.config.TokenHeader]
if authHeader == "" {
if p.config.Required {
return &PluginResult{
StatusCode: http.StatusUnauthorized,
Body: []byte(`{"error":"missing authentication"}`),
Headers: map[string]string{"Content-Type": "application/json"},
ShouldContinue: false,
Metrics: PluginMetrics{
DurationMs: time.Since(start).Milliseconds(),
},
}, nil
}
return &PluginResult{ShouldContinue: true}, nil
}
// Validate token (simplified)
if len(authHeader) < len(p.config.TokenPrefix) {
return &PluginResult{
StatusCode: http.StatusUnauthorized,
Body: []byte(`{"error":"invalid token format"}`),
Headers: map[string]string{"Content-Type": "application/json"},
ShouldContinue: false,
Metrics: PluginMetrics{
DurationMs: time.Since(start).Milliseconds(),
},
}, nil
}
token := authHeader[len(p.config.TokenPrefix):]
// In real implementation, validate JWT or API key here
pluginCtx.SetState("user_id", "user-from-token-"+token[:8])
return &PluginResult{
StatusCode: http.StatusOK,
ShouldContinue: true,
Metrics: PluginMetrics{
DurationMs: time.Since(start).Milliseconds(),
},
}, nil
}
func (p *AuthPlugin) ValidateConfig(config json.RawMessage) error {
return nil
}
func (p *AuthPlugin) HealthCheck(ctx context.Context) error {
return nil
}
func (p *AuthPlugin) Shutdown(ctx context.Context) error {
return nil
}
// RateLimitPlugin demonstrates rate limiting
type RateLimitPlugin struct {
limiter *TokenBucketLimiter
config RateLimitConfig
}
type RateLimitConfig struct {
RequestsPerSecond float64 `json:"requests_per_second"`
BurstSize int `json:"burst_size"`
KeyTemplate string `json:"key_template"`
}
type TokenBucketLimiter struct {
rate float64
burst int
tokens map[string]*Bucket
mu sync.RWMutex
}
type Bucket struct {
tokens float64
lastUpdate time.Time
}
func NewRateLimitPlugin() *RateLimitPlugin {
return &RateLimitPlugin{
limiter: &TokenBucketLimiter{
tokens: make(map[string]*Bucket),
},
}
}
func (p *RateLimitPlugin) Metadata() PluginMetadata {
return PluginMetadata{
ID: "rate-limit-plugin",
Name: "Rate Limiting Plugin",
Version: Version{Major: 1, Minor: 0, Patch: 0},
Description: "Enforces rate limits on API requests",
Author: "Gateway Framework",
Phases: []PluginPhase{PhasePreAuth},
Capabilities: []string{"rate-limiting", "throttling"},
}
}
func (p *RateLimitPlugin) Contract() PluginContract {
return PluginContract{
Metadata: p.Metadata(),
MaxMemoryMB: 128,
TimeoutMs: 100,
}
}
func (p *RateLimitPlugin) Initialize(ctx context.Context, config json.RawMessage) error {
if len(config) > 0 {
if err := json.Unmarshal(config, &p.config); err != nil {
return err
}
} else {
p.config = RateLimitConfig{
RequestsPerSecond: 100,
BurstSize: 50,
KeyTemplate: "{{.IP}}",
}
}
p.limiter.rate = p.config.RequestsPerSecond
p.limiter.burst = p.config.BurstSize
return nil
}
func (p *RateLimitPlugin) Execute(ctx context.Context, pluginCtx *PluginContext) (*PluginResult, error) {
start := time.Now()
// Generate rate limit key (simplified - use IP)
key := pluginCtx.Headers["X-Real-IP"]
if key == "" {
key = "default"
}
allowed := p.limiter.Allow(key)
if !allowed {
return &PluginResult{
StatusCode: http.StatusTooManyRequests,
Body: []byte(`{"error":"rate limit exceeded"}`),
Headers: map[string]string{"Content-Type": "application/json"},
ShouldContinue: false,
Metrics: PluginMetrics{
DurationMs: time.Since(start).Milliseconds(),
},
}, nil
}
return &PluginResult{
ShouldContinue: true,
Metrics: PluginMetrics{
DurationMs: time.Since(start).Milliseconds(),
},
}, nil
}
func (l *TokenBucketLimiter) Allow(key string) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := time.Now()
bucket, exists := l.tokens[key]
if !exists {
bucket = &Bucket{
tokens: float64(l.burst),
lastUpdate: now,
}
l.tokens[key] = bucket
}
// Refill tokens
elapsed := now.Sub(bucket.lastUpdate).Seconds()
bucket.tokens = min(float64(l.burst), bucket.tokens+elapsed*l.rate)
bucket.lastUpdate = now
if bucket.tokens >= 1 {
bucket.tokens--
return true
}
return false
}
func (p *RateLimitPlugin) ValidateConfig(config json.RawMessage) error {
return nil
}
func (p *RateLimitPlugin) HealthCheck(ctx context.Context) error {
return nil
}
func (p *RateLimitPlugin) Shutdown(ctx context.Context) error {
return nil
}
// TransformPlugin demonstrates request/response transformation
type TransformPlugin struct {
config TransformPluginConfig
}
type TransformPluginConfig struct {
AddHeaders map[string]string `json:"add_headers"`
RemoveHeaders []string `json:"remove_headers"`
RewritePath string `json:"rewrite_path"`
}
func NewTransformPlugin() *TransformPlugin {
return &TransformPlugin{}
}
func (p *TransformPlugin) Metadata() PluginMetadata {
return PluginMetadata{
ID: "transform-plugin",
Name: "Transformation Plugin",
Version: Version{Major: 1, Minor: 0, Patch: 0},
Description: "Transforms requests and responses",
Author: "Gateway Framework",
Phases: []PluginPhase{PhaseTransform},
Capabilities: []string{"header-manipulation", "path-rewrite", "body-transform"},
}
}
func (p *TransformPlugin) Contract() PluginContract {
return PluginContract{
Metadata: p.Metadata(),
MaxMemoryMB: 256,
TimeoutMs: 500,
}
}
func (p *TransformPlugin) Initialize(ctx context.Context, config json.RawMessage) error {
if len(config) > 0 {
return json.Unmarshal(config, &p.config)
}
return nil
}
func (p *TransformPlugin) Execute(ctx context.Context, pluginCtx *PluginContext) (*PluginResult, error) {
start := time.Now()
result := &PluginResult{
StatusCode: http.StatusOK,
ShouldContinue: true,
Headers: make(map[string]string),
Metrics: PluginMetrics{
DurationMs: time.Since(start).Milliseconds(),
},
}
// Add headers
for k, v := range p.config.AddHeaders {
result.Headers[k] = v
}
// Copy headers except removed ones
for k, v := range pluginCtx.Headers {
shouldRemove := false
for _, removeKey := range p.config.RemoveHeaders {
if k == removeKey {
shouldRemove = true
break
}
}
if !shouldRemove {
if result.Headers[k] == "" {
result.Headers[k] = v
}
}
}
return result, nil
}
func (p *TransformPlugin) ValidateConfig(config json.RawMessage) error {
return nil
}
func (p *TransformPlugin) HealthCheck(ctx context.Context) error {
return nil
}
func (p *TransformPlugin) Shutdown(ctx context.Context) error {
return nil
}
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
func generateRequestID() string {
return fmt.Sprintf("req-%d", time.Now().UnixNano())
}
func headersToMap(headers http.Header) map[string]string {
result := make(map[string]string)
for k, v := range headers {
if len(v) > 0 {
result[k] = v[0]
}
}
return result
}
func queryToMap(query map[string][]string) map[string]string {
result := make(map[string]string)
for k, v := range query {
if len(v) > 0 {
result[k] = v[0]
}
}
return result
}
func min(a, b float64) float64 {
if a < b {
return a
}
return b
}
// ============================================================================
// MAIN DEMO
// ============================================================================
func RunDemo() {
fmt.Println("╔════════════════════════════════════════════════════════════════╗")
fmt.Println("║ COMPOSABLE API GATEWAY FRAMEWORK DEMO ║")
fmt.Println("╚════════════════════════════════════════════════════════════════╝")
fmt.Println()
// Create gateway with configuration
gatewayConfig := GatewayConfig{
Name: "demo-gateway",
Version: Version{Major: 1, Minor: 0, Patch: 0},
DefaultTimeout: 30 * time.Second,
MaxRequestSize: 10 * 1024 * 1024, // 10MB
EnableTracing: true,
EnableMetrics: true,
RollbackConfig: RollbackConfig{
MaxSnapshots: 10,
HealthCheckInterval: 5 * time.Second,
HealthCheckWindow: 2 * time.Minute,
ErrorRateThreshold: 0.1, // 10%
LatencyThreshold: 2 * time.Second,
CanaryDuration: 5 * time.Minute,
AutoRollbackEnabled: true,
},
SandboxConfig: SandboxConfig{
ExecutionTimeout: 5 * time.Second,
MaxMemoryBytes: 256 * 1024 * 1024,
NetworkDisabled: false,
},
}
gateway := NewGateway(gateway)
fmt.Println("✓ Gateway created")
// Register plugins
fmt.Println("\n▸ Registering plugins...")
authPlugin := NewAuthPlugin()
if err := gateway.RegisterPlugin(authPlugin); err != nil {
fmt.Printf("✗ Failed to register auth plugin: %v\n", err)
} else {
fmt.Println(" ✓ Auth plugin registered")
}
rateLimitPlugin := NewRateLimitPlugin()
if err := gateway.RegisterPlugin(rateLimitPlugin); err != nil {
fmt.Printf("✗ Failed to register rate limit plugin: %v\n", err)
} else {
fmt.Println(" ✓ Rate limit plugin registered")
}
transformPlugin := NewTransformPlugin()
if err := gateway.RegisterPlugin(transformPlugin); err != nil {
fmt.Printf("✗ Failed to register transform plugin: %v\n", err)
} else {
fmt.Println(" ✓ Transform plugin registered")
}
// Create initial policy
fmt.Println("\n▸ Creating policy...")
policy := Policy{
ID: "policy-001",
Name: "Production Policy",
Version: Version{Major: 1, Minor: 0, Patch: 0},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
CreatedBy: "admin",
Routes: []RouteConfig{
{
ID: "route-001",
Path: "/api/v1/users",
Methods: []string{"GET", "POST"},
Backend: "http://backend-service:8080",
Timeout: 30 * time.Second,
PluginChain: []string{"rate