engine

package
v0.0.0-...-cf3d621 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2025 License: Apache-2.0 Imports: 37 Imported by: 0

Documentation

Overview

Package engine provides the core workflow execution engine for nFlow Runtime. This file implements a thread-safe repository pattern for managing global configuration and resources, eliminating race conditions.

Package engine provides the core workflow execution engine for nFlow Runtime. This file contains resource limit management for JavaScript VMs to prevent resource exhaustion attacks and ensure stable operation.

Package engine provides the core workflow execution engine for nFlow Runtime. This file implements JavaScript sandboxing to restrict dangerous operations and provide a secure execution environment for user scripts.

Index

Constants

This section is empty.

Variables

View Source
var (
	Steps map[string]Step = make(map[string]Step)
	// ActorDataMutex protege el acceso a actor.Data en todos los steps
	ActorDataMutex sync.RWMutex
)
View Source
var (
	ErrMemoryLimitExceeded    = errors.New("memory limit exceeded")
	ErrTimeLimitExceeded      = errors.New("execution time limit exceeded")
	ErrOperationLimitExceeded = errors.New("operation limit exceeded")
	ErrExecutionInterrupted   = errors.New("execution interrupted")
)

Limit errors

View Source
var EchoSessionsMutex = &defaultSessionManager{}

EchoSessionsMutex para compatibilidad

View Source
var PayloadSessionMutex = &defaultSessionManager{}

PayloadSessionMutex para compatibilidad

View Source
var Plugins map[string]NflowPlugin

Functions

func AddFeatureSession

func AddFeatureSession(vm *goja.Runtime, c echo.Context)

func AddFeatureSessionOptimized

func AddFeatureSessionOptimized(vm *goja.Runtime, c echo.Context)

addFeatureSessionOptimized usa el SessionManager para mejor performance

func AddFeatureTemplate

func AddFeatureTemplate(vm *goja.Runtime, c echo.Context)

func AddFeatureToken

func AddFeatureToken(vm *goja.Runtime, c echo.Context)

func AddFeatureUsers

func AddFeatureUsers(vm *goja.Runtime, c echo.Context)

func AddGlobals

func AddGlobals(vm *goja.Runtime, c echo.Context)

func CloneValue

func CloneValue(value goja.Value, vm *goja.Runtime) goja.Value

func CloseDBPool

func CloseDBPool() error

CloseDBPool cierra el pool de conexiones

func CreateRuntimeController

func CreateRuntimeController(cc *model.Controller) model.Runeable

CreateRuntimeController crea un wrapper para model.Controller

func DisableTracker

func DisableTracker()

func EnableTracker

func EnableTracker()

func Execute

func Execute(cc *model.Controller, c echo.Context, vm *goja.Runtime, next string, vars model.Vars, currentProcess *process.Process, payload goja.Value, fork bool)

Execute runs the main workflow execution loop. It processes nodes sequentially, following the connections between them until there are no more nodes to execute. The function handles forking for parallel execution and maintains the workflow state. Parameters:

  • cc: The controller containing the workflow definition
  • c: Echo context for HTTP request/response
  • vm: JavaScript VM for executing node code
  • next: ID of the next node to execute
  • vars: Variables extracted from the URL path
  • currentProcess: Current process instance tracking execution
  • payload: Data passed between nodes
  • fork: Whether this is a forked execution

func ExecuteWithRetry

func ExecuteWithRetry(ctx context.Context, fn func(*sql.Conn) error) error

ExecuteWithRetry ejecuta una query con reintentos

func GetDB

func GetDB() (*sql.DB, error)

func GetDBOptimized

func GetDBOptimized() (*sql.DB, error)

GetDBOptimized obtiene una conexión del pool optimizado

func GetDBStats

func GetDBStats() map[string]interface{}

GetDBStats retorna las estadísticas actuales del pool

func GetPlaybook

func GetPlaybook(ctx context.Context, conn *sql.Conn, pbName string) (map[string]map[string]*model.Playbook, error)

func GetProfile

func GetProfile(c echo.Context) map[string]string

func GetProfileOptimized

func GetProfileOptimized(c echo.Context) map[string]string

func GetRedisClient

func GetRedisClient() *redis.Client

GetRedisClient returns the current Redis client (compatibility helper)

func GetRequireRegistry

func GetRequireRegistry() *require.Registry

GetRequireRegistry retorna el registry de require

func GetTokenFromDB

func GetTokenFromDB(paramName string) []map[string]interface{}

func GetUserFromDB

func GetUserFromDB(paramUsername string) map[string]interface{}

func GetWorkflow

