api

package
v0.0.0-...-3989c17 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package api provides distributed WebSocket management using NNG messaging.

This allows WebSocket clients connected to any node in the cluster to receive execution updates and real-time events from workflows running on any other node.

Package api provides HTTP API functionality

Package api provides HTTP API functionality

Package api provides HTTP API functionality

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthMiddleware

func AuthMiddleware(next http.Handler) http.Handler

AuthMiddleware validates authentication (basic implementation) NOTE: This middleware requires authentication by default. Use AuthMiddlewareWithManager for full authentication support with JWT and API keys.

func AuthMiddlewareWithManager

func AuthMiddlewareWithManager(authManager *auth.AuthManager) func(http.Handler) http.Handler

AuthMiddlewareWithManager creates an authentication middleware with a configured AuthManager

func CORSMiddleware

func CORSMiddleware(allowedOrigin string) func(http.Handler) http.Handler

CORSMiddleware handles Cross-Origin Resource Sharing

func ContextWithAuth

func ContextWithAuth(ctx context.Context, auth *AuthContext) context.Context

ContextWithAuth adds authentication context to a context

func LoggingMiddleware

func LoggingMiddleware(next http.Handler) http.Handler

LoggingMiddleware logs HTTP requests

func RateLimitMiddleware

func RateLimitMiddleware(requestsPerMinute int) func(http.Handler) http.Handler

RateLimitMiddleware implements basic rate limiting (optional - can be enhanced)

func RecoveryMiddleware

func RecoveryMiddleware(next http.Handler) http.Handler

RecoveryMiddleware recovers from panics and returns a 500 error

func RequireAdminMiddleware

func RequireAdminMiddleware(next http.Handler) http.Handler

RequireAdminMiddleware creates a middleware that requires admin role

func RequireAuthMiddleware

func RequireAuthMiddleware(next http.Handler) http.Handler

RequireAuthMiddleware creates a middleware that requires authentication

func RequirePermissionMiddleware

func RequirePermissionMiddleware(permission string) func(http.Handler) http.Handler

RequirePermissionMiddleware creates a middleware that requires a specific permission

func SanitizeInput

func SanitizeInput(input string) string

SanitizeInput sanitizes string input to prevent injection attacks

func SecurityHeadersMiddleware

func SecurityHeadersMiddleware(next http.Handler) http.Handler

SecurityHeadersMiddleware adds security headers to all responses

func ValidateCronExpression

func ValidateCronExpression(cron string) bool

ValidateCronExpression validates a cron expression (basic check)

func ValidateEmail

func ValidateEmail(email string) bool

ValidateEmail validates an email address format

func ValidateURL

func ValidateURL(url string) bool

ValidateURL validates a URL format

func ValidateWorkflowName

func ValidateWorkflowName(name string) error

ValidateWorkflowName validates a workflow name

Types

type APIError

type APIError struct {
	Code       ErrorCode              `json:"code"`
	Message    string                 `json:"message"`
	Details    map[string]interface{} `json:"details,omitempty"`
	RequestID  string                 `json:"requestId,omitempty"`
	Path       string                 `json:"path,omitempty"`
	Method     string                 `json:"method,omitempty"`
	Timestamp  string                 `json:"timestamp,omitempty"`
	Stack      []string               `json:"stack,omitempty"` // Only in dev mode
	StatusCode int                    `json:"-"`               // HTTP status code (not serialized)
	Cause      error                  `json:"-"`               // Original error (not serialized)
}

APIError represents a structured API error

func ErrBadRequest

func ErrBadRequest(message string) *APIError

ErrBadRequest creates a bad request error

func ErrConflict

func ErrConflict(message string) *APIError

ErrConflict creates a conflict error

func ErrCredentialNotFound

func ErrCredentialNotFound(id string) *APIError

ErrCredentialNotFound creates a credential not found error

func ErrDatabase

func ErrDatabase(operation string) *APIError

ErrDatabase creates a database error

func ErrExecutionNotFound

func ErrExecutionNotFound(id string) *APIError

ErrExecutionNotFound creates an execution not found error

func ErrExpression

func ErrExpression(expression string, cause error) *APIError

ErrExpression creates an expression evaluation error

func ErrExternalService

func ErrExternalService(service string) *APIError

ErrExternalService creates an external service error

func ErrForbidden

func ErrForbidden(message string) *APIError

ErrForbidden creates a forbidden error

func ErrInternal

