api

package
v0.0.0-...-6a3e998 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2025 License: MIT Imports: 33 Imported by: 0

README

API Package

Overview

The api package provides the HTTP and WebSocket API implementations for the DevOps MCP platform. It includes REST endpoints, WebSocket handlers for real-time communication, middleware components, and integration with various DevOps tools.

Note: This package is being migrated to the new monorepo structure. New REST endpoints should be implemented in apps/rest-api/ and WebSocket functionality in apps/mcp-server/.

Architecture

api/
├── server.go            # Main REST API server
├── mcp_api.go          # MCP context management endpoints
├── tool_api.go         # DevOps tool integrations
├── agent_api.go        # AI agent management
├── embedding_api_v2.go # Embedding operations
├── vector_api.go       # Vector search operations
├── middleware.go       # Authentication, rate limiting, etc.
├── webhook_server.go   # Webhook handling
├── context/           # Context-specific handlers
├── webhooks/          # Webhook providers
└── responses/         # Response utilities

REST API Endpoints

Context Management (/api/v1/contexts)
// Create new context
POST   /api/v1/contexts
{
    "name": "authentication-refactor",
    "content": "Implement OAuth2 authentication...",
    "type": "task",
    "metadata": {
        "priority": "high",
        "tags": ["auth", "security"]
    }
}

// Get context
GET    /api/v1/contexts/:id

// Update context  
PUT    /api/v1/contexts/:id

// Delete context
DELETE /api/v1/contexts/:id

// Search contexts
GET    /api/v1/contexts/search?q=authentication&limit=10

// Summarize context
POST   /api/v1/contexts/:id/summarize
Agent Management (/api/v1/agents)
// Register agent
POST   /api/v1/agents
{
    "name": "code-analyzer-1",
    "type": "analyzer",
    "capabilities": ["code_analysis", "security_scan"],
    "endpoint": "ws://agent1.internal:8080"
}

// List agents
GET    /api/v1/agents?status=active&capability=code_analysis

// Get agent details
GET    /api/v1/agents/:id

// Update agent status
PATCH  /api/v1/agents/:id/status
{
    "status": "active"
}

// Get agent workload
GET    /api/v1/agents/:id/workload
Embedding Operations (/api/v1/embeddings)
// Generate embedding
POST   /api/v1/embeddings
{
    "text": "Fix memory leak in worker process",
    "model": "text-embedding-3-small",
    "metadata": {
        "type": "issue",
        "id": "ISSUE-123"
    }
}

// Batch generate
POST   /api/v1/embeddings/batch
{
    "texts": ["text1", "text2", "text3"],
    "model": "amazon.titan-embed-text-v1"
}

// Search similar
POST   /api/v1/embeddings/search
{
    "query": "authentication bug",
    "model": "text-embedding-3-small",
    "top_k": 10,
    "filters": {
        "type": "issue",
        "status": "open"
    }
}
Tool Integration (/api/v1/tools)
// Execute tool action
POST   /api/v1/tools/:tool/execute
{
    "action": "create_issue",
    "params": {
        "title": "Fix memory leak",
        "body": "Description...",
        "labels": ["bug", "performance"]
    }
}

// Supported tools:
// - github: Issues, PRs, commits, files
// - harness: Pipelines, deployments
// - sonarqube: Code quality metrics
// - slack: Notifications
// - custom: User-defined tools
Vector Operations (/api/v1/vectors)
// Store vector
POST   /api/v1/vectors
{
    "id": "doc-123",
    "vector": [0.1, 0.2, ...],
    "metadata": {
        "type": "document",
        "tags": ["api", "rest"]
    }
}

// Search vectors
POST   /api/v1/vectors/search
{
    "vector": [0.1, 0.2, ...],
    "top_k": 20,
    "min_similarity": 0.7
}

WebSocket API (MCP Server)

The WebSocket server implements the Model Context Protocol with binary optimization:

Connection
// Connect to WebSocket server
const ws = new WebSocket('ws://localhost:8080/ws');

// Send initialization message
ws.send(JSON.stringify({
    jsonrpc: "2.0",
    method: "initialize",
    params: {
        protocolVersion: "0.1.0",
        capabilities: {
            tools: {},
            prompts: {},
            resources: {}
        },
        clientInfo: {
            name: "devops-agent",
            version: "1.0.0"
        }
    },
    id: 1
}));
Binary Protocol

For performance, large messages use binary encoding:

// Binary message format (24 bytes header)
type Header struct {
    Magic      [4]byte  // "DMCP"
    Version    uint8    // Protocol version
    Type       uint8    // Message type
    Method     uint16   // Method enum
    Flags      uint8    // Compression, encryption
    Reserved   [3]byte  // Future use
    PayloadLen uint32   // Payload size
    RequestID  uint64   // Request ID
}

// Automatic compression for messages > 1KB
// Supports gzip compression
// Max payload: ~4GB
Real-time Features
// Subscribe to agent events
ws.send(JSON.stringify({
    method: "agent.subscribe",
    params: {
        events: ["status_change", "task_assigned"],
        agent_ids: ["agent-1", "agent-2"]
    }
}));