func GetWorkflow(c echo.Context, playbooks map[string]map[string]*model.Playbook, wfPath string, method string, appName string) (model.Runeable, model.Vars, int, string, error)

func InitDBPool

func InitDBPool() error

InitDBPool inicializa el pool de conexiones

func InitializeImmutableWorkflow

func InitializeImmutableWorkflow(cc *model.Controller)

InitializeImmutableWorkflow inicializa el manager con un controller

func InitializePlaybookRepository

func InitializePlaybookRepository(db *sql.DB)

InitializePlaybookRepository inicializa el repository con la base de datos

func IsResourceLimitError

func IsResourceLimitError(err error) bool

IsResourceLimitError checks if an error is due to resource limits

func IsTrackerEnabled

func IsTrackerEnabled() bool

Public API functions for runtime control

func LoadPlugins

func LoadPlugins()

func QueryWithTimeout

func QueryWithTimeout(ctx context.Context, timeout time.Duration, query string, args ...interface{}) (*sql.Rows, error)

QueryWithTimeout ejecuta una query con timeout

func Run

func Run(cc *model.Controller, c echo.Context, vars model.Vars, next string, endpoint string, uuid1 string, payload goja.Value) error

Run ejecuta el workflow

func RunWithCallback

func RunWithCallback(cc *model.Controller, c echo.Context, vars model.Vars, next string, endpoint string, uuid1 string, payload goja.Value) error

RunWithCallback ejecuta el workflow con callback

func SetupJSContext

func SetupJSContext(vm *goja.Runtime, c echo.Context)

SetupJSContext configures the JavaScript VM with the wrapped context

func ShutdownTracker

func ShutdownTracker()

func StartTracker

func StartTracker(numWorkers int)

StartTracker initializes the high-performance tracker system

func UpdateQueries

func UpdateQueries()

func ValidateTokenDB

func ValidateTokenDB(c echo.Context, name string) bool

func ValidateUserDB

func ValidateUserDB(username string, password string) bool

Types

type BatchProcessor

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

type ConfigBasedate

type ConfigBasedate struct {
	DatabaseURL    string `toml:"url"`
	DatabaseDriver string `toml:"driver"`
	DatabaseInit   string `toml:"init"`
}

ConfigBasedate is ...

type ConfigMail

type ConfigMail struct {
	MailSMTP     string `toml:"smtp"`
	MailSMTPPort string `toml:"port"`
	MailFrom     string `toml:"from"`
	MailPassword string `toml:"password"`
}

ConfigMail is ...

type ConfigRepository

type ConfigRepository interface {
	GetConfig() *ConfigWorkspace
	SetConfig(config ConfigWorkspace)
	GetRedisClient() *redis.Client
	SetRedisClient(client *redis.Client)
	GetDB() (*sql.DB, error)
	SetDB(database *sql.DB)
}

ConfigRepository manages thread-safe access to configuration and global resources

func GetConfigRepository

func GetConfigRepository() ConfigRepository

GetConfigRepository returns the singleton instance of the repository

type ConfigWorkspace

type ConfigWorkspace struct {
	ConfigBasedate       ConfigBasedate    `toml:"database"`
	ConfigMail           ConfigMail        `toml:"mail"`
	URLConfig            URLConfig         `toml:"url"`
	MongoConfig          MongoConfig       `toml:"mongo"`
	PluginConfig         PluginConfig      `toml:"plugin"`
	RedisConfig          RedisConfig       `toml:"redis"`
	PgSessionConfig      PgSessionConfig   `toml:"pg_session"`
	TwilioConfig         TwilioConfig      `toml:"twilio"`
	Env                  map[string]string `toml:"env"`
	HttpsEngineConfig    HttpsConfig       `toml:"https_engine"`
	HttpsDesingnerConfig HttpsConfig       `toml:"https_designer"`
	DatabaseNflow        DatabaseNflow     `toml:"database_nflow"`
	VMPoolConfig         VMPoolConfig      `toml:"vm_pool"`
	TrackerConfig        TrackerConfig     `toml:"tracker"`
	DebugConfig          DebugConfig       `toml:"debug"`
	MonitorConfig        MonitorConfig     `toml:"monitor"`
	RateLimitConfig      RateLimitConfig   `toml:"rate_limit"`
}

ConfigWorkspace represents the complete configuration structure for nFlow Runtime. It is loaded from the config.toml file and contains all settings for databases, services, plugins, and security configurations.

func GetConfig

func GetConfig() *ConfigWorkspace

GetConfig returns the current configuration (compatibility helper)

func GetConfigReference

func GetConfigReference() *ConfigWorkspace

Utility functions

type DBPool

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

DBPool gestiona un pool de conexiones optimizado

type DBStats