func ErrInternal(message string) *APIError

ErrInternal creates an internal server error

func ErrMethodNotAllowed

func ErrMethodNotAllowed(method string) *APIError

ErrMethodNotAllowed creates a method not allowed error

func ErrNodeNotFound

func ErrNodeNotFound(nodeType string) *APIError

ErrNodeNotFound creates a node not found error

func ErrNotFound

func ErrNotFound(resource string) *APIError

ErrNotFound creates a not found error

func ErrNotImplemented

func ErrNotImplemented(feature string) *APIError

ErrNotImplemented creates a not implemented error

func ErrPayloadTooLarge

func ErrPayloadTooLarge(maxSize int64) *APIError

ErrPayloadTooLarge creates a payload too large error

func ErrRateLimited

func ErrRateLimited(retryAfter int) *APIError

ErrRateLimited creates a rate limit error

func ErrServiceUnavailable

func ErrServiceUnavailable(message string) *APIError

ErrServiceUnavailable creates a service unavailable error

func ErrTemplateNotFound

func ErrTemplateNotFound(id string) *APIError

ErrTemplateNotFound creates a template not found error

func ErrUnauthorized

func ErrUnauthorized(message string) *APIError

ErrUnauthorized creates an unauthorized error

func ErrUnsupportedMediaType

func ErrUnsupportedMediaType(contentType string) *APIError

ErrUnsupportedMediaType creates an unsupported media type error

func ErrValidation

func ErrValidation(message string) *APIError

ErrValidation creates a validation error

func ErrValidationFields

func ErrValidationFields(fields map[string]string) *APIError

ErrValidationFields creates a validation error with field details

func ErrWorkflowInactive

func ErrWorkflowInactive(id string) *APIError

ErrWorkflowInactive creates a workflow inactive error

func ErrWorkflowNotFound

func ErrWorkflowNotFound(id string) *APIError

ErrWorkflowNotFound creates a workflow not found error

func NewAPIError

func NewAPIError(code ErrorCode, message string, statusCode int) *APIError

NewAPIError creates a new API 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) WithCause

func (e *APIError) WithCause(err error) *APIError

WithCause sets the underlying cause

func (*APIError) WithDetail

func (e *APIError) WithDetail(key string, value interface{}) *APIError

WithDetail adds a single detail to the error

func (*APIError) WithDetails

func (e *APIError) WithDetails(details map[string]interface{}) *APIError

WithDetails adds details to the error

func (*APIError) WithRequestInfo

func (e *APIError) WithRequestInfo(r *http.Request, requestID string) *APIError

WithRequestInfo adds request information

type APIKey

type APIKey struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	Key         string     `json:"key"`
	HashedKey   string     `json:"-"` // Never expose the actual key
	Permissions []string   `json:"permissions"`
	CreatedAt   time.Time  `json:"created_at"`
	LastUsed    time.Time  `json:"last_used"`
	ExpiresAt   *time.Time `json:"expires_at,omitempty"`
	Active      bool       `json:"active"`
}

APIKey represents an API key with metadata

type APIServer

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

APIServer provides REST API with workflow compatibility

func NewAPIServer

func NewAPIServer(eng engine.WorkflowEngine, scheduler *scheduler.WorkflowScheduler, storage storage.WorkflowStorage) *APIServer

NewAPIServer creates a new API server instance

func NewAPIServerWithConfig

func NewAPIServerWithConfig(eng engine.WorkflowEngine, scheduler *scheduler.WorkflowScheduler, storage storage.WorkflowStorage, config *APIServerConfig) *APIServer

NewAPIServerWithConfig creates a new API server with custom configuration

func (*APIServer) ActivateWorkflow

func (s *APIServer) ActivateWorkflow(w http.ResponseWriter, r *http.Request)

func (*APIServer) ApplyTemplate

func (s *APIServer) ApplyTemplate(w http.ResponseWriter, r *http.Request)

ApplyTemplate creates a new workflow from a template

func (*APIServer) BroadcastExecutionUpdate

func (s *APIServer) BroadcastExecutionUpdate(execution *model.WorkflowExecution)

BroadcastExecutionUpdate sends execution updates to all connected clients

func (*APIServer) CancelExecution

func (s *APIServer) CancelExecution(w http.ResponseWriter, r *http.Request)

func (*APIServer) CopilotChat

func (s *APIServer) CopilotChat(w http.ResponseWriter, r *http.Request)

CopilotChat handles conversational workflow building