// Receive notifications
ws.onmessage = (event) => {
    const msg = JSON.parse(event.data);
    if (msg.method === "agent.notification") {
        // Handle agent notification
    }
};

Middleware

Authentication
// JWT authentication
authMiddleware := middleware.JWTAuth(jwtSecret)

// API key authentication
apiKeyAuth := middleware.APIKeyAuth(apiKeyValidator)

// Combined authentication
app.Use(middleware.Auth(
    middleware.WithJWT(jwtSecret),
    middleware.WithAPIKey(validator),
))
Rate Limiting
// Rate limit by IP
rateLimiter := middleware.RateLimit(
    100,              // requests
    time.Minute,      // per minute
    middleware.ByIP,  // key function
)

// Custom rate limits
customLimiter := middleware.RateLimit(
    10,
    time.Minute,
    func(c *gin.Context) string {
        return c.GetString("user_id")
    },
)
CORS Configuration
corsConfig := cors.Config{
    AllowOrigins:     []string{"https://app.example.com"},
    AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders:     []string{"Authorization", "Content-Type"},
    ExposeHeaders:    []string{"X-Total-Count"},
    AllowCredentials: true,
    MaxAge:          12 * time.Hour,
}
Metrics Collection
// Automatic metrics for all endpoints
metricsMiddleware := middleware.Metrics()

// Collected metrics:
// - http_requests_total
// - http_request_duration_seconds
// - http_request_size_bytes
// - http_response_size_bytes
// - http_requests_in_flight

Webhook Support

GitHub Webhooks
// Configure webhook handler
webhookHandler := webhooks.NewGitHubHandler(
    githubSecret,
    func(event webhooks.Event) error {
        switch event.Type {
        case "push":
            // Handle push event
        case "pull_request":
            // Handle PR event
        case "issues":
            // Handle issue event
        }
        return nil
    },
)

// Register webhook endpoint
router.POST("/webhooks/github", webhookHandler.Handle)
Custom Webhooks
// Register custom webhook provider
webhookServer.RegisterProvider("custom", &CustomProvider{
    ValidateSignature: func(r *http.Request) error {
        // Validate webhook signature
    },
    ParseEvent: func(r *http.Request) (Event, error) {
        // Parse webhook payload
    },
})

Error Handling

Standard Error Response
type ErrorResponse struct {
    Error ErrorDetail `json:"error"`
}

type ErrorDetail struct {
    Code    string                 `json:"code"`
    Message string                 `json:"message"`
    Details map[string]interface{} `json:"details,omitempty"`
}

// Example error response
{
    "error": {
        "code": "RESOURCE_NOT_FOUND",
        "message": "Context not found",
        "details": {
            "id": "ctx-123",
            "type": "context"
        }
    }
}
Error Middleware
// Global error handler
app.Use(middleware.ErrorHandler())

// Custom error handling
app.Use(func(c *gin.Context) {
    c.Next()
    
    if len(c.Errors) > 0 {
        err := c.Errors.Last()
        switch e := err.Err.(type) {
        case *ValidationError:
            c.JSON(400, ErrorResponse{
                Error: ErrorDetail{
                    Code: "VALIDATION_ERROR",
                    Message: e.Error(),
                    Details: e.Fields,
                },
            })
        default:
            c.JSON(500, ErrorResponse{
                Error: ErrorDetail{
                    Code: "INTERNAL_ERROR",
                    Message: "An error occurred",
                },
            })
        }
    }
})

Response Utilities

JSON Responses
// Success response with data
responses.JSON(c, 200, map[string]interface{}{
    "data": result,
    "meta": map[string]interface{}{
        "count": len(result),
        "page": 1,
    },
})

// Error response
responses.Error(c, 404, "RESOURCE_NOT_FOUND", "Context not found")

// Created response with location header
responses.Created(c, "/api/v1/contexts/"+id, context)
HATEOAS Support
// Add hypermedia links
response := map[string]interface{}{
    "data": context,
    "_links": map[string]interface{}{
        "self": "/api/v1/contexts/" + context.ID,
        "update": "/api/v1/contexts/" + context.ID,
        "delete": "/api/v1/contexts/" + context.ID,
        "embeddings": "/api/v1/contexts/" + context.ID + "/embeddings",
    },
}

Versioning

API Version Management
// Version in URL path
v1 := router.Group("/api/v1")
v2 := router.Group("/api/v2")

// Version in header
version := c.GetHeader("API-Version")
switch version {
case "1.0":
    handleV1(c)
case "2.0":
    handleV2(c)
default:
    c.JSON(400, gin.H{"error": "Invalid API version"})
}

Performance Optimization

Response Compression
// Enable gzip compression
app.Use(gzip.Gzip(gzip.DefaultCompression))
ETag Support
// Generate ETag for responses
etag := generateETag(data)
c.Header("ETag", etag)