type DBStats struct {
	TotalQueries  int64
	ActiveConns   int
	IdleConns     int
	WaitTime      time.Duration
	LastError     error
	LastErrorTime time.Time
	// contains filtered or unexported fields
}

DBStats almacena estadísticas del pool

type DatabaseNflow

type DatabaseNflow struct {
	Driver                      string `tom:"driver"`
	DSN                         string `tom:"dsn"`
	Query                       string `tom:"query"`
	QueryGetUser                string `tom:"QueryGetUser"`
	QueryGetApp                 string `tom:"QueryGetApp"`
	QueryGetModules             string `tom:"QueryGetModules"`
	QueryCountModulesByName     string `tom:"QueryCountModulesByName"`
	QueryGetModuleByName        string `tom:"QueryGetModuleByName"`
	QueryUpdateModModuleByName  string `tom:"QueryUpdateModModuleByName"`
	QueryUpdateFormModuleByName string `tom:"QueryUpdateFormModuleByName"`
	QueryUpdateCodeModuleByName string `tom:"QueryUpdateCodeModuleByName"`
	QueryUpdateApp              string `tom:"QueryUpdateApp"`
	QueryInsertModule           string `tom:"QueryInsertModule"`
	QueryDeleteModule           string `tom:"QueryDeleteModule"`
	QueryInsertLog              string `tom:"QueryInsertLog"`
	QueryGetToken               string `tom:"QueryGetToken"`
	QueryGetTemplateCount       string `tom:"QueryGetTemplateCount"`
	QueryGetTemplate            string `tom:"QueryGetTemplate"`
	QueryGetTemplates           string `tom:"QueryGetTemplates"`
	QueryUpdateTemplate         string `tom:"QueryUpdateTemplate"`
	QueryInsertTemplate         string `tom:"QueryInsertTemplate"`
	QueryDeleteTemplate         string `tom:"QueryDeleteTemplate"`
}

type DebugConfig

type DebugConfig struct {
	Enabled     bool   `toml:"enabled"`      // Enable debug endpoints (default: false)
	AuthToken   string `toml:"auth_token"`   // Optional auth token for debug endpoints
	AllowedIPs  string `toml:"allowed_ips"`  // Comma-separated list of allowed IPs (empty = all)
	EnablePprof bool   `toml:"enable_pprof"` // Enable Go pprof endpoints (default: false)
}

DebugConfig configures debug endpoints availability and security. When enabled, provides detailed system information for troubleshooting.

type EchoContextManager

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

EchoContextManager provides thread-safe access to Echo context

func NewEchoContextManager

func NewEchoContextManager(c echo.Context) *EchoContextManager

NewEchoContextManager creates a new thread-safe Echo context wrapper

func (*EchoContextManager) GetContext

func (m *EchoContextManager) GetContext() echo.Context

GetContext returns a thread-safe context wrapper

type HttpsConfig

type HttpsConfig struct {
	Enable      bool   `tom:"enable"`
	Cert        string `tom:"cert"`
	Key         string `tom:"key"`
	Address     string `tom:"address"`
	Description string `tom:"description"`
	HTTPBasic   bool   `tom:"httpbasic"`
}

type ImmutableWorkflowManager

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

ImmutableWorkflowManager maneja snapshots inmutables

func GetWorkflowManager

func GetWorkflowManager() *ImmutableWorkflowManager

GetWorkflowManager retorna el manager global

func (*ImmutableWorkflowManager) GetSnapshot

GetSnapshot retorna el snapshot actual (lock-free read)

func (*ImmutableWorkflowManager) UpdateWorkflow

func (iwm *ImmutableWorkflowManager) UpdateWorkflow(cc *model.Controller)

UpdateWorkflow actualiza el snapshot inmutable (thread-safe)

type ImmutableWorkflowSnapshot

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

ImmutableWorkflowSnapshot representa un snapshot inmutable del workflow

func GetImmutableWorkflow

func GetImmutableWorkflow() *ImmutableWorkflowSnapshot

GetImmutableWorkflow retorna el snapshot actual

func (*ImmutableWorkflowSnapshot) GetNode

func (iws *ImmutableWorkflowSnapshot) GetNode(nodeID string) *model.Node

GetNode retorna un nodo específico (thread-safe)

func (*ImmutableWorkflowSnapshot) GetPlaybook

func (iws *ImmutableWorkflowSnapshot) GetPlaybook() map[string]*model.Node

GetPlaybook retorna el playbook inmutable

func (*ImmutableWorkflowSnapshot) GetStartNextNode

func (iws *ImmutableWorkflowSnapshot) GetStartNextNode() (string, error)

GetStartNextNode retorna el siguiente nodo desde start (thread-safe)