func (*APIServer) CopilotExplain

func (s *APIServer) CopilotExplain(w http.ResponseWriter, r *http.Request)

CopilotExplain explains a workflow

func (*APIServer) CopilotFix

func (s *APIServer) CopilotFix(w http.ResponseWriter, r *http.Request)

CopilotFix suggests fixes for workflow errors

func (*APIServer) CopilotGenerate

func (s *APIServer) CopilotGenerate(w http.ResponseWriter, r *http.Request)

CopilotGenerate generates a workflow from a description

func (*APIServer) CopilotSuggest

func (s *APIServer) CopilotSuggest(w http.ResponseWriter, r *http.Request)

CopilotSuggest suggests nodes for a workflow

func (*APIServer) CreateCredential

func (s *APIServer) CreateCredential(w http.ResponseWriter, r *http.Request)

func (*APIServer) CreateExecution

func (s *APIServer) CreateExecution(w http.ResponseWriter, r *http.Request)

func (*APIServer) CreateSchedule

func (s *APIServer) CreateSchedule(w http.ResponseWriter, r *http.Request)

CreateSchedule handles POST /api/v1/schedules

func (*APIServer) CreateTag

func (s *APIServer) CreateTag(w http.ResponseWriter, r *http.Request)

func (*APIServer) CreateWorkflow

func (s *APIServer) CreateWorkflow(w http.ResponseWriter, r *http.Request)

func (*APIServer) DeactivateWorkflow

func (s *APIServer) DeactivateWorkflow(w http.ResponseWriter, r *http.Request)

func (*APIServer) DeleteCredential

func (s *APIServer) DeleteCredential(w http.ResponseWriter, r *http.Request)

func (*APIServer) DeleteExecution

func (s *APIServer) DeleteExecution(w http.ResponseWriter, r *http.Request)

func (*APIServer) DeleteSchedule

func (s *APIServer) DeleteSchedule(w http.ResponseWriter, r *http.Request)

DeleteSchedule handles DELETE /api/v1/schedules/{id}

func (*APIServer) DeleteTag

func (s *APIServer) DeleteTag(w http.ResponseWriter, r *http.Request)

func (*APIServer) DeleteWorkflow

func (s *APIServer) DeleteWorkflow(w http.ResponseWriter, r *http.Request)

func (*APIServer) DetailedHealth

func (s *APIServer) DetailedHealth(w http.ResponseWriter, r *http.Request)

DetailedHealth returns detailed health information

func (*APIServer) DisableSchedule

func (s *APIServer) DisableSchedule(w http.ResponseWriter, r *http.Request)

DisableSchedule handles POST /api/v1/schedules/{id}/disable

func (*APIServer) DiscardDLQItem

func (s *APIServer) DiscardDLQItem(w http.ResponseWriter, r *http.Request)

DiscardDLQItem discards a DLQ item

func (*APIServer) DuplicateWorkflow

func (s *APIServer) DuplicateWorkflow(w http.ResponseWriter, r *http.Request)

DuplicateWorkflow creates a copy of an existing workflow

func (*APIServer) EnableSchedule

func (s *APIServer) EnableSchedule(w http.ResponseWriter, r *http.Request)

EnableSchedule handles POST /api/v1/schedules/{id}/enable

func (*APIServer) EvaluateExpression

func (s *APIServer) EvaluateExpression(w http.ResponseWriter, r *http.Request)

func (*APIServer) ExecuteWorkflow

func (s *APIServer) ExecuteWorkflow(w http.ResponseWriter, r *http.Request)

func (*APIServer) ExecuteWorkflowAsync

func (s *APIServer) ExecuteWorkflowAsync(w http.ResponseWriter, r *http.Request)

ExecuteWorkflowAsync enqueues a workflow for async execution

func (*APIServer) ExecuteWorkflowByDefinition

func (s *APIServer) ExecuteWorkflowByDefinition(w http.ResponseWriter, r *http.Request)

ExecuteWorkflowByDefinition executes an inline workflow definition payload.

func (*APIServer) GetCredential

func (s *APIServer) GetCredential(w http.ResponseWriter, r *http.Request)

func (*APIServer) GetDLQItem

func (s *APIServer) GetDLQItem(w http.ResponseWriter, r *http.Request)

GetDLQItem gets a specific DLQ item

func (*APIServer) GetDLQStats

func (s *APIServer) GetDLQStats(w http.ResponseWriter, r *http.Request)