// Check If-None-Match
if c.GetHeader("If-None-Match") == etag {
    c.Status(304)
    return
}
Connection Pooling
// Configure HTTP client with pooling
client := &http.Client{
    Transport: &http.Transport{
        MaxIdleConns:        100,
        MaxIdleConnsPerHost: 10,
        IdleConnTimeout:     90 * time.Second,
    },
    Timeout: 30 * time.Second,
}

Testing

Unit Tests
// Test REST endpoints
func TestCreateContext(t *testing.T) {
    router := setupTestRouter()
    
    w := httptest.NewRecorder()
    body := bytes.NewBufferString(`{"name":"test"}`)
    req, _ := http.NewRequest("POST", "/api/v1/contexts", body)
    req.Header.Set("Content-Type", "application/json")
    
    router.ServeHTTP(w, req)
    
    assert.Equal(t, 201, w.Code)
}
WebSocket Tests
// Test WebSocket connection
func TestWebSocketConnection(t *testing.T) {
    server := httptest.NewServer(wsHandler)
    defer server.Close()
    
    ws, _, err := websocket.DefaultDialer.Dial(
        "ws"+strings.TrimPrefix(server.URL, "http")+"/ws",
        nil,
    )
    require.NoError(t, err)
    defer ws.Close()
    
    // Test message exchange
    err = ws.WriteJSON(initMessage)
    require.NoError(t, err)
}

Migration Guide

When migrating to the new structure:

  1. REST Endpoints: Move to apps/rest-api/internal/api/
  2. WebSocket Handlers: Move to apps/mcp-server/internal/api/websocket/
  3. Shared Types: Keep in pkg/api/types/
  4. Middleware: Move to respective app's internal/middleware/

Best Practices

  1. Always validate input: Use binding tags and custom validators
  2. Use middleware: Leverage middleware for cross-cutting concerns
  3. Return consistent responses: Use the response utilities
  4. Handle errors gracefully: Never expose internal errors
  5. Add metrics: Monitor all critical endpoints
  6. Document APIs: Keep OpenAPI spec updated
  7. Version APIs: Plan for backward compatibility

References

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CORSMiddleware

func CORSMiddleware(cfg CORSConfig) gin.HandlerFunc

CORSMiddleware adds CORS headers to responses

func CachingMiddleware

func CachingMiddleware() gin.HandlerFunc

CachingMiddleware adds HTTP caching headers

func CompressionMiddleware

func CompressionMiddleware() gin.HandlerFunc

CompressionMiddleware adds gzip compression to responses

func ErrorHandlerMiddleware

func ErrorHandlerMiddleware() gin.HandlerFunc

ErrorHandlerMiddleware catches and formats errors consistently

func MetricsMiddleware

func MetricsMiddleware() gin.HandlerFunc

MetricsMiddleware collects API metrics

func RateLimiter

func RateLimiter(cfg RateLimiterConfig) gin.HandlerFunc

RateLimiter middleware implements rate limiting per IP address

func RegisterShutdownHook

func RegisterShutdownHook(hook func())

RegisterShutdownHook registers a function to be called during server shutdown

func RequestLogger

func RequestLogger() gin.HandlerFunc

RequestLogger middleware logs HTTP requests

func RouteToVersion

func RouteToVersion(c *gin.Context, handlers map[APIVersion]gin.HandlerFunc)

RouteToVersion routes requests to the appropriate version handler

func SetupMetricsHandler

func SetupMetricsHandler() gin.HandlerFunc

SetupMetricsHandler sets up the Prometheus metrics handler

func VersioningMiddleware

func VersioningMiddleware(config VersioningConfig) gin.HandlerFunc

VersioningMiddleware adds API versioning support

Types

type APIError

type APIError struct {
	Code     ErrorCode
	Message  string
	Details  interface{}
	HTTPCode int
	Err      error
}

APIError represents an API error with associated metadata

func HandleValidationErrors

func HandleValidationErrors(err error) *APIError

HandleValidationErrors converts field validation errors to a standardized format

func NewAPIError

func NewAPIError(code ErrorCode, message string, httpCode int, err error) *APIError

NewAPIError creates a new API error

func NewBadRequestError

func NewBadRequestError(message string, err error) *APIError

NewBadRequestError creates a bad request error

func NewContextNotFoundError

func NewContextNotFoundError(contextID string, err error) *APIError

NewContextNotFoundError creates a context not found error

func NewForbiddenError

func NewForbiddenError(message string, err error) *APIError

NewForbiddenError creates a forbidden error

func NewInternalServerError

func NewInternalServerError(message string, err error) *APIError

NewInternalServerError creates an internal server error

func NewNotFoundError

func NewNotFoundError(message string, err error) *APIError

NewNotFoundError creates a not found error

func NewUnauthorizedError

func NewUnauthorizedError(message string, err error) *APIError

NewUnauthorizedError creates an unauthorized error

func NewValidationError

func NewValidationError(message string, details interface{}) *APIError

NewValidationError creates a validation error

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns the underlying error

func (*APIError) WithDetails

func (e *APIError) WithDetails(details interface{}) *APIError

WithDetails adds details to the error

type APIVersion

type APIVersion string