func (*ImmutableWorkflowSnapshot) GetStartNode

func (iws *ImmutableWorkflowSnapshot) GetStartNode() *model.Node

GetStartNode retorna el nodo de inicio (thread-safe)

func (*ImmutableWorkflowSnapshot) GetVersion

func (iws *ImmutableWorkflowSnapshot) GetVersion() int64

GetVersion retorna la versión del snapshot

func (*ImmutableWorkflowSnapshot) HasPlaybook

func (iws *ImmutableWorkflowSnapshot) HasPlaybook() bool

HasPlaybook verifica si hay un playbook válido

type IsolatedContext

type IsolatedContext struct {
	echo.Context
	// contains filtered or unexported fields
}

IsolatedContext provides a context for goroutines that doesn't share HTTP response

func NewIsolatedContext

func NewIsolatedContext(c echo.Context) *IsolatedContext

NewIsolatedContext creates a new isolated context from an Echo context

func (*IsolatedContext) FormParams

func (ic *IsolatedContext) FormParams() (url.Values, error)

FormParams returns form params from the cloned request

func (*IsolatedContext) FormValue

func (ic *IsolatedContext) FormValue(name string) string

FormValue returns form value from the cloned request

func (*IsolatedContext) Get

func (ic *IsolatedContext) Get(key string) interface{}

Get retrieves a value from context

func (*IsolatedContext) GetCookies

func (ic *IsolatedContext) GetCookies() []*http.Cookie

GetCookies returns the collected cookies

func (*IsolatedContext) GetHeaders

func (ic *IsolatedContext) GetHeaders() http.Header

GetHeaders returns the collected headers

func (*IsolatedContext) GetOutput

func (ic *IsolatedContext) GetOutput() string

GetOutput returns the buffered output

func (*IsolatedContext) HTML

func (ic *IsolatedContext) HTML(code int, html string) error

HTML writes HTML response to buffer

func (*IsolatedContext) JSON

func (ic *IsolatedContext) JSON(code int, i interface{}) error

JSON writes JSON response to buffer

func (*IsolatedContext) Redirect

func (ic *IsolatedContext) Redirect(code int, url string) error

Redirect captures redirect but doesn't execute it

func (*IsolatedContext) Request

func (ic *IsolatedContext) Request() *http.Request

Request returns the cloned request

func (*IsolatedContext) Response

func (ic *IsolatedContext) Response() *echo.Response

Response returns an isolated response that doesn't affect the original

func (*IsolatedContext) Set

func (ic *IsolatedContext) Set(key string, val interface{})

Set sets a value in context

func (*IsolatedContext) String

func (ic *IsolatedContext) String(code int, s string) error

String writes string response to buffer

type JSContextWrapper

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

JSContextWrapper wraps an Echo context to expose its methods to JavaScript

func NewJSContextWrapper

func NewJSContextWrapper(c echo.Context) *JSContextWrapper

NewJSContextWrapper creates a wrapper that exposes Echo context methods to JavaScript

func (*JSContextWrapper) FormValue

func (w *JSContextWrapper) FormValue(name string) string

FormValue returns form value by name - exposed to JavaScript

func (*JSContextWrapper) Get

func (w *JSContextWrapper) Get(key string) interface{}

Get retrieves data from context - exposed to JavaScript

func (*JSContextWrapper) JSON

func (w *JSContextWrapper) JSON(code int, i interface{}) error

JSON sends a JSON response - exposed to JavaScript

func (*JSContextWrapper) Param

func (w *JSContextWrapper) Param(name string) string

Param returns path parameter by name - exposed to JavaScript

func (*JSContextWrapper) QueryParam

func (w *JSContextWrapper) QueryParam(name string) string

QueryParam returns query parameter by name - exposed to JavaScript

func (*JSContextWrapper) Redirect

func (w *JSContextWrapper) Redirect(code int, url string) error

Redirect performs an HTTP redirect - exposed to JavaScript

func (*JSContextWrapper) Request

func (w *JSContextWrapper) Request() interface{}

Request returns the HTTP request - exposed to JavaScript

func (*JSContextWrapper) Response

func (w *JSContextWrapper) Response() interface{}

Response returns the HTTP response - exposed to JavaScript

func (*JSContextWrapper) Set

func (w *JSContextWrapper) Set(key string, val interface{})

Set saves data in context - exposed to JavaScript

func (*JSContextWrapper) String

func (w *JSContextWrapper) String(code int, s string) error

String sends a string response - exposed to JavaScript

type Module

type Module struct {
	Form string
	Mod  string
	Code string
}

type MongoConfig

type MongoConfig struct {
	URL string `tom:"url"`
}