GetDLQStats returns DLQ statistics

func (*APIServer) GetExecution

func (s *APIServer) GetExecution(w http.ResponseWriter, r *http.Request)

func (*APIServer) GetJob

func (s *APIServer) GetJob(w http.ResponseWriter, r *http.Request)

GetJob returns details of a specific job

func (*APIServer) GetLDAP

func (s *APIServer) GetLDAP(w http.ResponseWriter, r *http.Request)

GetLDAP returns LDAP configuration (enterprise feature stub)

func (*APIServer) GetLicense

func (s *APIServer) GetLicense(w http.ResponseWriter, r *http.Request)

GetLicense returns license information (enterprise feature stub)

func (*APIServer) GetMetrics

func (s *APIServer) GetMetrics(w http.ResponseWriter, r *http.Request)

func (*APIServer) GetNodeType

func (s *APIServer) GetNodeType(w http.ResponseWriter, r *http.Request)

GetNodeType returns a specific node type

func (*APIServer) GetPerformanceStats

func (s *APIServer) GetPerformanceStats(w http.ResponseWriter, r *http.Request)

GetPerformanceStats returns performance statistics

func (*APIServer) GetSchedule

func (s *APIServer) GetSchedule(w http.ResponseWriter, r *http.Request)

GetSchedule handles GET /api/v1/schedules/{id}

func (*APIServer) GetScheduleHistory

func (s *APIServer) GetScheduleHistory(w http.ResponseWriter, r *http.Request)

GetScheduleHistory handles GET /api/v1/schedules/{id}/history

func (*APIServer) GetSettings

func (s *APIServer) GetSettings(w http.ResponseWriter, r *http.Request)

GetSettings returns system settings (n8n compatible)

func (*APIServer) GetTemplate

func (s *APIServer) GetTemplate(w http.ResponseWriter, r *http.Request)

GetTemplate returns a specific template

func (*APIServer) GetVersion

func (s *APIServer) GetVersion(w http.ResponseWriter, r *http.Request)

GetVersion returns version information

func (*APIServer) GetWorkflow

func (s *APIServer) GetWorkflow(w http.ResponseWriter, r *http.Request)

func (*APIServer) HandleWebSocket

func (s *APIServer) HandleWebSocket(w http.ResponseWriter, r *http.Request)

HandleWebSocket handles WebSocket connections for real-time updates

func (*APIServer) HealthCheck

func (s *APIServer) HealthCheck(w http.ResponseWriter, r *http.Request)

HealthCheck handles health check requests

func (*APIServer) ListCredentials

func (s *APIServer) ListCredentials(w http.ResponseWriter, r *http.Request)

func (*APIServer) ListDLQ

func (s *APIServer) ListDLQ(w http.ResponseWriter, r *http.Request)

ListDLQ lists items in the dead letter queue

func (*APIServer) ListExecutions

func (s *APIServer) ListExecutions(w http.ResponseWriter, r *http.Request)

func (*APIServer) ListJobs

func (s *APIServer) ListJobs(w http.ResponseWriter, r *http.Request)

ListJobs returns a list of jobs

func (*APIServer) ListNodeTypes

func (s *APIServer) ListNodeTypes(w http.ResponseWriter, r *http.Request)

ListNodeTypes returns available node types

func (*APIServer) ListSchedules

func (s *APIServer) ListSchedules(w http.ResponseWriter, r *http.Request)

ListSchedules handles GET /api/v1/schedules

func (*APIServer) ListTags

func (s *APIServer) ListTags(w http.ResponseWriter, r *http.Request)

func (*APIServer) ListTemplates

func (s *APIServer) ListTemplates(w http.ResponseWriter, r *http.Request)

ListTemplates returns all available workflow templates

func (*APIServer) ListWorkflows

func (s *APIServer) ListWorkflows(w http.ResponseWriter, r *http.Request)

func (*APIServer) ReadyCheck

func (s *APIServer) ReadyCheck(w http.ResponseWriter, r *http.Request)

ReadyCheck handles readiness check requests

func (*APIServer) RegisterRoutes

func (s *APIServer) RegisterRoutes(router *mux.Router)

RegisterRoutes registers all API routes

func (*APIServer) RetryDLQItem

func (s *APIServer) RetryDLQItem(w http.ResponseWriter, r *http.Request)

RetryDLQItem retries a DLQ item

func (*APIServer) RetryExecution