APIVersion represents a specific API version

const (
	APIVersionUnspecified APIVersion = ""
	APIVersionV1          APIVersion = "v1"
	APIVersionV2          APIVersion = "v2"
)

Supported API versions

func GetAPIVersion

func GetAPIVersion(c *gin.Context) APIVersion

GetAPIVersion returns the API version from the context

type AgentAPI

type AgentAPI struct {
	// contains filtered or unexported fields
}

AgentAPI handles agent management endpoints Implements tenant-scoped CRUD operations for agents using the repository pattern.

func NewAgentAPI

func NewAgentAPI(repo repository.AgentRepository) *AgentAPI

func (*AgentAPI) RegisterRoutes

func (a *AgentAPI) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers agent endpoints under /agents

type AuthConfig

type AuthConfig struct {
	JWTSecret string      `mapstructure:"jwt_secret"`
	APIKeys   interface{} `mapstructure:"api_keys"`
}

AuthConfig holds authentication configuration

type CORSConfig

type CORSConfig struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	ExposedHeaders   []string
	AllowCredentials bool
	MaxAge           int
}

CORSConfig holds CORS configuration

type Config

type Config struct {
	ListenAddress string                   `mapstructure:"listen_address"`
	ReadTimeout   time.Duration            `mapstructure:"read_timeout"`
	WriteTimeout  time.Duration            `mapstructure:"write_timeout"`
	IdleTimeout   time.Duration            `mapstructure:"idle_timeout"`
	EnableCORS    bool                     `mapstructure:"enable_cors"`
	EnableSwagger bool                     `mapstructure:"enable_swagger"`
	TLS           *securitytls.Config      `mapstructure:"tls"` // TLS configuration
	Auth          AuthConfig               `mapstructure:"auth"`
	RateLimit     RateLimitConfig          `mapstructure:"rate_limit"`
	Versioning    VersioningConfig         `mapstructure:"versioning"`
	Performance   PerformanceConfig        `mapstructure:"performance"`
	Webhook       interfaces.WebhookConfig `mapstructure:"webhook"`
}

Config holds configuration for the API server

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults

type ContextManagerInterface

type ContextManagerInterface interface {
	CreateContext(ctx context.Context, context *models.Context) (*models.Context, error)
	GetContext(ctx context.Context, contextID string) (*models.Context, error)
	UpdateContext(ctx context.Context, contextID string, context *models.Context, options *models.ContextUpdateOptions) (*models.Context, error)
	DeleteContext(ctx context.Context, contextID string) error
	ListContexts(ctx context.Context, agentID, sessionID string, options map[string]interface{}) ([]*models.Context, error)
	SearchInContext(ctx context.Context, contextID, query string) ([]models.ContextItem, error)
	SummarizeContext(ctx context.Context, contextID string) (string, error)
}

ContextManagerInterface defines the interface for context management

type CrossModelSearchRequest

type CrossModelSearchRequest struct {
	Query          string                 `json:"query" validate:"required"`
	SearchModel    string                 `json:"search_model,omitempty"`
	IncludeModels  []string               `json:"include_models,omitempty"`
	ExcludeModels  []string               `json:"exclude_models,omitempty"`
	Limit          int                    `json:"limit,omitempty"`
	MinSimilarity  float64                `json:"min_similarity,omitempty"`
	MetadataFilter map[string]interface{} `json:"metadata_filter,omitempty"`
}

type CrossModelSearchResult

type CrossModelSearchResult struct {
	ID                uuid.UUID              `json:"id"`
	Content           string                 `json:"content"`
	OriginalModel     string                 `json:"original_model"`
	OriginalDimension int                    `json:"original_dimension"`
	NormalizedScore   float64                `json:"normalized_score"`
	Metadata          map[string]interface{} `json:"metadata"`
}

type Embedding

type Embedding struct {
	ID          string                 `json:"id" db:"id"`
	Vector      []float32              `json:"vector" db:"vector"`
	Dimensions  int                    `json:"dimensions" db:"dimensions"`
	ModelID     string                 `json:"model_id" db:"model_id"`
	ContentType string                 `json:"content_type" db:"content_type"`
	ContentID   string                 `json:"content_id" db:"content_id"`
	Namespace   string                 `json:"namespace" db:"namespace"`
	ContextID   string                 `json:"context_id" db:"context_id"`
	CreatedAt   time.Time              `json:"created_at" db:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at" db:"updated_at"`
	Metadata    map[string]interface{} `json:"metadata" db:"metadata"`
	Similarity  float64                `json:"similarity" db:"similarity"`
}

Embedding represents a vector embedding in the internal database model format This struct mirrors the internal/database.Embedding struct to avoid importing it directly

type EmbeddingAPIV2

type EmbeddingAPIV2 struct {
	// contains filtered or unexported fields
}

EmbeddingAPIV2 handles embedding API requests for multi-agent system

func NewEmbeddingAPIV2

func NewEmbeddingAPIV2(embeddingService *embedding.ServiceV2, agentService embedding.AgentService) *EmbeddingAPIV2