type MonitorConfig

type MonitorConfig struct {
	Enabled               bool   `toml:"enabled"`                 // Enable monitoring endpoints (default: true)
	HealthCheckPath       string `toml:"health_check_path"`       // Health check endpoint path (default: /health)
	MetricsPath           string `toml:"metrics_path"`            // Prometheus metrics path (default: /metrics)
	EnableDetailedMetrics bool   `toml:"enable_detailed_metrics"` // Include detailed metrics (default: false)
	MetricsPort           string `toml:"metrics_port"`            // Separate port for metrics (empty = same port)
}

MonitorConfig configures monitoring and health check endpoints. Provides Prometheus-compatible metrics and comprehensive health checks.

type NflowPlugin

type NflowPlugin interface {
	Run(c echo.Context, vars map[string]string, payloadIn interface{}, dromedary_data string, callback chan string) (payload_out interface{}, next string, err error)
	Name() string
	AddFeatureJS() map[string]interface{}
}

type PgSessionConfig

type PgSessionConfig struct {
	Url string `tom:"url"`
}

type PlaybookRepository

type PlaybookRepository interface {
	Get(appName string) (map[string]map[string]*model.Playbook, error)
	Set(appName string, playbooks map[string]map[string]*model.Playbook)
	NeedsReload(appName string) bool
	SetReloaded(appName string)
	LoadPlaybook(ctx context.Context, appName string) (map[string]map[string]*model.Playbook, error)
	InvalidateCache(appName string)
	InvalidateAllCache()
	GetCacheSize() int
}

PlaybookRepository maneja el acceso thread-safe a los playbooks

func GetPlaybookRepository

func GetPlaybookRepository() PlaybookRepository

GetPlaybookRepository retorna el repository actual

func NewPlaybookRepository

func NewPlaybookRepository(db *sql.DB) PlaybookRepository

NewPlaybookRepository crea una nueva instancia del repository

type PluginConfig

type PluginConfig struct {
	Plugins []string `toml:"plugins"`
}

type PreparedStatement

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

PreparedStatement gestiona statements preparados de forma segura

func GetPreparedStatement

func GetPreparedStatement(query string) (*PreparedStatement, error)

GetPreparedStatement obtiene o crea un statement preparado

type RateLimitConfig

type RateLimitConfig struct {
	Enabled bool `toml:"enabled"` // Enable rate limiting (default: false)

	// IP rate limiting
	IPRateLimit     int `toml:"ip_rate_limit"`     // Requests per IP per window (default: 100)
	IPWindowMinutes int `toml:"ip_window_minutes"` // Time window in minutes (default: 1)
	IPBurstSize     int `toml:"ip_burst_size"`     // Burst size for IP limiting (default: 10)

	// Storage backend
	Backend         string `toml:"backend"`          // Backend type: "memory" or "redis" (default: "memory")
	CleanupInterval int    `toml:"cleanup_interval"` // Cleanup interval in minutes for memory backend (default: 10)

	// Response configuration
	RetryAfterHeader bool   `toml:"retry_after_header"` // Include Retry-After header (default: true)
	ErrorMessage     string `toml:"error_message"`      // Custom error message (default: "Rate limit exceeded")

	// Exclusions
	ExcludedIPs   string `toml:"excluded_ips"`   // Comma-separated IPs to exclude
	ExcludedPaths string `toml:"excluded_paths"` // Comma-separated paths to exclude
}

RateLimitConfig configures IP-based rate limiting for API endpoints. Supports configurable storage backends and exclusion rules.

type RedisConfig

type RedisConfig struct {
	Host              string `tom:"host"`
	Password          string `tom:"password"`
	MaxConnectionPool int    `tom:"maxconnectionpool"`
}

type RepositoryModules

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

func GetRepositoryModules

func GetRepositoryModules() *RepositoryModules

func (*RepositoryModules) GetModule

func (r *RepositoryModules) GetModule(name string) (Module, bool)

func (*RepositoryModules) GetModuleWithFallback

func (r *RepositoryModules) GetModuleWithFallback(name string, ctx context.Context, conn *sql.Conn) (Module, bool)

func (*RepositoryModules) IsDinamic

func (r *RepositoryModules) IsDinamic() bool

func (*RepositoryModules) SetDinamic

func (r *RepositoryModules) SetDinamic(dinamic bool)

type RepositoryTemplate

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

func GetRepositoryTemplate

func GetRepositoryTemplate() *RepositoryTemplate

func (*RepositoryTemplate) AddTemplate

func (r *RepositoryTemplate) AddTemplate(name, content string)

func (*RepositoryTemplate) ClearTemplates