func (s *APIServer) RetryExecution(w http.ResponseWriter, r *http.Request)

func (*APIServer) SetJobQueue

func (s *APIServer) SetJobQueue(jq queue.JobQueue)

SetJobQueue sets the job queue for async execution

func (*APIServer) UpdateCredential

func (s *APIServer) UpdateCredential(w http.ResponseWriter, r *http.Request)

func (*APIServer) UpdateSchedule

func (s *APIServer) UpdateSchedule(w http.ResponseWriter, r *http.Request)

UpdateSchedule handles PUT /api/v1/schedules/{id}

func (*APIServer) UpdateSettings

func (s *APIServer) UpdateSettings(w http.ResponseWriter, r *http.Request)

UpdateSettings handles settings updates

func (*APIServer) UpdateTag

func (s *APIServer) UpdateTag(w http.ResponseWriter, r *http.Request)

func (*APIServer) UpdateWorkflow

func (s *APIServer) UpdateWorkflow(w http.ResponseWriter, r *http.Request)

type APIServerConfig

type APIServerConfig struct {
	// AllowedOrigins for WebSocket CORS (comma-separated in env)
	AllowedOrigins []string
	// DevMode enables permissive security settings
	DevMode bool
	// MaxPaginationLimit caps the number of items per page
	MaxPaginationLimit int
}

APIServerConfig configures the API server

func DefaultAPIServerConfig

func DefaultAPIServerConfig() *APIServerConfig

DefaultAPIServerConfig returns default configuration from environment

type AuthContext

type AuthContext struct {
	UserID      string
	SessionID   string
	APIKeyID    string
	Permissions []string
	AuthMethod  string // "jwt", "api_key"
}

AuthContext contains authentication information

func AuthFromContext

func AuthFromContext(ctx context.Context) *AuthContext

AuthFromContext retrieves authentication context from a context

func RequireAuthFromContext

func RequireAuthFromContext(ctx context.Context) *AuthContext

RequireAuthFromContext retrieves authentication context and panics if not found This should only be used in handlers that are protected by authentication middleware

func (*AuthContext) GetIdentifier

func (ac *AuthContext) GetIdentifier() string

GetIdentifier returns a unique identifier for the authenticated entity

func (*AuthContext) GetUserID

func (ac *AuthContext) GetUserID() string

GetUserID returns the user ID if available

func (*AuthContext) HasPermission

func (ac *AuthContext) HasPermission(permission string) bool

HasPermission checks if the authentication context has a specific permission

func (*AuthContext) IsAPIKey

func (ac *AuthContext) IsAPIKey() bool

IsAPIKey returns true if the authentication was done via API key

func (*AuthContext) IsJWT

func (ac *AuthContext) IsJWT() bool

IsJWT returns true if the authentication was done via JWT token

type AuthManager

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

AuthManager handles authentication for the API

func NewAuthManager

func NewAuthManager(jwtSecret string) *AuthManager

NewAuthManager creates a new authentication manager

func (*AuthManager) AuthenticationMiddleware

func (am *AuthManager) AuthenticationMiddleware(next http.Handler) http.Handler

AuthenticationMiddleware validates incoming requests

func (*AuthManager) CleanupExpiredSessions

func (am *AuthManager) CleanupExpiredSessions()

CleanupExpiredSessions removes expired sessions

func (*AuthManager) CreateAPIKey

func (am *AuthManager) CreateAPIKey(name string, permissions []string, expiresAt *time.Time) (*APIKey, error)

CreateAPIKey creates a new API key

func (*AuthManager) CreateJWTToken

func (am *AuthManager) CreateJWTToken(userID string, permissions []string, sessionID string) (string, error)

CreateJWTToken creates a new JWT token

func (*AuthManager) CreateSession

func (am *AuthManager) CreateSession(userID, ipAddress, userAgent string) *Session

CreateSession creates a new user session

func (*AuthManager) GetAPIKeyCount

func (am *AuthManager) GetAPIKeyCount() int

GetAPIKeyCount returns the number of active API keys

func (*AuthManager) GetSessionCount

func (am *AuthManager) GetSessionCount() int

GetSessionCount returns the number of active sessions

func (*AuthManager) InvalidateSession

func (am *AuthManager) InvalidateSession(sessionID string)

InvalidateSession removes a session

func (*AuthManager) ListAPIKeys

func (am *AuthManager) ListAPIKeys() []*APIKey

ListAPIKeys returns all API keys (without the actual key values)