NewEmbeddingAPIV2 creates a new embedding API handler

func (*EmbeddingAPIV2) BatchGenerateEmbeddings

func (api *EmbeddingAPIV2) BatchGenerateEmbeddings(w http.ResponseWriter, r *http.Request)

BatchGenerateEmbeddings handles POST /api/v2/embeddings/batch

func (*EmbeddingAPIV2) CreateAgentConfig

func (api *EmbeddingAPIV2) CreateAgentConfig(w http.ResponseWriter, r *http.Request)

CreateAgentConfig handles POST /api/v2/embeddings/agents

func (*EmbeddingAPIV2) CrossModelSearch

func (api *EmbeddingAPIV2) CrossModelSearch(w http.ResponseWriter, r *http.Request)

CrossModelSearch handles POST /api/v2/embeddings/search/cross-model

func (*EmbeddingAPIV2) GenerateEmbedding

func (api *EmbeddingAPIV2) GenerateEmbedding(w http.ResponseWriter, r *http.Request)

GenerateEmbedding handles POST /api/v2/embeddings

func (*EmbeddingAPIV2) GetAgentConfig

func (api *EmbeddingAPIV2) GetAgentConfig(w http.ResponseWriter, r *http.Request)

GetAgentConfig handles GET /api/v2/embeddings/agents/{agentId}

func (*EmbeddingAPIV2) GetAgentCosts

func (api *EmbeddingAPIV2) GetAgentCosts(w http.ResponseWriter, r *http.Request)

GetAgentCosts handles GET /api/v2/embeddings/agents/{agentId}/costs

func (*EmbeddingAPIV2) GetAgentModels

func (api *EmbeddingAPIV2) GetAgentModels(w http.ResponseWriter, r *http.Request)

GetAgentModels handles GET /api/v2/embeddings/agents/{agentId}/models

func (*EmbeddingAPIV2) GetProviderHealth

func (api *EmbeddingAPIV2) GetProviderHealth(w http.ResponseWriter, r *http.Request)

GetProviderHealth handles GET /api/v2/embeddings/providers/health

func (*EmbeddingAPIV2) RegisterRoutes

func (api *EmbeddingAPIV2) RegisterRoutes(router *mux.Router)

RegisterRoutes registers embedding API routes

func (*EmbeddingAPIV2) SearchEmbeddings

func (api *EmbeddingAPIV2) SearchEmbeddings(w http.ResponseWriter, r *http.Request)

SearchEmbeddings handles POST /api/v2/embeddings/search

func (*EmbeddingAPIV2) UpdateAgentConfig

func (api *EmbeddingAPIV2) UpdateAgentConfig(w http.ResponseWriter, r *http.Request)

UpdateAgentConfig handles PUT /api/v2/embeddings/agents/{agentId}

type EmbeddingRepositoryInterface

type EmbeddingRepositoryInterface interface {
	StoreEmbedding(ctx context.Context, embedding *repository.Embedding) error
	SearchEmbeddings(ctx context.Context, queryVector []float32, contextID string, modelID string, limit int, similarityThreshold float64) ([]*repository.Embedding, error)
	SearchEmbeddings_Legacy(ctx context.Context, queryVector []float32, contextID string, limit int) ([]*repository.Embedding, error)
	GetContextEmbeddings(ctx context.Context, contextID string) ([]*repository.Embedding, error)
	DeleteContextEmbeddings(ctx context.Context, contextID string) error
	GetEmbeddingsByModel(ctx context.Context, contextID string, modelID string) ([]*repository.Embedding, error)
	GetSupportedModels(ctx context.Context) ([]string, error)
	DeleteModelEmbeddings(ctx context.Context, contextID string, modelID string) error
}

EmbeddingRepositoryInterface defines the interface for embedding repository operations

type EmbeddingSearchRequest