func (r *RepositoryTemplate) ClearTemplates()

func (*RepositoryTemplate) GetTemplate

func (r *RepositoryTemplate) GetTemplate(name string) (string, bool)

func (*RepositoryTemplate) HasTemplate

func (r *RepositoryTemplate) HasTemplate(name string) bool

func (*RepositoryTemplate) InicializarTemplate

func (r *RepositoryTemplate) InicializarTemplate(templates map[string]string)

func (*RepositoryTemplate) IsDinamic

func (r *RepositoryTemplate) IsDinamic() bool

func (*RepositoryTemplate) ListTemplates

func (r *RepositoryTemplate) ListTemplates() []string

func (*RepositoryTemplate) RemoveTemplate

func (r *RepositoryTemplate) RemoveTemplate(name string)

func (*RepositoryTemplate) SetDinamic

func (r *RepositoryTemplate) SetDinamic(dinamic bool)

func (*RepositoryTemplate) TemplateCount

func (r *RepositoryTemplate) TemplateCount() int

type RuntimeController

type RuntimeController struct {
	*model.Controller
}

RuntimeController es un wrapper que hace que model.Controller implemente Runeable

func (*RuntimeController) GetMethods

func (rc *RuntimeController) GetMethods() []string

GetMethods implementa el método requerido por la interfaz Runeable

func (*RuntimeController) Run

func (rc *RuntimeController) Run(c echo.Context, vars model.Vars, next string, endpoint string, uuid1 string, payload goja.Value) error

Run implementa el método requerido por la interfaz Runeable

type SandboxConfig

type SandboxConfig struct {
	AllowedGlobals   map[string]bool
	AllowedModules   map[string]bool
	BlockedFunctions []string
	EnableFileSystem bool
	EnableNetwork    bool
	EnableProcess    bool
}

SandboxConfig defines the sandbox configuration

func DefaultSandboxConfig

func DefaultSandboxConfig() SandboxConfig

DefaultSandboxConfig returns a secure default configuration

func GetSandboxConfigFromConfig

func GetSandboxConfigFromConfig() SandboxConfig

GetSandboxConfigFromConfig gets sandbox configuration from config

type SessionManager

type SessionManager interface {
	Lock()
	Unlock()
	RLock()
	RUnlock()
}

SessionManager interfaz para manejo de sesiones

type Step

type Step interface {
	Run(cc *model.Controller, actor *model.Node, c echo.Context, vm *goja.Runtime, connectionNext string, vars model.Vars, currentProcess *process.Process, payload goja.Value) (string, goja.Value, error)
}

type StepGorutine

type StepGorutine struct {
}

func (*StepGorutine) Run

func (s *StepGorutine) Run(cc *model.Controller, actor *model.Node, c echo.Context, vm *goja.Runtime, connectionNext string, vars model.Vars, currentProcess *process.Process, payload goja.Value) (string, goja.Value, error)

type StepJS

type StepJS struct {
}

func (*StepJS) Run

func (s *StepJS) Run(cc *model.Controller, actor *model.Node, c echo.Context, vm *goja.Runtime, connection_next string, vars model.Vars, currentProcess *process.Process, payload goja.Value) (string, goja.Value, error)

type StepPlugin

type StepPlugin struct {
}

func (*StepPlugin) Run

func (s *StepPlugin) Run(cc *model.Controller, actor *model.Node, c echo.Context, vm *goja.Runtime, connectionNext string, vars model.Vars, currentProcess *process.Process, payload goja.Value) (string, goja.Value, error)

type StepPluginCallback

type StepPluginCallback struct {
}

func (*StepPluginCallback) Run

func (s *StepPluginCallback) Run(cc *model.Controller, actor *model.Node, c echo.Context, vm *goja.Runtime, connection_next string, vars model.Vars, currentProcess *process.Process, payload goja.Value) (string, goja.Value, error)

type SyncContext

type SyncContext struct {
	echo.Context
	// contains filtered or unexported fields
}

SyncContext wraps an Echo context to make it thread-safe

func (*SyncContext) Bind

func (sc *SyncContext) Bind(i interface{}) error

Bind binds request body with request lock

func (*SyncContext) Echo

func (sc *SyncContext) Echo() *echo.Echo

Echo returns the Echo instance

func (*SyncContext) FormParams

func (sc *SyncContext) FormParams() (url.Values, error)

FormParams gets form params with request lock

func (*SyncContext) FormValue

func (sc *SyncContext) FormValue(name string) string

FormValue gets form value with request lock

func (*SyncContext) Get

func (sc *SyncContext) Get(key string) interface{}

Get retrieves a value from context with read lock

func (*SyncContext) HTML