func (*AuthManager) RequirePermission

func (am *AuthManager) RequirePermission(permission string) func(http.Handler) http.Handler

RequirePermission middleware to check specific permissions

func (*AuthManager) RevokeAPIKey

func (am *AuthManager) RevokeAPIKey(keyID string) error

RevokeAPIKey revokes an API key

func (*AuthManager) SetTokenTTL

func (am *AuthManager) SetTokenTTL(ttl time.Duration)

SetTokenTTL sets the JWT token time-to-live

type CredentialResponse

type CredentialResponse struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	CreatedAt time.Time `json:"createdAt,omitempty"`
	UpdatedAt time.Time `json:"updatedAt,omitempty"`
}

CredentialResponse represents a safe credential response without sensitive data

type DistributedWebSocketManager

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

DistributedWebSocketManager manages WebSocket connections across cluster nodes

func NewDistributedWebSocketManager

func NewDistributedWebSocketManager(nng *messaging.NNGMessaging) *DistributedWebSocketManager

NewDistributedWebSocketManager creates a new distributed WebSocket manager

func (*DistributedWebSocketManager) AddClient

func (m *DistributedWebSocketManager) AddClient(clientID string, conn *websocket.Conn)

AddClient registers a new WebSocket connection

func (*DistributedWebSocketManager) BroadcastExecutionUpdate

func (m *DistributedWebSocketManager) BroadcastExecutionUpdate(execution *model.WorkflowExecution) error

BroadcastExecutionUpdate broadcasts a workflow execution update to all clients

func (*DistributedWebSocketManager) BroadcastNodeExecution

func (m *DistributedWebSocketManager) BroadcastNodeExecution(execID, nodeID, status string, data map[string]interface{}) error

BroadcastNodeExecution broadcasts a node execution event

func (*DistributedWebSocketManager) BroadcastToCluster

func (m *DistributedWebSocketManager) BroadcastToCluster(msgType string, data map[string]interface{}) error

BroadcastToCluster broadcasts a message to all nodes in the cluster

func (*DistributedWebSocketManager) GetLocalClientCount

func (m *DistributedWebSocketManager) GetLocalClientCount() int

GetLocalClientCount returns the number of clients connected to this node

func (*DistributedWebSocketManager) GetLocalClients

func (m *DistributedWebSocketManager) GetLocalClients() []string

GetLocalClients returns a list of local client IDs

func (*DistributedWebSocketManager) PingClients

func (m *DistributedWebSocketManager) PingClients()

PingClients sends ping messages to all local clients to keep connections alive

func (*DistributedWebSocketManager) RemoveClient

func (m *DistributedWebSocketManager) RemoveClient(clientID string)

RemoveClient unregisters a WebSocket connection

func (*DistributedWebSocketManager) SendToClient

func (m *DistributedWebSocketManager) SendToClient(clientID string, msgType string, data map[string]interface{}) error

SendToClient sends a message to a specific local client

func (*DistributedWebSocketManager) StartPingRoutine

func (m *DistributedWebSocketManager) StartPingRoutine()

StartPingRoutine starts a goroutine that pings clients periodically

func (*DistributedWebSocketManager) Stats

func (m *DistributedWebSocketManager) Stats() map[string]interface{}

Stats returns statistics about WebSocket connections

type EndpointLimit

type EndpointLimit struct {
	RequestsPerSecond int
	Burst             int
	// Methods to apply limit to (empty = all methods)
	Methods []string
}

EndpointLimit defines rate limits for a specific endpoint

type EndpointValidator

type EndpointValidator struct {
	// Required fields
	RequiredFields []string

	// Field validators
	Fields map[string]FieldValidator

	// Custom validation function
	CustomValidator func(body map[string]interface{}) error
}

EndpointValidator defines validation rules for a specific endpoint

type ErrorCode

type ErrorCode string

ErrorCode represents a specific error type