type EmbeddingSearchRequest struct {
	AgentID   string                 `json:"agent_id" validate:"required"`
	Query     string                 `json:"query" validate:"required"`
	Limit     int                    `json:"limit,omitempty"`
	Threshold float64                `json:"threshold,omitempty"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

type ErrorCode

type ErrorCode string

ErrorCode represents a standardized error code

const (
	// General errors
	ErrBadRequest         ErrorCode = "BAD_REQUEST"
	ErrUnauthorized       ErrorCode = "UNAUTHORIZED"
	ErrForbidden          ErrorCode = "FORBIDDEN"
	ErrNotFound           ErrorCode = "NOT_FOUND"
	ErrMethodNotAllowed   ErrorCode = "METHOD_NOT_ALLOWED"
	ErrConflict           ErrorCode = "CONFLICT"
	ErrTooManyRequests    ErrorCode = "TOO_MANY_REQUESTS"
	ErrInternalServer     ErrorCode = "INTERNAL_SERVER_ERROR"
	ErrServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"

	// Domain-specific errors
	ErrContextNotFound ErrorCode = "CONTEXT_NOT_FOUND"
	ErrContextTooLarge ErrorCode = "CONTEXT_TOO_LARGE"
	ErrContextInvalid  ErrorCode = "CONTEXT_INVALID"

	// Vector/embedding errors
	ErrEmbeddingFailed  ErrorCode = "EMBEDDING_FAILED"
	ErrEmbeddingInvalid ErrorCode = "EMBEDDING_INVALID"

	// Tool-specific errors
	ErrToolNotFound   ErrorCode = "TOOL_NOT_FOUND"
	ErrActionNotFound ErrorCode = "ACTION_NOT_FOUND"
	ErrActionFailed   ErrorCode = "ACTION_FAILED"
	ErrActionInvalid  ErrorCode = "ACTION_INVALID"

	// Model-specific errors
	ErrModelNotFound ErrorCode = "MODEL_NOT_FOUND"
	ErrModelInvalid  ErrorCode = "MODEL_INVALID"

	// Validation errors
	ErrValidationFailed ErrorCode = "VALIDATION_FAILED"
)

Standard error codes

type ErrorResponse

type ErrorResponse struct {
	Code    ErrorCode   `json:"code"`
	Message string      `json:"message"`
	Details interface{} `json:"details,omitempty"`
	TraceID string      `json:"trace_id,omitempty"`
}

ErrorResponse is the standard response format for errors

type MCPAPI

type MCPAPI struct {
	// contains filtered or unexported fields
}

MCPAPI handles the MCP-specific API endpoints

func NewMCPAPI

func NewMCPAPI(contextManager interface{}) *MCPAPI

NewMCPAPI creates a new MCP API handler

func (*MCPAPI) RegisterRoutes

func (api *MCPAPI) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers all MCP API routes

type ModelAPI

type ModelAPI struct {
	// contains filtered or unexported fields
}

ModelAPI handles model management endpoints Implements tenant-scoped CRUD operations for models using the repository pattern.

func NewModelAPI

func NewModelAPI(repo repository.ModelRepository) *ModelAPI

NewModelAPI creates a new ModelAPI with the provided repository

func (*ModelAPI) RegisterRoutes

func (m *ModelAPI) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers model endpoints under /models

type PerformanceConfig

type PerformanceConfig struct {
	// Connection pooling for database
	DBMaxIdleConns    int           `mapstructure:"db_max_idle_conns"`
	DBMaxOpenConns    int           `mapstructure:"db_max_open_conns"`
	DBConnMaxLifetime time.Duration `mapstructure:"db_conn_max_lifetime"`

	// HTTP client settings
	HTTPMaxIdleConns    int           `mapstructure:"http_max_idle_conns"`
	HTTPMaxConnsPerHost int           `mapstructure:"http_max_conns_per_host"`
	HTTPIdleConnTimeout time.Duration `mapstructure:"http_idle_conn_timeout"`

	// Response optimization
	EnableCompression bool `mapstructure:"enable_compression"`
	EnableETagCaching bool `mapstructure:"enable_etag_caching"`

	// Cache control settings
	StaticContentMaxAge  time.Duration `mapstructure:"static_content_max_age"`
	DynamicContentMaxAge time.Duration `mapstructure:"dynamic_content_max_age"`

	// Circuit breaker settings for external services
	CircuitBreakerEnabled bool          `mapstructure:"circuit_breaker_enabled"`
	CircuitBreakerTimeout time.Duration `mapstructure:"circuit_breaker_timeout"`
	MaxRetries            int           `mapstructure:"max_retries"`
	RetryBackoff          time.Duration `mapstructure:"retry_backoff"`
}

PerformanceConfig holds configuration for performance optimization

type RateLimitConfig

type RateLimitConfig struct {
	Enabled     bool          `mapstructure:"enabled"`
	Limit       int           `mapstructure:"limit"`
	Period      time.Duration `mapstructure:"period"`
	BurstFactor int           `mapstructure:"burst_factor"`
}

RateLimitConfig holds rate limiting configuration

type RateLimiterConfig

type RateLimiterConfig struct {
	RequestsPerSecond float64
	Burst             int
	Message           string
	StatusCode        int
}

RateLimiterConfig holds the configuration for rate limiting

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() RateLimiterConfig

DefaultRateLimiterConfig provides sensible defaults

func NewRateLimiterConfigFromConfig

func NewRateLimiterConfigFromConfig(cfg RateLimitConfig) RateLimiterConfig

NewRateLimiterConfigFromConfig creates a rate limiter config from the API config

type SearchByVectorRequest

type SearchByVectorRequest struct {
	// Pre-computed vector to search with
	Vector []float32 `json:"vector"`
	// ContentTypes to filter by
	ContentTypes []string `json:"content_types,omitempty"`
	// Filters to apply to metadata
	Filters []embedding.SearchFilter `json:"filters,omitempty"`
	// Sorting criteria
	Sorts []embedding.SearchSort `json:"sorts,omitempty"`
	// Maximum number of results to return
	Limit int `json:"limit,omitempty"`
	// Number of results to skip (for pagination)
	Offset int `json:"offset,omitempty"`
	// Minimum similarity threshold (0.0 to 1.0)
	MinSimilarity float32 `json:"min_similarity,omitempty"`
	// Weight factors for scoring
	WeightFactors map[string]float32 `json:"weight_factors,omitempty"`
}

SearchByVectorRequest represents a vector search request with a pre-computed vector

type SearchEmbeddingsRequest

type SearchEmbeddingsRequest struct {
	ContextID           string    `json:"context_id" binding:"required"`
	QueryEmbedding      []float32 `json:"query_embedding" binding:"required"`
	Limit               int       `json:"limit" binding:"required"`
	ModelID             string    `json:"model_id"`
	SimilarityThreshold float64   `json:"similarity_threshold"`
}

SearchEmbeddingsRequest represents a request to search embeddings

type SearchHandler

type SearchHandler struct {
	// contains filtered or unexported fields
}

SearchHandler manages vector search API endpoints

func NewSearchHandler

func NewSearchHandler(searchService embedding.SearchService) *SearchHandler

NewSearchHandler creates a new search handler

func (*SearchHandler) HandleSearch

func (h *SearchHandler) HandleSearch(w http.ResponseWriter, r *http.Request)

HandleSearch handles text-based vector search requests

func (*SearchHandler) HandleSearchByVector

func (h *SearchHandler) HandleSearchByVector(w http.ResponseWriter, r *http.Request)

HandleSearchByVector handles vector-based search requests

func (*SearchHandler) HandleSearchSimilar

func (h *SearchHandler) HandleSearchSimilar(w http.ResponseWriter, r *http.Request)

HandleSearchSimilar handles "more like this" search requests

func (*SearchHandler) RegisterRoutes

func (h *SearchHandler) RegisterRoutes(router *http.ServeMux)

RegisterRoutes registers the search endpoints with the provided router

type SearchRequest

type SearchRequest struct {
	// Query text to search for
	Query string `json:"query"`
	// ContentTypes to filter by
	ContentTypes []string `json:"content_types,omitempty"`
	// Filters to apply to metadata
	Filters []embedding.SearchFilter `json:"filters,omitempty"`
	// Sorting criteria
	Sorts []embedding.SearchSort `json:"sorts,omitempty"`
	// Maximum number of results to return
	Limit int `json:"limit,omitempty"`
	// Number of results to skip (for pagination)
	Offset int `json:"offset,omitempty"`
	// Minimum similarity threshold (0.0 to 1.0)
	MinSimilarity float32 `json:"min_similarity,omitempty"`
	// Weight factors for scoring
	WeightFactors map[string]float32 `json:"weight_factors,omitempty"`
}

SearchRequest represents a vector search request

type SearchResponse

type SearchResponse struct {
	// Results is the list of search results
	Results []*embedding.SearchResult `json:"results"`
	// Total is the total number of results found (for pagination)
	Total int `json:"total"`
	// HasMore indicates if there are more results available
	HasMore bool `json:"has_more"`
	// Query information for debugging and auditing
	Query struct {
		// Text or ContentID that was searched for
		Input string `json:"input,omitempty"`
		// Options that were used for the search
		Options *embedding.SearchOptions `json:"options,omitempty"`
	} `json:"query"`
}

SearchResponse represents the API response for search endpoints

type SearchResult

type SearchResult struct {
	ID         uuid.UUID              `json:"id"`
	Content    string                 `json:"content"`
	Similarity float64                `json:"similarity"`
	Metadata   map[string]interface{} `json:"metadata"`
}

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents the API server

func NewServer

func NewServer(engine *core.Engine, cfg Config, db *sqlx.DB, metrics observability.MetricsClient, config *config.Config) *Server

NewServer creates a new API server with internal/database implementation

func (*Server) Initialize

func (s *Server) Initialize(ctx context.Context) error

Initialize initializes all components and routes

func (*Server) RegisterWebhookRoutes

func (s *Server) RegisterWebhookRoutes(router *mux.Router)

RegisterWebhookRoutes registers webhook routes for all providers on the given router

func (*Server) SetupVectorAPI

func (s *Server) SetupVectorAPI(ctx context.Context) error

SetupVectorAPI initializes and registers the vector API routes

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the API server

func (*Server) Start

func (s *Server) Start() error

Start starts the API server without TLS

func (*Server) StartTLS

func (s *Server) StartTLS(certFile, keyFile string) error

StartTLS starts the API server with TLS

type StoreEmbeddingRequest

type StoreEmbeddingRequest struct {
	ContextID    string    `json:"context_id" binding:"required"`
	ContentIndex int       `json:"content_index" binding:"required"`
	Text         string    `json:"text" binding:"required"`
	Embedding    []float32 `json:"embedding" binding:"required"`
	ModelID      string    `json:"model_id" binding:"required"`
}

StoreEmbeddingRequest represents a request to store an embedding

type ToolAPI

type ToolAPI struct {
	// contains filtered or unexported fields
}

ToolAPI handles API endpoints for tool operations

func NewToolAPI

func NewToolAPI(adapterBridge interface{}) *ToolAPI

NewToolAPI creates a new tool API handler

func (*ToolAPI) RegisterRoutes

func (api *ToolAPI) RegisterRoutes(router *gin.RouterGroup)

RegisterRoutes registers all tool API routes

type VectorAPI

type VectorAPI struct {
	// contains filtered or unexported fields
}

VectorAPI handles the vector operations API endpoints

func NewVectorAPI

func NewVectorAPI(embedRepo EmbeddingRepositoryInterface, logger observability.Logger) *VectorAPI

NewVectorAPI creates a new vector API handler

func (*VectorAPI) RegisterRoutes

func (v *VectorAPI) RegisterRoutes(group *gin.RouterGroup)

RegisterRoutes registers the vector API routes with the given router group

type VectorDatabaseAdapter

type VectorDatabaseAdapter struct {
	// contains filtered or unexported fields
}

VectorDatabaseAdapter provides compatibility between internal/database.VectorDatabase and pkg/database.VectorDatabase This adapter allows us to migrate code incrementally without breaking existing functionality

func NewVectorDatabaseAdapter

func NewVectorDatabaseAdapter(db *sqlx.DB, cfg interface{}, logger observability.Logger) (*VectorDatabaseAdapter, error)

NewVectorDatabaseAdapter creates a new adapter that wraps a pkg/database.VectorDatabase instance but exposes it with the same interface as internal/database.VectorDatabase

func (*VectorDatabaseAdapter) BatchDeleteEmbeddings

func (a *VectorDatabaseAdapter) BatchDeleteEmbeddings(ctx context.Context, contentType, contentID, contextID string) (int, error)

BatchDeleteEmbeddings deletes multiple embeddings matching criteria

func (*VectorDatabaseAdapter) Close

func (a *VectorDatabaseAdapter) Close() error

Close closes the vector database connection

func (*VectorDatabaseAdapter) DeleteEmbedding

func (a *VectorDatabaseAdapter) DeleteEmbedding(ctx context.Context, id string) error

DeleteEmbedding deletes an embedding from the database

func (*VectorDatabaseAdapter) EnsureSchema

func (a *VectorDatabaseAdapter) EnsureSchema(ctx context.Context) error

EnsureSchema ensures the vector database schema exists

func (*VectorDatabaseAdapter) GetEmbeddingByID

func (a *VectorDatabaseAdapter) GetEmbeddingByID(ctx context.Context, id string) (*Embedding, error)

GetEmbeddingByID retrieves an embedding by ID

func (*VectorDatabaseAdapter) Initialize

func (a *VectorDatabaseAdapter) Initialize(ctx context.Context) error

Initialize initializes the vector database tables and indexes

func (*VectorDatabaseAdapter) SearchEmbeddings

func (a *VectorDatabaseAdapter) SearchEmbeddings(ctx context.Context, queryVector []float32, contextID string, modelID string, limit int, similarityThreshold float64) ([]*Embedding, error)

SearchEmbeddings searches for similar embeddings in the vector database

func (*VectorDatabaseAdapter) StoreEmbedding

func (a *VectorDatabaseAdapter) StoreEmbedding(ctx context.Context, embedding *Embedding) error

StoreEmbedding stores an embedding vector in the database

func (*VectorDatabaseAdapter) Transaction

func (a *VectorDatabaseAdapter) Transaction(ctx context.Context, fn func(tx *sqlx.Tx) error) error

Transaction initiates a transaction and passes control to the provided function

type VersionedHandlers

type VersionedHandlers struct {
	// contains filtered or unexported fields
}

VersionedHandlers holds handlers for different API versions

func NewVersionedHandlers

func NewVersionedHandlers() *VersionedHandlers

NewVersionedHandlers creates a new versioned handlers instance

func (*VersionedHandlers) Add

func (vh *VersionedHandlers) Add(version APIVersion, handler gin.HandlerFunc) *VersionedHandlers

Add adds a handler for a specific version

func (*VersionedHandlers) AddDefault

func (vh *VersionedHandlers) AddDefault(handler gin.HandlerFunc) *VersionedHandlers

AddDefault adds a default handler

func (*VersionedHandlers) Handle

func (vh *VersionedHandlers) Handle(c *gin.Context)

Handle handles a request with the appropriate version handler

type VersioningConfig

type VersioningConfig struct {
	Enabled           bool     `mapstructure:"enabled"`
	DefaultVersion    string   `mapstructure:"default_version"`
	SupportedVersions []string `mapstructure:"supported_versions"`
}

VersioningConfig holds API versioning configuration

type WebhookProvider

type WebhookProvider struct {
	Name       string
	Enabled    func() bool
	Endpoint   func() string
	Handler    func() http.HandlerFunc
	Middleware func() mux.MiddlewareFunc // can be nil
}

WebhookProvider represents a webhook provider's registration logic Extend this struct for additional providers (e.g., GitLab, Bitbucket)

Directories

Path Synopsis
Package webhooks provides GitHub webhook handlers and IP validation middleware.
Package webhooks provides GitHub webhook handlers and IP validation middleware.

Jump to

Keyboard shortcuts

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