func (sc *SyncContext) HTML(code int, html string) error

HTML renders HTML with response lock

func (*SyncContext) JSON

func (sc *SyncContext) JSON(code int, i interface{}) error

JSON sends JSON response with response lock

func (*SyncContext) Param

func (sc *SyncContext) Param(name string) string

Param gets path param with request lock

func (*SyncContext) ParamNames

func (sc *SyncContext) ParamNames() []string

ParamNames gets param names with request lock

func (*SyncContext) ParamValues

func (sc *SyncContext) ParamValues() []string

ParamValues gets param values with request lock

func (*SyncContext) Path

func (sc *SyncContext) Path() string

Path returns the path

func (*SyncContext) QueryParam

func (sc *SyncContext) QueryParam(name string) string

QueryParam gets query param with request lock

func (*SyncContext) QueryParams

func (sc *SyncContext) QueryParams() url.Values

QueryParams gets query params with request lock

func (*SyncContext) RealIP

func (sc *SyncContext) RealIP() string

RealIP gets real IP with request lock

func (*SyncContext) Redirect

func (sc *SyncContext) Redirect(code int, url string) error

Redirect performs redirect with response lock

func (*SyncContext) Request

func (sc *SyncContext) Request() *http.Request

Request returns the request with read lock

func (*SyncContext) Response

func (sc *SyncContext) Response() *echo.Response

Response returns a thread-safe response wrapper

func (*SyncContext) Set

func (sc *SyncContext) Set(key string, val interface{})

Set sets a value in context with write lock

func (*SyncContext) String

func (sc *SyncContext) String(code int, s string) error

String sends string response with response lock

type TrackerConfig

type TrackerConfig struct {
	Enabled        bool `toml:"enabled"`         // Enable/disable tracker (default: false)
	Workers        int  `toml:"workers"`         // Number of worker goroutines (default: 4)
	BatchSize      int  `toml:"batch_size"`      // Batch size for database inserts (default: 100)
	FlushInterval  int  `toml:"flush_interval"`  // Flush interval in milliseconds (default: 250)
	ChannelBuffer  int  `toml:"channel_buffer"`  // Channel buffer size (default: 100000)
	VerboseLogging bool `toml:"verbose_logging"` // Enable verbose logging (default: false)
	StatsInterval  int  `toml:"stats_interval"`  // Stats reporting interval in seconds (default: 300)
}

TrackerConfig configures the performance tracking system. It allows fine-tuning of the tracker's behavior to minimize performance impact.

type TrackerEntry

type TrackerEntry struct {
	LogId, BoxId, BoxName, BoxType        string
	Username, IP, RealIP, URL             string
	ConnectionNext                        string
	Diff                                  time.Duration
	OrderBox                              int
	JSONPayload                           []byte
	UserAgent, QueryParam, Hostname, Host string
}

type TrackerStats

type TrackerStats struct {
	Processed   int64
	Errors      int64
	Dropped     int64
	BatchCount  int64
	LastProcess time.Time
}

func GetTrackerStats

func GetTrackerStats() TrackerStats

type TwilioConfig

type TwilioConfig struct {
	Enable          bool   `toml:"enable"`
	AccountSid      string `toml:"account_sid"`
	AuthToken       string `toml:"auth_token"`
	VerifyServiceID string `toml:"verify_service_id"`
}

type URLConfig

type URLConfig struct {
	URLBase string `toml:"url_base"`
}

type VMFactory

type VMFactory func() (*goja.Runtime, error)

VMFactory creates new VM instances with proper initialization

type VMInstance

type VMInstance struct {
	VM       *goja.Runtime
	ID       string
	InUse    bool
	LastUsed time.Time
	UseCount int64
	// contains filtered or unexported fields
}

VMInstance represents a VM with metadata

type VMManager

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

VMManager manages a pool of Goja VMs with proper synchronization

func GetVMManager

func GetVMManager() *VMManager

GetVMManager returns the singleton VM manager

func NewVMManager

func NewVMManager(maxSize int) *VMManager

NewVMManager creates a new VM manager with specified pool size

func NewVMManagerWithConfig

func NewVMManagerWithConfig(maxSize int, config *VMPoolConfig) *VMManager

NewVMManagerWithConfig creates a new VM manager with configuration

func (*VMManager) AcquireVM

func (m *VMManager) AcquireVM(c echo.Context) (*VMInstance, error)

AcquireVM gets a VM from the pool or creates a new one

func (*VMManager) Cleanup

func (m *VMManager) Cleanup()

Cleanup performs periodic cleanup of idle VMs

func (*VMManager) GetStats

func (m *VMManager) GetStats() *VMStats