const (
	// Client errors (4xx)
	ErrCodeBadRequest          ErrorCode = "BAD_REQUEST"
	ErrCodeUnauthorized        ErrorCode = "UNAUTHORIZED"
	ErrCodeForbidden           ErrorCode = "FORBIDDEN"
	ErrCodeNotFound            ErrorCode = "NOT_FOUND"
	ErrCodeMethodNotAllowed    ErrorCode = "METHOD_NOT_ALLOWED"
	ErrCodeConflict            ErrorCode = "CONFLICT"
	ErrCodeValidationFailed    ErrorCode = "VALIDATION_FAILED"
	ErrCodeRateLimitExceeded   ErrorCode = "RATE_LIMIT_EXCEEDED"
	ErrCodePayloadTooLarge     ErrorCode = "PAYLOAD_TOO_LARGE"
	ErrCodeUnsupportedMedia    ErrorCode = "UNSUPPORTED_MEDIA_TYPE"
	ErrCodeUnprocessableEntity ErrorCode = "UNPROCESSABLE_ENTITY"

	// Server errors (5xx)
	ErrCodeInternalError      ErrorCode = "INTERNAL_ERROR"
	ErrCodeNotImplemented     ErrorCode = "NOT_IMPLEMENTED"
	ErrCodeServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"
	ErrCodeDatabaseError      ErrorCode = "DATABASE_ERROR"
	ErrCodeExternalService    ErrorCode = "EXTERNAL_SERVICE_ERROR"

	// Domain-specific errors
	ErrCodeWorkflowNotFound   ErrorCode = "WORKFLOW_NOT_FOUND"
	ErrCodeWorkflowInactive   ErrorCode = "WORKFLOW_INACTIVE"
	ErrCodeExecutionNotFound  ErrorCode = "EXECUTION_NOT_FOUND"
	ErrCodeExecutionFailed    ErrorCode = "EXECUTION_FAILED"
	ErrCodeCredentialNotFound ErrorCode = "CREDENTIAL_NOT_FOUND"
	ErrCodeCredentialInvalid  ErrorCode = "CREDENTIAL_INVALID"
	ErrCodeNodeNotFound       ErrorCode = "NODE_NOT_FOUND"
	ErrCodeNodeExecutionError ErrorCode = "NODE_EXECUTION_ERROR"
	ErrCodeExpressionError    ErrorCode = "EXPRESSION_ERROR"
	ErrCodeTemplateNotFound   ErrorCode = "TEMPLATE_NOT_FOUND"
	ErrCodeWebhookNotFound    ErrorCode = "WEBHOOK_NOT_FOUND"
	ErrCodeSchedulerError     ErrorCode = "SCHEDULER_ERROR"
)

type ErrorHandler

type ErrorHandler struct {
	DevMode bool
	Logger  func(err *APIError)
}

ErrorHandler handles API errors and sends appropriate responses

func NewErrorHandler

func NewErrorHandler(devMode bool) *ErrorHandler

NewErrorHandler creates a new error handler

func (*ErrorHandler) Handle

func (h *ErrorHandler) Handle(w http.ResponseWriter, r *http.Request, err error, requestID string)

Handle processes an error and sends the response

func (*ErrorHandler) HandleAPIError

func (h *ErrorHandler) HandleAPIError(w http.ResponseWriter, r *http.Request, apiErr *APIError, requestID string)

HandleAPIError handles an APIError directly

func (*ErrorHandler) RecoveryMiddleware

func (h *ErrorHandler) RecoveryMiddleware(next http.Handler) http.Handler

RecoveryMiddleware recovers from panics and returns an error response

func (*ErrorHandler) SetLogger

func (h *ErrorHandler) SetLogger(logger func(err *APIError))

SetLogger sets the error logger

type FieldValidator

type FieldValidator struct {
	Type      string // string, number, boolean, array, object
	Required  bool
	MinLength int
	MaxLength int
	MinValue  float64
	MaxValue  float64
	Pattern   string
	Enum      []interface{}
}

FieldValidator defines validation rules for a field

type JSONValidator

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

JSONValidator provides JSON-specific validation

func NewJSONValidator

func NewJSONValidator() *JSONValidator

NewJSONValidator creates a new JSON validator

func (*JSONValidator) ValidateJSON

func (jv *JSONValidator) ValidateJSON(data []byte) error

ValidateJSON validates JSON structure

type JWTClaims

type JWTClaims struct {
	UserID      string   `json:"user_id"`
	SessionID   string   `json:"session_id"`
	Permissions []string `json:"permissions"`
	jwt.RegisteredClaims
}

JWTClaims represents JWT token claims

type LimitedReader

type LimitedReader struct {
	R io.Reader
	N int64
}

LimitedReader wraps a reader with a size limit

func (*LimitedReader) Read

func (l *LimitedReader) Read(p []byte) (n int, err error)

Read implements io.Reader with size limiting

type RateLimiter

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

RateLimiter provides rate limiting functionality

func NewRateLimiter