GetStats returns current pool statistics as a pointer to avoid copying the mutex

func (*VMManager) ReleaseVM

func (m *VMManager) ReleaseVM(instance *VMInstance)

ReleaseVM returns a VM to the pool

func (*VMManager) WithVM

func (m *VMManager) WithVM(c echo.Context, fn func(*goja.Runtime) error) error

WithVM executes a function with a VM from the pool

type VMPoolConfig

type VMPoolConfig struct {
	MaxSize         int  `toml:"max_size"`         // Maximum number of VMs in pool (default: 50)
	PreloadSize     int  `toml:"preload_size"`     // Number of VMs to preload (default: max_size/2)
	IdleTimeout     int  `toml:"idle_timeout"`     // Minutes before idle VM is removed (default: 10)
	CleanupInterval int  `toml:"cleanup_interval"` // Minutes between cleanup runs (default: 5)
	EnableMetrics   bool `toml:"enable_metrics"`   // Enable VM pool metrics logging

	// Resource limits
	MaxMemoryMB         int   `toml:"max_memory_mb"`         // Max memory per VM in MB (default: 128)
	MaxExecutionSeconds int   `toml:"max_execution_seconds"` // Max execution time in seconds (default: 30)
	MaxOperations       int64 `toml:"max_operations"`        // Max JS operations (default: 10M)

	// Sandbox settings
	EnableFileSystem bool `toml:"enable_filesystem"` // Allow filesystem access (default: false)
	EnableNetwork    bool `toml:"enable_network"`    // Allow network access (default: false)
	EnableProcess    bool `toml:"enable_process"`    // Allow process access (default: false)
}

VMPoolConfig configures the JavaScript VM pool for workflow execution. It includes settings for pool size, resource limits, and security sandboxing.

type VMResourceLimits

type VMResourceLimits struct {
	MaxMemoryBytes   int64         // Maximum memory in bytes (0 = no limit)
	MaxExecutionTime time.Duration // Maximum execution time (0 = no limit)
	MaxOperations    int64         // Maximum JS operations (0 = no limit)
	MaxStackDepth    int           // Maximum stack depth (0 = no limit)
	CheckInterval    int64         // How many operations between limit checks
}

VMResourceLimits defines resource limits for a VM

func DefaultVMResourceLimits

func DefaultVMResourceLimits() VMResourceLimits

DefaultVMResourceLimits returns safe default limits

func GetLimitsFromConfig

func GetLimitsFromConfig() VMResourceLimits

GetLimitsFromConfig gets limits from configuration

type VMResourceStats

type VMResourceStats struct {
	ElapsedTime    time.Duration
	OperationCount int64
	MemoryUsed     int64
	Interrupted    bool
}

VMResourceStats contains usage statistics

type VMResourceTracker

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

VMResourceTracker tracks resource usage of a VM

func CreateSecureVM

func CreateSecureVM(limits VMResourceLimits, sandboxConfig SandboxConfig) (*goja.Runtime, *VMResourceTracker, error)

CreateSecureVM creates a VM with sandbox and limits applied

func NewVMResourceTracker

func NewVMResourceTracker(limits VMResourceLimits) *VMResourceTracker

NewVMResourceTracker creates a new resource tracker

func SetupVMWithLimits

func SetupVMWithLimits(vm *goja.Runtime, limits VMResourceLimits) *VMResourceTracker

SetupVMWithLimits configures a VM with resource limits

func (*VMResourceTracker) CheckLimits

func (t *VMResourceTracker) CheckLimits() bool

CheckLimits checks if limits have been exceeded

func (*VMResourceTracker) GetStats

func (t *VMResourceTracker) GetStats() VMResourceStats

GetStats returns current statistics

func (*VMResourceTracker) Stop

func (t *VMResourceTracker) Stop()

Stop stops the tracker and releases resources

type VMSandbox

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

VMSandbox manages the sandbox for a VM

func NewVMSandbox

func NewVMSandbox(vm *goja.Runtime, config SandboxConfig) *VMSandbox

NewVMSandbox creates a new sandbox

func (*VMSandbox) Apply

func (s *VMSandbox) Apply() error

Apply applies sandbox restrictions to the VM

type VMStats

type VMStats struct {
	Created   int64
	InUse     int64
	Available int64
	TotalUses int64
	Errors    int64
	// contains filtered or unexported fields
}

VMStats tracks usage statistics

type WorkflowError

type WorkflowError struct {
	Message string
}

WorkflowError para errores específicos de workflow

func NewWorkflowError

func NewWorkflowError(message string) *WorkflowError

func (*WorkflowError) Error

func (we *WorkflowError) Error() string

Jump to

Keyboard shortcuts

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