func NewRateLimiter(config *RateLimiterConfig) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(ip string, endpoint string, method string) (bool, int)

Allow checks if a request should be allowed

func (*RateLimiter) Middleware

func (rl *RateLimiter) Middleware(errorHandler *ErrorHandler) func(http.Handler) http.Handler

Middleware returns an HTTP middleware for rate limiting

func (*RateLimiter) Stats

func (rl *RateLimiter) Stats() map[string]interface{}

Stats returns current rate limiter statistics

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the rate limiter cleanup goroutine

type RateLimiterConfig

type RateLimiterConfig struct {
	// Global rate limiting
	GlobalRequestsPerSecond int
	GlobalBurst             int

	// Per-IP rate limiting
	IPRequestsPerSecond int
	IPBurst             int

	// Per-endpoint rate limiting (optional overrides)
	EndpointLimits map[string]EndpointLimit

	// Cleanup interval for expired entries
	CleanupInterval time.Duration

	// Enable/disable
	Enabled bool

	// TrustedProxies is a list of trusted proxy IP addresses or CIDR ranges
	// Only trust X-Forwarded-For headers from these proxies
	TrustedProxies []string
}

RateLimiterConfig configures the rate limiter

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() *RateLimiterConfig

DefaultRateLimiterConfig returns sensible defaults

type RequestValidator

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

RequestValidator provides request validation functionality

func NewRequestValidator

func NewRequestValidator(config *ValidatorConfig, errorHandler *ErrorHandler) *RequestValidator

NewRequestValidator creates a new request validator

func (*RequestValidator) Middleware

func (rv *RequestValidator) Middleware() func(http.Handler) http.Handler

Middleware returns an HTTP middleware for request validation

func (*RequestValidator) ValidateBody

func (rv *RequestValidator) ValidateBody(r *http.Request, body map[string]interface{}) *APIError

ValidateBody validates the request body against endpoint rules

func (*RequestValidator) ValidateRequest

func (rv *RequestValidator) ValidateRequest(r *http.Request) *APIError

ValidateRequest validates an HTTP request

type Session

type Session struct {
	ID        string    `json:"id"`
	UserID    string    `json:"user_id"`
	CreatedAt time.Time `json:"created_at"`
	ExpiresAt time.Time `json:"expires_at"`
	IPAddress string    `json:"ip_address"`
	UserAgent string    `json:"user_agent"`
}

Session represents a user session

type SlidingWindowRateLimiter

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

SlidingWindowRateLimiter implements sliding window rate limiting for more accurate rate limiting at window boundaries

func NewSlidingWindowRateLimiter

func NewSlidingWindowRateLimiter(windowSize time.Duration, maxRequests int) *SlidingWindowRateLimiter

NewSlidingWindowRateLimiter creates a sliding window rate limiter

func (*SlidingWindowRateLimiter) Allow

func (sw *SlidingWindowRateLimiter) Allow(key string) bool

Allow checks if a request from the given key should be allowed

type Template

type Template struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Category    string                 `json:"category"`
	Workflow    *model.Workflow        `json:"workflow"`
	Tags        []string               `json:"tags"`
	Metadata    map[string]interface{} `json:"metadata"`
}

Template represents a workflow template

type TokenBucket

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

TokenBucket implements the token bucket algorithm

func NewTokenBucket

func NewTokenBucket(tokensPerSecond int, burst int) *TokenBucket

NewTokenBucket creates a new token bucket

func (*TokenBucket) Allow

func (tb *TokenBucket) Allow() bool

Allow checks if a request is allowed and consumes a token if so

func (*TokenBucket) LastUsed

func (tb *TokenBucket) LastUsed() time.Time

LastUsed returns when this bucket was last accessed

func (*TokenBucket) Tokens

func (tb *TokenBucket) Tokens() float64

Tokens returns the current number of available tokens

type ValidatorConfig

type ValidatorConfig struct {
	// Maximum request body size in bytes
	MaxBodySize int64

	// Allowed content types
	AllowedContentTypes []string

	// Enable strict content type checking
	StrictContentType bool

	// Enable JSON validation
	ValidateJSON bool

	// Custom validators per endpoint
	EndpointValidators map[string]EndpointValidator
}

ValidatorConfig configures the request validator

func DefaultValidatorConfig

func DefaultValidatorConfig() *ValidatorConfig

DefaultValidatorConfig returns sensible defaults

Jump to

Keyboard shortcuts

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