module

package
v0.0.0-...-dac86b4 Latest Latest
Warning

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

Go to latest
Published: Feb 16, 2026 License: MIT Imports: 67 Imported by: 0

Documentation

Overview

Package module defines core interfaces for the workflow engine

Index

Constants

View Source
const (
	LifecycleStarted   = "started"
	LifecycleCompleted = "completed"
	LifecycleFailed    = "failed"
)

Lifecycle constants for workflow and step events.

View Source
const EventBusBridgeName = "messaging.broker.eventbus"

EventBusBridgeName is the default service name for the EventBus bridge adapter.

View Source
const (
	// EventBusTriggerName is the standard name for the EventBus trigger.
	EventBusTriggerName = "trigger.eventbus"
)
View Source
const (
	// EventTriggerName is the standard name for event triggers
	EventTriggerName = "trigger.event"
)
View Source
const (
	// HTTPTriggerName is the standard name for HTTP triggers
	HTTPTriggerName = "trigger.http"
)
View Source
const (
	InMemoryMessageBrokerName = "messaging.broker.memory"
)

Standard module name constants

View Source
const (
	// ScheduleTriggerName is the standard name for schedule triggers
	ScheduleTriggerName = "trigger.schedule"
)
View Source
const (
	SimpleMessageHandlerName = "messaging.handler"
)

Standard module name constants

View Source
const (
	StateMachineEngineName = "statemachine.engine"
)

Standard module name constants

View Source
const StateMachineStateConnectorName = "workflow.connector.statemachine"

StateMachineStateConnectorName is the standard service name

View Source
const StateTrackerName = "workflow.service.statetracker"

StateTrackerName is the standard name for the state tracker service

Variables

This section is empty.

Functions

func BuildDeleteSQL

func BuildDeleteSQL(table string, where string, whereArgs ...any) (string, []any, error)

BuildDeleteSQL builds a DELETE SQL string (exported for testing). Returns an error if the table name contains unsafe characters.

func BuildInsertSQL

func BuildInsertSQL(table string, data map[string]any) (string, []any, error)

BuildInsertSQL builds an INSERT SQL string and returns it with values (exported for testing). Returns an error if table or column names contain unsafe characters.

func BuildUpdateSQL

func BuildUpdateSQL(table string, data map[string]any, where string, whereArgs ...any) (string, []any, error)

BuildUpdateSQL builds an UPDATE SQL string and returns it with values (exported for testing). Returns an error if table or column names contain unsafe characters.

func CalculateBackoff

func CalculateBackoff(initialBackoff time.Duration, multiplier float64, maxBackoff time.Duration, attempt int) time.Duration

CalculateBackoff is exported for testing

func CreateIsolatedApp

func CreateIsolatedApp(t *testing.T) modular.Application

CreateIsolatedApp creates an isolated application for tests

func DefaultSummaryFields

func DefaultSummaryFields() []string

DefaultSummaryFields returns the default list of fields to include in summary responses.

func DefaultTransitionMap

func DefaultTransitionMap() map[string]string

DefaultTransitionMap returns the default sub-action to state machine transition mapping.

func ExtractUIAssets

func ExtractUIAssets(destDir string) error

ExtractUIAssets extracts the embedded UI assets to destDir, preserving directory structure. This is used by the admin package to provide a filesystem path for static.fileserver to serve from.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID extracts the request ID from the context.

func RegisterAdminSchemas

func RegisterAdminSchemas(gen *OpenAPIGenerator)

RegisterAdminSchemas registers all admin API request/response schemas on the given OpenAPI generator. Call after BuildSpec and before ApplySchemas.

func SkipTestWithContext

func SkipTestWithContext(ctx context.Context, skip bool) context.Context

Skip tests with a context.Context parameter

func StepTopic

func StepTopic(workflowType, stepName, lifecycle string) string

StepTopic returns the event bus topic for a step lifecycle event. Format: "workflow.<workflowType>.step.<stepName>.<lifecycle>"

func WorkflowTopic

func WorkflowTopic(workflowType, lifecycle string) string

WorkflowTopic returns the event bus topic for a workflow lifecycle event. Format: "workflow.<workflowType>.<lifecycle>"

Types

type ArtifactOutput

type ArtifactOutput struct {
	Key  string `yaml:"key"`
	Path string `yaml:"path"`
}

ArtifactOutput defines an artifact to collect after shell execution.

type ArtifactPullStep

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

ArtifactPullStep retrieves an artifact from a configured source (previous execution, URL, or S3) and writes it to a destination path.

func (*ArtifactPullStep) Execute

Execute pulls the artifact from the configured source and writes it to dest.

func (*ArtifactPullStep) Name

func (s *ArtifactPullStep) Name() string

Name returns the step name.

type ArtifactPushStep

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

ArtifactPushStep reads a file from sourcePath and stores it in the artifact store.

func (*ArtifactPushStep) Execute

Execute reads the source file and stores it as an artifact.

func (*ArtifactPushStep) Name

func (s *ArtifactPushStep) Name() string

Name returns the step name.

type AuthMiddleware

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

AuthMiddleware implements an HTTP authorization middleware

func NewAuthMiddleware

func NewAuthMiddleware(name string, authType string) *AuthMiddleware

NewAuthMiddleware creates a new authentication middleware

func (*AuthMiddleware) AddProvider

func (m *AuthMiddleware) AddProvider(validTokens map[string]map[string]any)

AddProvider creates and registers a simple token-based auth provider

func (*AuthMiddleware) Init

func (m *AuthMiddleware) Init(app modular.Application) error

Init initializes the middleware with the application context

func (*AuthMiddleware) Name

func (m *AuthMiddleware) Name() string

Name returns the module name

func (*AuthMiddleware) Process

func (m *AuthMiddleware) Process(next http.Handler) http.Handler

Process implements the HTTPMiddleware interface

func (*AuthMiddleware) ProvidesServices

func (m *AuthMiddleware) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module

func (*AuthMiddleware) RegisterProvider

func (m *AuthMiddleware) RegisterProvider(provider AuthProvider)

RegisterProvider adds an authentication provider

func (*AuthMiddleware) RequiresServices

func (m *AuthMiddleware) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module

func (*AuthMiddleware) Start

func (m *AuthMiddleware) Start(ctx context.Context) error

Start is a no-op for this middleware

func (*AuthMiddleware) Stop

func (m *AuthMiddleware) Stop(ctx context.Context) error

Stop is a no-op for this middleware

type AuthProvider

type AuthProvider interface {
	Authenticate(token string) (bool, map[string]any, error)
}

AuthProvider defines methods for authentication providers

type CORSMiddleware

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

CORSMiddleware provides CORS support

func NewCORSMiddleware

func NewCORSMiddleware(name string, allowedOrigins, allowedMethods []string) *CORSMiddleware

NewCORSMiddleware creates a new CORS middleware

func (*CORSMiddleware) Init

func (m *CORSMiddleware) Init(app modular.Application) error

Init initializes the middleware

func (*CORSMiddleware) Name

func (m *CORSMiddleware) Name() string

Name returns the module name

func (*CORSMiddleware) Process

func (m *CORSMiddleware) Process(next http.Handler) http.Handler

Process implements middleware processing

func (*CORSMiddleware) ProvidesServices

func (m *CORSMiddleware) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this middleware

func (*CORSMiddleware) RequiresServices

func (m *CORSMiddleware) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this middleware

func (*CORSMiddleware) Start

func (m *CORSMiddleware) Start(ctx context.Context) error

Start is a no-op for this middleware

func (*CORSMiddleware) Stop

func (m *CORSMiddleware) Stop(ctx context.Context) error

Stop is a no-op for this middleware

type CommandFunc

type CommandFunc func(ctx context.Context, r *http.Request) (any, error)

CommandFunc is a state-changing command function that returns a result or an error.

type CommandHandler

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

CommandHandler dispatches POST/PUT/DELETE requests to named command functions. Each command is registered by name and dispatched by extracting the last path segment from the request URL. Route pipelines can be attached for composable per-route processing. A delegate service can be configured to handle requests that don't match any registered command name.

func NewCommandHandler

func NewCommandHandler(name string) *CommandHandler

NewCommandHandler creates a new CommandHandler with the given name.

func (*CommandHandler) Handle

func (h *CommandHandler) Handle(w http.ResponseWriter, r *http.Request)

Handle dispatches an HTTP request to the appropriate command function.

func (*CommandHandler) Init

func (h *CommandHandler) Init(app modular.Application) error

Init initializes the command handler and resolves the delegate service.

func (*CommandHandler) Name

func (h *CommandHandler) Name() string

Name returns the unique identifier for this module.

func (*CommandHandler) ProvidesServices

func (h *CommandHandler) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns a list of services provided by this module.

func (*CommandHandler) RegisterCommand

func (h *CommandHandler) RegisterCommand(name string, fn CommandFunc)

RegisterCommand adds a named command function to the handler.

func (*CommandHandler) RequiresServices

func (h *CommandHandler) RequiresServices() []modular.ServiceDependency

RequiresServices returns a list of services required by this module.

func (*CommandHandler) ResolveDelegatePostStart

func (h *CommandHandler) ResolveDelegatePostStart()

ResolveDelegatePostStart is called after engine.Start to resolve delegates that may not have been available during Init (e.g., services registered by post-start hooks).

func (*CommandHandler) ServeHTTP

func (h *CommandHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface. It looks up a route pipeline by the full "METHOD /path" pattern (set by Go 1.22+ ServeMux), falling back to the last path segment for backward compatibility with registered commands. Dispatch chain: RegisteredCommandFunc -> RoutePipeline -> DelegateHandler -> 404

func (*CommandHandler) SetDelegate

func (h *CommandHandler) SetDelegate(name string)

SetDelegate sets the delegate service name. The service must implement http.Handler and will be resolved from the service registry during Init.

func (*CommandHandler) SetDelegateHandler

func (h *CommandHandler) SetDelegateHandler(handler http.Handler)

SetDelegateHandler directly sets the HTTP handler used for delegation.

func (*CommandHandler) SetExecutionTracker

func (h *CommandHandler) SetExecutionTracker(t *ExecutionTracker)

SetExecutionTracker sets the execution tracker for recording pipeline executions.

func (*CommandHandler) SetRoutePipeline

func (h *CommandHandler) SetRoutePipeline(routePath string, pipeline *Pipeline)

SetRoutePipeline attaches a pipeline to a specific route path.

type CompositeTransitionHandler

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

CompositeTransitionHandler combines multiple transition handlers

func NewCompositeTransitionHandler

func NewCompositeTransitionHandler() *CompositeTransitionHandler

NewCompositeTransitionHandler creates a new composite handler

func (*CompositeTransitionHandler) AddHandler

func (c *CompositeTransitionHandler) AddHandler(handler TransitionHandler)

AddHandler adds a handler to the composite

func (*CompositeTransitionHandler) HandleTransition

func (c *CompositeTransitionHandler) HandleTransition(ctx context.Context, event TransitionEvent) error

HandleTransition calls all handlers in sequence

type ConditionalStep

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

ConditionalStep routes pipeline execution to different steps based on a field value in pc.Current.

func (*ConditionalStep) Execute

Execute resolves the field value and determines the next step.

func (*ConditionalStep) Name

func (s *ConditionalStep) Name() string

Name returns the step name.

type CronScheduler

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

CronScheduler implements a cron-based scheduler

func NewCronScheduler

func NewCronScheduler(name string, cronExpression string) *CronScheduler

NewCronScheduler creates a new cron scheduler

func (*CronScheduler) Init

func (s *CronScheduler) Init(app modular.Application) error

Init initializes the scheduler

func (*CronScheduler) Name

func (s *CronScheduler) Name() string

Name returns the module name

func (*CronScheduler) Schedule

func (s *CronScheduler) Schedule(job Job) error

Schedule adds a job to the scheduler

func (*CronScheduler) Start

func (s *CronScheduler) Start(ctx context.Context) error

Start starts the scheduler

func (*CronScheduler) Stop

func (s *CronScheduler) Stop(ctx context.Context) error

Stop stops the scheduler

type CrossWorkflowRouter

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

CrossWorkflowRouter routes events from one workflow to linked target workflows.

func NewCrossWorkflowRouter

func NewCrossWorkflowRouter(linkStore store.CrossWorkflowLinkStore, getEngine func(uuid.UUID) (any, bool), logger *slog.Logger) *CrossWorkflowRouter

NewCrossWorkflowRouter creates a new router. The getEngine callback must return a value whose concrete type has a field or method that provides a TriggerWorkflower. In practice this is *workflow.ManagedEngine.

func (r *CrossWorkflowRouter) RefreshLinks(ctx context.Context) error

RefreshLinks reloads link configurations from the database.

func (*CrossWorkflowRouter) RouteEvent

func (r *CrossWorkflowRouter) RouteEvent(ctx context.Context, sourceWorkflowID uuid.UUID, eventType string, eventData any) error

RouteEvent checks if an event from a source workflow should be forwarded to any target workflows based on configured links.

type DBExecStep

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

DBExecStep executes parameterized SQL INSERT/UPDATE/DELETE against a named database service.

func (*DBExecStep) Execute

func (s *DBExecStep) Execute(_ context.Context, pc *PipelineContext) (*StepResult, error)

func (*DBExecStep) Name

func (s *DBExecStep) Name() string

type DBProvider

type DBProvider interface {
	DB() *sql.DB
}

DBProvider is implemented by modules that provide a *sql.DB connection. Both SQLiteStorage and WorkflowDatabase satisfy this interface.

type DBQueryStep

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

DBQueryStep executes a parameterized SQL SELECT against a named database service.

func (*DBQueryStep) Execute

func (s *DBQueryStep) Execute(_ context.Context, pc *PipelineContext) (*StepResult, error)

func (*DBQueryStep) Name

func (s *DBQueryStep) Name() string

type DataTransformer

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

DataTransformer provides named data transformation pipelines

func NewDataTransformer

func NewDataTransformer(name string) *DataTransformer

NewDataTransformer creates a new DataTransformer module

func (*DataTransformer) Init

func (dt *DataTransformer) Init(app modular.Application) error

Init registers the data transformer as a service

func (*DataTransformer) Name

func (dt *DataTransformer) Name() string

Name returns the module name

func (*DataTransformer) RegisterPipeline

func (dt *DataTransformer) RegisterPipeline(pipeline *TransformPipeline)

RegisterPipeline registers a named transformation pipeline

func (*DataTransformer) Transform

func (dt *DataTransformer) Transform(ctx context.Context, pipelineName string, data any) (any, error)

Transform runs a named pipeline on the given data

func (*DataTransformer) TransformWithOps

func (dt *DataTransformer) TransformWithOps(ctx context.Context, ops []TransformOperation, data any) (any, error)

TransformWithOps runs a sequence of operations on the given data

type DatabaseConfig

type DatabaseConfig struct {
	Driver          string        `json:"driver" yaml:"driver"`
	DSN             string        `json:"dsn" yaml:"dsn"`
	MaxOpenConns    int           `json:"maxOpenConns" yaml:"maxOpenConns"`
	MaxIdleConns    int           `json:"maxIdleConns" yaml:"maxIdleConns"`
	ConnMaxLifetime time.Duration `json:"connMaxLifetime" yaml:"connMaxLifetime"`
	MigrationsDir   string        `json:"migrationsDir" yaml:"migrationsDir"`
}

DatabaseConfig holds configuration for the workflow database module

type DatabaseIntegrationConnector

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

DatabaseIntegrationConnector implements IntegrationConnector for database operations

func NewDatabaseIntegrationConnector

func NewDatabaseIntegrationConnector(name string, db *WorkflowDatabase) *DatabaseIntegrationConnector

NewDatabaseIntegrationConnector creates a new database integration connector

func (*DatabaseIntegrationConnector) Connect

Connect opens the database connection

func (*DatabaseIntegrationConnector) Disconnect

Disconnect closes the database connection

func (*DatabaseIntegrationConnector) Execute

func (c *DatabaseIntegrationConnector) Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error)

Execute dispatches to the appropriate WorkflowDatabase method based on action

func (*DatabaseIntegrationConnector) GetName

func (c *DatabaseIntegrationConnector) GetName() string

GetName returns the connector name

func (*DatabaseIntegrationConnector) IsConnected

func (c *DatabaseIntegrationConnector) IsConnected() bool

IsConnected returns whether the connector is connected

type DelegateStep

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

DelegateStep forwards the HTTP request to a named service implementing http.Handler. This is a "passthrough" pipeline step: the delegate service handles the full HTTP response (status, headers, body). Because the delegate writes to the ResponseWriter directly, this step sets _response_handled in pipeline metadata and returns Stop: true.

func (*DelegateStep) Execute

Execute forwards the request to the delegate service. It reads _http_request and _http_response_writer from the pipeline context metadata. If these are present (live HTTP context), the delegate writes directly to the response writer. If not present (e.g., test context), it uses httptest.ResponseRecorder and returns the captured response as output.

func (*DelegateStep) Name

func (s *DelegateStep) Name() string

Name returns the step name.

type DeployStep

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

DeployStep executes a deployment through the deploy.Executor, bridging pipeline execution to cloud providers via deployment strategies.

func (*DeployStep) Execute

func (s *DeployStep) Execute(ctx context.Context, pc *PipelineContext) (*StepResult, error)

Execute builds a deploy request and delegates to the deploy.Executor.

func (*DeployStep) Name

func (s *DeployStep) Name() string

Name returns the step name.

type DockerBuildStep

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

DockerBuildStep builds a Docker image from a context directory and Dockerfile.

func (*DockerBuildStep) Execute

Execute builds a Docker image using the Docker SDK.

func (*DockerBuildStep) Name

func (s *DockerBuildStep) Name() string

Name returns the step name.

type DockerPushStep

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

DockerPushStep pushes a Docker image to a remote registry.

func (*DockerPushStep) Execute

Execute pushes the image to the configured registry.

func (*DockerPushStep) Name

func (s *DockerPushStep) Name() string

Name returns the step name.

type DockerRunStep

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

DockerRunStep runs a command inside a Docker container using the sandbox.

func (*DockerRunStep) Execute

func (s *DockerRunStep) Execute(ctx context.Context, _ *PipelineContext) (*StepResult, error)

Execute runs the container and returns exit code, stdout, and stderr.

func (*DockerRunStep) Name

func (s *DockerRunStep) Name() string

Name returns the step name.

type ErrorStrategy

type ErrorStrategy string

ErrorStrategy defines how a pipeline handles step errors.

const (
	ErrorStrategyStop       ErrorStrategy = "stop"
	ErrorStrategySkip       ErrorStrategy = "skip"
	ErrorStrategyCompensate ErrorStrategy = "compensate"
)

type EventBusBridge

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

EventBusBridge adapts the modular framework's EventBusModule to the workflow engine's MessageBroker interface. It allows the workflow engine to publish and subscribe to events through the EventBus using the existing MessageBroker API.

func NewEventBusBridge

func NewEventBusBridge(name string) *EventBusBridge

NewEventBusBridge creates a new EventBusBridge with the given name.

func (*EventBusBridge) Consumer

func (b *EventBusBridge) Consumer() MessageConsumer

Consumer returns the bridge itself, which implements MessageConsumer.

func (*EventBusBridge) Init

func (b *EventBusBridge) Init(app modular.Application) error

Init registers the bridge as a service in the application's service registry. It does not look up the EventBus here; that is done via SetEventBus or InitFromApp after the application has been fully initialized.

func (*EventBusBridge) InitFromApp

func (b *EventBusBridge) InitFromApp(app modular.Application) error

InitFromApp looks up the EventBusModule from the application's service registry using the well-known service name "eventbus.provider".

func (*EventBusBridge) Name

func (b *EventBusBridge) Name() string

Name returns the bridge's service name.

func (*EventBusBridge) Producer

func (b *EventBusBridge) Producer() MessageProducer

Producer returns the bridge itself, which implements MessageProducer.

func (*EventBusBridge) SendMessage

func (b *EventBusBridge) SendMessage(topic string, message []byte) error

SendMessage publishes a message to the EventBus. The message bytes are unmarshalled from JSON into an interface{} payload. If unmarshalling fails, the raw bytes are published as the payload. Returns nil (no-op) if no EventBus has been set.

func (*EventBusBridge) SetEventBus

func (b *EventBusBridge) SetEventBus(eb *eventbus.EventBusModule)

SetEventBus injects the EventBusModule directly. This is useful when the engine already has a reference to the EventBus after app.Init().

func (*EventBusBridge) Start

func (b *EventBusBridge) Start(_ context.Context) error

Start is a no-op; the EventBus lifecycle is managed externally.

func (*EventBusBridge) Stop

func (b *EventBusBridge) Stop(_ context.Context) error

Stop cancels all active subscriptions and clears the subscription map.

func (*EventBusBridge) Subscribe

func (b *EventBusBridge) Subscribe(topic string, handler MessageHandler) error

Subscribe registers a MessageHandler to receive events from the EventBus on the given topic. Events are marshalled to JSON before being passed to the handler. Returns nil (no-op) if no EventBus has been set.

func (*EventBusBridge) Unsubscribe

func (b *EventBusBridge) Unsubscribe(topic string) error

Unsubscribe cancels the subscription for the given topic and removes it.

type EventBusTrigger

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

EventBusTrigger implements the Trigger interface and starts workflows in response to events published on the EventBus.

func NewEventBusTrigger

func NewEventBusTrigger() *EventBusTrigger

NewEventBusTrigger creates a new EventBus trigger with default namespace.

func NewEventBusTriggerWithNamespace

func NewEventBusTriggerWithNamespace(namespace ModuleNamespaceProvider) *EventBusTrigger

NewEventBusTriggerWithNamespace creates a new EventBus trigger with namespace support.

func (*EventBusTrigger) Configure

func (t *EventBusTrigger) Configure(app modular.Application, triggerConfig any) error

Configure parses the trigger config and resolves the EventBus and engine services from the application.

func (*EventBusTrigger) Init

Init registers the trigger as a service.

func (*EventBusTrigger) Name

func (t *EventBusTrigger) Name() string

Name returns the trigger name.

func (*EventBusTrigger) SetEventBusAndEngine

func (t *EventBusTrigger) SetEventBusAndEngine(eb *eventbus.EventBusModule, engine WorkflowEngine)

SetEventBusAndEngine allows directly setting the EventBus and engine for testing.

func (*EventBusTrigger) Start

func (t *EventBusTrigger) Start(ctx context.Context) error

Start subscribes to the configured EventBus topics.

func (*EventBusTrigger) Stop

func (t *EventBusTrigger) Stop(_ context.Context) error

Stop cancels all active EventBus subscriptions.

type EventBusTriggerSubscription

type EventBusTriggerSubscription struct {
	Topic    string         `json:"topic" yaml:"topic"`
	Event    string         `json:"event,omitempty" yaml:"event,omitempty"`
	Workflow string         `json:"workflow" yaml:"workflow"`
	Action   string         `json:"action" yaml:"action"`
	Async    bool           `json:"async,omitempty" yaml:"async,omitempty"`
	Params   map[string]any `json:"params,omitempty" yaml:"params,omitempty"`
}

EventBusTriggerSubscription defines a single subscription that the trigger listens to on the EventBus and maps to a workflow execution.

type EventData

type EventData struct {
	EventType  string         `json:"eventType"`
	Timestamp  time.Time      `json:"timestamp"`
	SourceID   string         `json:"sourceId"`
	CorrelID   string         `json:"correlId,omitempty"`
	Data       map[string]any `json:"data,omitempty"`
	RawMessage []byte         `json:"-"`
}

EventData represents an event in the system

type EventHandler

type EventHandler interface {
	HandlePattern(ctx context.Context, match PatternMatch) error
}

EventHandler processes matched event patterns

type EventPattern

type EventPattern struct {
	PatternID    string         `json:"patternId" yaml:"patternId"`
	EventTypes   []string       `json:"eventTypes" yaml:"eventTypes"`
	WindowTime   time.Duration  `json:"windowTime" yaml:"windowTime"`
	Condition    string         `json:"condition" yaml:"condition"`
	MinOccurs    int            `json:"minOccurs" yaml:"minOccurs"`
	MaxOccurs    int            `json:"maxOccurs" yaml:"maxOccurs"`
	OrderMatters bool           `json:"orderMatters" yaml:"orderMatters"`
	ExtraParams  map[string]any `json:"extraParams,omitempty" yaml:"extraParams,omitempty"`
}

EventPattern defines a pattern for matching complex event sequences

type EventProcessor

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

EventProcessor processes complex event patterns

func GetProcessor

func GetProcessor(app modular.Application) (*EventProcessor, error)

GetProcessor is a utility to get an event processor from the app

func NewEventProcessor

func NewEventProcessor(name string) *EventProcessor

NewEventProcessor creates a new complex event processor

func (*EventProcessor) AddPattern

func (p *EventProcessor) AddPattern(pattern *EventPattern)

AddPattern adds a new event pattern to monitor

func (*EventProcessor) Error

func (p *EventProcessor) Error() string

Error returns the last error from the processor - implements the error interface

func (*EventProcessor) GetService

func (p *EventProcessor) GetService(name string, out any) error

GetService implements the service functionality expected by handlers. It follows the modular.Application interface signature

func (*EventProcessor) Init

func (p *EventProcessor) Init(app modular.Application) error

Init initializes the event processor

func (*EventProcessor) Name

func (p *EventProcessor) Name() string

Name returns the module name

func (*EventProcessor) ProcessEvent

func (p *EventProcessor) ProcessEvent(ctx context.Context, event EventData) error

ProcessEvent processes a new event and checks for pattern matches

func (*EventProcessor) ProvidesServices

func (p *EventProcessor) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns services provided by this processor

func (*EventProcessor) RegisterHandler

func (p *EventProcessor) RegisterHandler(patternID string, handler EventHandler) error

RegisterHandler registers a handler for a specific pattern

func (*EventProcessor) RequiresServices

func (p *EventProcessor) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this processor

func (*EventProcessor) Service

func (p *EventProcessor) Service(name string) any

Service provides access to a named service

func (*EventProcessor) Services

func (p *EventProcessor) Services() map[string]any

Services returns a map of all available services

func (*EventProcessor) SetError

func (p *EventProcessor) SetError(err error)

SetError sets the processor error

func (*EventProcessor) Start

func (p *EventProcessor) Start(ctx context.Context) error

Start starts the event processor

func (*EventProcessor) Stop

func (p *EventProcessor) Stop(ctx context.Context) error

Stop stops the event processor

type EventProcessorLocator

type EventProcessorLocator struct {
	App modular.Application
}

EventProcessorLocator helps locate the event processor

func NewEventProcessorLocator

func NewEventProcessorLocator(app modular.Application) *EventProcessorLocator

NewEventProcessorLocator creates a new locator

func (*EventProcessorLocator) Locate

func (l *EventProcessorLocator) Locate(name string) (*EventProcessor, error)

Locate finds an event processor by name

func (*EventProcessorLocator) LocateDefault

func (l *EventProcessorLocator) LocateDefault() (*EventProcessor, error)

LocateDefault finds the default event processor

type EventRecorder

type EventRecorder interface {
	RecordEvent(ctx context.Context, executionID string, eventType string, data map[string]any) error
}

EventRecorder is an optional interface for recording execution events. When set on Pipeline, execution events are appended for observability. The store.EventStore can satisfy this via an adapter at the wiring layer.

type EventTrigger

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

EventTrigger implements a trigger that starts workflows from messaging events

func NewEventTrigger

func NewEventTrigger() *EventTrigger

NewEventTrigger creates a new event trigger

func NewEventTriggerWithNamespace

func NewEventTriggerWithNamespace(namespace ModuleNamespaceProvider) *EventTrigger

NewEventTriggerWithNamespace creates a new event trigger with namespace support

func (*EventTrigger) Configure

func (t *EventTrigger) Configure(app modular.Application, triggerConfig any) error

Configure sets up the trigger from configuration

func (*EventTrigger) Init

func (t *EventTrigger) Init(app modular.Application) error

Init initializes the trigger

func (*EventTrigger) Name

func (t *EventTrigger) Name() string

Name returns the name of this trigger

func (*EventTrigger) SetBrokerAndEngine

func (t *EventTrigger) SetBrokerAndEngine(broker MessageBroker, engine WorkflowEngine)

SetBrokerAndEngine allows directly setting the broker and engine for testing

func (*EventTrigger) Start

func (t *EventTrigger) Start(ctx context.Context) error

Start starts the trigger

func (*EventTrigger) Stop

func (t *EventTrigger) Stop(ctx context.Context) error

Stop stops the trigger

type EventTriggerConfig

type EventTriggerConfig struct {
	Subscriptions []EventTriggerSubscription `json:"subscriptions" yaml:"subscriptions"`
}

EventTriggerConfig represents the configuration for an event trigger

type EventTriggerSubscription

type EventTriggerSubscription struct {
	Topic    string         `json:"topic" yaml:"topic"`
	Event    string         `json:"event" yaml:"event"`
	Workflow string         `json:"workflow" yaml:"workflow"`
	Action   string         `json:"action" yaml:"action"`
	Params   map[string]any `json:"params,omitempty" yaml:"params,omitempty"`
}

EventTriggerSubscription represents a subscription to a message topic

type ExecutionTracker

type ExecutionTracker struct {
	Store      *V1Store
	WorkflowID string
}

ExecutionTracker wraps pipeline execution with V1Store recording.

func (*ExecutionTracker) TrackPipelineExecution

func (t *ExecutionTracker) TrackPipelineExecution(
	ctx context.Context,
	pipeline *Pipeline,
	triggerData map[string]any,
	r *http.Request,
) (*PipelineContext, error)

TrackPipelineExecution wraps a pipeline execution call, recording the execution and its steps in the V1Store. It returns the PipelineContext and any error from the underlying pipeline execution.

type Executor

type Executor interface {
	Execute(ctx context.Context, params map[string]any) (map[string]any, error)
}

Executor is the interface that dynamic components satisfy.

type ExternalOperation

type ExternalOperation struct {
	Method      string   `json:"method"`
	Path        string   `json:"path"`
	OperationID string   `json:"operationId"`
	Summary     string   `json:"summary"`
	Tags        []string `json:"tags"`
	HasBody     bool     `json:"hasBody"`
}

ExternalOperation describes a callable operation from an external API spec.

type ExternalStateMachineDefinition

type ExternalStateMachineDefinition struct {
	ID           string                                  `json:"id" yaml:"id"`
	Description  string                                  `json:"description,omitempty" yaml:"description,omitempty"`
	InitialState string                                  `json:"initialState" yaml:"initialState"`
	States       map[string]StateMachineStateConfig      `json:"states" yaml:"states"`
	Transitions  map[string]StateMachineTransitionConfig `json:"transitions" yaml:"transitions"`
}

ExternalStateMachineDefinition is used for registering state machines from configuration

type FieldEncryptor

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

FieldEncryptor provides AES-256-GCM encryption for PII fields in data maps. It encrypts specific fields before storage and decrypts them on retrieval, ensuring data at rest contains no plaintext PII.

func NewFieldEncryptor

func NewFieldEncryptor(keyStr string) *FieldEncryptor

NewFieldEncryptor creates a FieldEncryptor from a key string. If the key is empty, encryption is disabled (passthrough mode).

func NewFieldEncryptorFromEnv

func NewFieldEncryptorFromEnv() *FieldEncryptor

NewFieldEncryptorFromEnv creates a FieldEncryptor using the ENCRYPTION_KEY environment variable. Returns a disabled encryptor if the var is not set.

func (*FieldEncryptor) DecryptJSON

func (e *FieldEncryptor) DecryptJSON(data []byte) ([]byte, error)

DecryptJSON decrypts an entire JSON payload (for Kafka messages). Non-encrypted payloads (no "_encrypted" key) are returned as-is.

func (*FieldEncryptor) DecryptPIIFields

func (e *FieldEncryptor) DecryptPIIFields(data map[string]any) (map[string]any, error)

DecryptPIIFields decrypts known PII fields in a data map. Values without the "enc::" prefix are returned as-is (backward compatible).

func (*FieldEncryptor) DecryptValue

func (e *FieldEncryptor) DecryptValue(encoded string) (string, error)

DecryptValue decrypts a single AES-256-GCM encrypted value. Values without the "enc::" prefix are returned as-is (plaintext passthrough).

func (*FieldEncryptor) Enabled

func (e *FieldEncryptor) Enabled() bool

Enabled returns whether encryption is active.

func (*FieldEncryptor) EncryptJSON

func (e *FieldEncryptor) EncryptJSON(data []byte) ([]byte, error)

EncryptJSON encrypts an entire JSON payload (for Kafka messages). The entire message is encrypted as a single blob.

func (*FieldEncryptor) EncryptPIIFields

func (e *FieldEncryptor) EncryptPIIFields(data map[string]any) (map[string]any, error)

EncryptPIIFields encrypts known PII fields in a data map. It handles nested "messages" arrays where each message may contain PII.

func (*FieldEncryptor) EncryptValue

func (e *FieldEncryptor) EncryptValue(plaintext string) (string, error)

EncryptValue encrypts a single string value using AES-256-GCM. Returns the encrypted value prefixed with "enc::" for identification.

type FieldMapping

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

FieldMapping provides configurable field name resolution with fallback chains. Each logical field name maps to an ordered list of actual field names to try when reading from a data map. This eliminates hard-coded field references and allows YAML configuration to remap fields without code changes.

func DefaultRESTFieldMapping

func DefaultRESTFieldMapping() *FieldMapping

DefaultRESTFieldMapping returns the default field mapping for REST API handlers. This matches the existing hard-coded behavior for full backwards compatibility.

func FieldMappingFromConfig

func FieldMappingFromConfig(cfg map[string]any) *FieldMapping

FieldMappingFromConfig parses a field mapping from a config map. The config format is: {"logicalName": ["actual1", "actual2"]} or {"logicalName": "actual1"}

func NewFieldMapping

func NewFieldMapping() *FieldMapping

NewFieldMapping creates a FieldMapping with no mappings defined.

func (*FieldMapping) Clone

func (fm *FieldMapping) Clone() *FieldMapping

Clone returns a deep copy of the field mapping.

func (*FieldMapping) Has

func (fm *FieldMapping) Has(logical string) bool

Has returns true if a mapping is defined for the given logical name.

func (*FieldMapping) MarshalJSON

func (fm *FieldMapping) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for FieldMapping.

func (*FieldMapping) Merge

func (fm *FieldMapping) Merge(other *FieldMapping)

Merge copies all mappings from other into fm. Existing mappings are overwritten.

func (*FieldMapping) Primary

func (fm *FieldMapping) Primary(logical string) string

Primary returns the primary (first) field name for a logical field. If no mapping is defined, returns the logical name itself.

func (*FieldMapping) Resolve

func (fm *FieldMapping) Resolve(data map[string]any, logical string) (any, bool)

Resolve looks up a logical field name in data, trying each actual name in order. Returns the value and true if found, or nil and false if no actual name matched.

func (*FieldMapping) ResolveSlice

func (fm *FieldMapping) ResolveSlice(data map[string]any, logical string) []any

ResolveSlice resolves a logical field name to a []interface{} value. Returns nil if not found or not a slice.

func (*FieldMapping) ResolveString

func (fm *FieldMapping) ResolveString(data map[string]any, logical string) string

ResolveString resolves a logical field name to a string value. Returns empty string if not found or not a string.

func (*FieldMapping) Set

func (fm *FieldMapping) Set(logical string, actual ...string)

Set defines the actual field name(s) for a logical field. The first name is the "primary" used for writes; all names are tried in order for reads.

func (*FieldMapping) SetValue

func (fm *FieldMapping) SetValue(data map[string]any, logical string, value any)

SetValue sets a value in data using the primary (first) field name for a logical field.

func (*FieldMapping) String

func (fm *FieldMapping) String() string

String returns a human-readable representation of the field mapping.

func (*FieldMapping) UnmarshalJSON

func (fm *FieldMapping) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for FieldMapping.

type Finding

type Finding struct {
	RuleID   string `json:"rule_id"`
	Severity string `json:"severity"` // "critical", "high", "medium", "low", "info"
	Message  string `json:"message"`
	Location string `json:"location"`
	Line     int    `json:"line,omitempty"`
}

Finding represents a single issue found by a scanner.

type FunctionHandler

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

FunctionHandler is a simple EventHandler that executes a function

func NewFunctionHandler

func NewFunctionHandler(fn func(ctx context.Context, match PatternMatch) error) *FunctionHandler

NewFunctionHandler creates a new function-based event handler

func (*FunctionHandler) HandlePattern

func (h *FunctionHandler) HandlePattern(ctx context.Context, match PatternMatch) error

HandlePattern handles a pattern match by calling the function

type FunctionJob

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

FunctionJob is a Job implementation that executes a function

func NewFunctionJob

func NewFunctionJob(fn func(context.Context) error) *FunctionJob

NewFunctionJob creates a new job from a function

func (*FunctionJob) Execute

func (j *FunctionJob) Execute(ctx context.Context) error

Execute runs the job function

type FunctionMessageHandler

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

FunctionMessageHandler adapts a function to the MessageHandler interface

func NewFunctionMessageHandler

func NewFunctionMessageHandler(fn func(message []byte) error) *FunctionMessageHandler

NewFunctionMessageHandler creates a new message handler from a function

func (*FunctionMessageHandler) HandleMessage

func (h *FunctionMessageHandler) HandleMessage(message []byte) error

HandleMessage implements the MessageHandler interface

type FunctionTransitionHandler

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

FunctionTransitionHandler is a simple TransitionHandler that executes a function

func NewFunctionTransitionHandler

func NewFunctionTransitionHandler(fn func(ctx context.Context, event TransitionEvent) error) *FunctionTransitionHandler

NewFunctionTransitionHandler creates a new function-based transition handler

func (*FunctionTransitionHandler) HandleTransition

func (h *FunctionTransitionHandler) HandleTransition(ctx context.Context, event TransitionEvent) error

HandleTransition handles a state transition by calling the function

type GCSStorage

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

GCSStorage provides object storage operations using Google Cloud Storage. This is a stub implementation that follows the same pattern as S3Storage.

func NewGCSStorage

func NewGCSStorage(name string) *GCSStorage

NewGCSStorage creates a new GCS storage module.

func (*GCSStorage) Delete

func (g *GCSStorage) Delete(_ context.Context, _ string) error

func (*GCSStorage) Get

func (*GCSStorage) Init

func (g *GCSStorage) Init(app modular.Application) error

func (*GCSStorage) List

func (g *GCSStorage) List(_ context.Context, _ string) ([]store.FileInfo, error)

func (*GCSStorage) Name

func (g *GCSStorage) Name() string

func (*GCSStorage) ProvidesServices

func (g *GCSStorage) ProvidesServices() []modular.ServiceProvider

func (*GCSStorage) Put

func (g *GCSStorage) Put(_ context.Context, _ string, _ io.Reader) error

func (*GCSStorage) RequiresServices

func (g *GCSStorage) RequiresServices() []modular.ServiceDependency

func (*GCSStorage) SetBucket

func (g *GCSStorage) SetBucket(bucket string)

SetBucket sets the GCS bucket name.

func (*GCSStorage) SetCredentialsFile

func (g *GCSStorage) SetCredentialsFile(path string)

SetCredentialsFile sets the path to a service account JSON key file.

func (*GCSStorage) SetProject

func (g *GCSStorage) SetProject(project string)

SetProject sets the GCP project ID.

func (*GCSStorage) Start

func (g *GCSStorage) Start(_ context.Context) error

func (*GCSStorage) Stat

func (g *GCSStorage) Stat(_ context.Context, _ string) (store.FileInfo, error)

func (*GCSStorage) Stop

func (g *GCSStorage) Stop(_ context.Context) error

type GateStep

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

GateStep implements an approval gate within a pipeline. It supports manual, automated, and scheduled gate types.

func (*GateStep) Execute

func (s *GateStep) Execute(_ context.Context, pc *PipelineContext) (*StepResult, error)

Execute evaluates the gate based on its type and returns a gate result.

func (*GateStep) Name

func (s *GateStep) Name() string

Name returns the step name.

type HTTPCallStep

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

HTTPCallStep makes an HTTP request as a pipeline step.

func (*HTTPCallStep) Execute

func (s *HTTPCallStep) Execute(ctx context.Context, pc *PipelineContext) (*StepResult, error)

Execute performs the HTTP request and returns the response.

func (*HTTPCallStep) Name

func (s *HTTPCallStep) Name() string

Name returns the step name.

type HTTPHandler

type HTTPHandler interface {
	Handle(w http.ResponseWriter, r *http.Request)
}

HTTPHandler defines the interface for HTTP request handlers

type HTTPHandlerAdapter

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

HTTPHandlerAdapter adapts an http.Handler to the HTTPHandler interface

func NewHTTPHandlerAdapter

func NewHTTPHandlerAdapter(handler http.Handler) *HTTPHandlerAdapter

NewHTTPHandlerAdapter creates a new adapter for an http.Handler

func (*HTTPHandlerAdapter) Handle

Handle implements the HTTPHandler interface

type HTTPIntegrationConnector

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

HTTPIntegrationConnector implements a connector using HTTP requests

func NewHTTPIntegrationConnector

func NewHTTPIntegrationConnector(name, baseURL string) *HTTPIntegrationConnector

NewHTTPIntegrationConnector creates a new HTTP-based integration connector

func (*HTTPIntegrationConnector) Connect

Connect establishes a connection to the external service

func (*HTTPIntegrationConnector) Disconnect

func (c *HTTPIntegrationConnector) Disconnect(ctx context.Context) error

Disconnect closes the connection to the external service

func (*HTTPIntegrationConnector) Execute

func (c *HTTPIntegrationConnector) Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error)

Execute performs an action on the external service

func (*HTTPIntegrationConnector) GetName

func (c *HTTPIntegrationConnector) GetName() string

GetName returns the connector name

func (*HTTPIntegrationConnector) IsConnected

func (c *HTTPIntegrationConnector) IsConnected() bool

IsConnected checks if the connector is connected

func (*HTTPIntegrationConnector) SetAllowPrivateIPs

func (c *HTTPIntegrationConnector) SetAllowPrivateIPs(allow bool)

SetAllowPrivateIPs enables or disables requests to private/internal IP addresses. This should only be used for testing or trusted internal services.

func (*HTTPIntegrationConnector) SetBasicAuth

func (c *HTTPIntegrationConnector) SetBasicAuth(username, password string)

SetBasicAuth sets basic authentication for the connector

func (*HTTPIntegrationConnector) SetBearerAuth

func (c *HTTPIntegrationConnector) SetBearerAuth(token string)

SetBearerAuth sets bearer token authentication for the connector

func (*HTTPIntegrationConnector) SetDefaultHeader

func (c *HTTPIntegrationConnector) SetDefaultHeader(key, value string)

SetDefaultHeader is an alias for SetHeader for backward compatibility

func (*HTTPIntegrationConnector) SetHeader

func (c *HTTPIntegrationConnector) SetHeader(key, value string)

SetHeader sets a custom header for requests

func (*HTTPIntegrationConnector) SetRateLimit

func (c *HTTPIntegrationConnector) SetRateLimit(requestsPerMinute int)

SetRateLimit sets a rate limit for requests

func (*HTTPIntegrationConnector) SetTimeout

func (c *HTTPIntegrationConnector) SetTimeout(timeout time.Duration)

SetTimeout sets the request timeout

type HTTPMiddleware

type HTTPMiddleware interface {
	Process(next http.Handler) http.Handler
}

HTTPMiddleware defines a middleware that can process HTTP requests

type HTTPRouter

type HTTPRouter interface {
	AddRoute(method, path string, handler HTTPHandler)
}

HTTPRouter interface for routing HTTP requests

type HTTPServer

type HTTPServer interface {
	AddRouter(router HTTPRouter)
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

HTTPServer interface for HTTP server modules

type HTTPTrigger

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

HTTPTrigger implements a trigger that starts workflows from HTTP requests

func NewHTTPTrigger

func NewHTTPTrigger() *HTTPTrigger

NewHTTPTrigger creates a new HTTP trigger

func NewHTTPTriggerWithNamespace

func NewHTTPTriggerWithNamespace(namespace ModuleNamespaceProvider) *HTTPTrigger

NewHTTPTriggerWithNamespace creates a new HTTP trigger with namespace support

func (*HTTPTrigger) Configure

func (t *HTTPTrigger) Configure(app modular.Application, triggerConfig any) error

Configure sets up the trigger from configuration

func (*HTTPTrigger) Init

func (t *HTTPTrigger) Init(app modular.Application) error

Init initializes the trigger

func (*HTTPTrigger) Name

func (t *HTTPTrigger) Name() string

Name returns the name of this trigger

func (*HTTPTrigger) Start

func (t *HTTPTrigger) Start(ctx context.Context) error

Start starts the trigger

func (*HTTPTrigger) Stop

func (t *HTTPTrigger) Stop(ctx context.Context) error

Stop stops the trigger

type HTTPTriggerConfig

type HTTPTriggerConfig struct {
	Routes []HTTPTriggerRoute `json:"routes" yaml:"routes"`
}

HTTPTriggerConfig represents the configuration for an HTTP trigger

type HTTPTriggerRoute

type HTTPTriggerRoute struct {
	Path     string         `json:"path" yaml:"path"`
	Method   string         `json:"method" yaml:"method"`
	Workflow string         `json:"workflow" yaml:"workflow"`
	Action   string         `json:"action" yaml:"action"`
	Params   map[string]any `json:"params,omitempty" yaml:"params,omitempty"`
}

HTTPTriggerRoute represents a single HTTP route configuration

type HealthCheck

type HealthCheck func(ctx context.Context) HealthCheckResult

HealthCheck is a function that performs a health check.

type HealthCheckResult

type HealthCheckResult struct {
	Status  string `json:"status"`
	Message string `json:"message,omitempty"`
}

HealthCheckResult represents the result of a health check.

type HealthCheckable

type HealthCheckable interface {
	HealthStatus() HealthCheckResult
}

HealthCheckable is implemented by modules that can report their own health. The health checker auto-discovers services implementing this interface.

type HealthChecker

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

HealthChecker provides /health, /ready, /live HTTP endpoints.

func NewHealthChecker

func NewHealthChecker(name string) *HealthChecker

NewHealthChecker creates a new HealthChecker module.

func (*HealthChecker) AutoDiscover

func (h *HealthChecker) AutoDiscover() bool

AutoDiscover returns whether auto-discovery of HealthCheckable services is enabled.

func (*HealthChecker) DiscoverHealthCheckables

func (h *HealthChecker) DiscoverHealthCheckables()

DiscoverHealthCheckables scans the service registry for services implementing HealthCheckable and auto-registers them as health checks.

func (*HealthChecker) HealthHandler

func (h *HealthChecker) HealthHandler() http.HandlerFunc

HealthHandler returns an HTTP handler that runs all health checks.

func (*HealthChecker) HealthPath

func (h *HealthChecker) HealthPath() string

HealthPath returns the configured health endpoint path.

func (*HealthChecker) Init

func (h *HealthChecker) Init(app modular.Application) error

Init registers the health checker as a service.

func (*HealthChecker) LiveHandler

func (h *HealthChecker) LiveHandler() http.HandlerFunc

LiveHandler returns an HTTP handler for liveness checks. Always returns 200 with {"status":"alive"}.

func (*HealthChecker) LivePath

func (h *HealthChecker) LivePath() string

LivePath returns the configured liveness endpoint path.

func (*HealthChecker) Name

func (h *HealthChecker) Name() string

Name returns the module name.

func (*HealthChecker) ProvidesServices

func (h *HealthChecker) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*HealthChecker) ReadyHandler

func (h *HealthChecker) ReadyHandler() http.HandlerFunc

ReadyHandler returns an HTTP handler that checks readiness. Returns 200 only if started AND all checks pass, else 503.

func (*HealthChecker) ReadyPath

func (h *HealthChecker) ReadyPath() string

ReadyPath returns the configured readiness endpoint path.

func (*HealthChecker) RegisterCheck

func (h *HealthChecker) RegisterCheck(name string, check HealthCheck)

RegisterCheck adds a named health check function.

func (*HealthChecker) RequiresServices

func (h *HealthChecker) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*HealthChecker) SetConfig

func (h *HealthChecker) SetConfig(cfg HealthCheckerConfig)

SetConfig applies configuration to the health checker.

func (*HealthChecker) SetStarted

func (h *HealthChecker) SetStarted(started bool)

SetStarted marks the health checker as started or stopped.

type HealthCheckerConfig

type HealthCheckerConfig struct {
	HealthPath   string        `yaml:"healthPath" json:"healthPath"`
	ReadyPath    string        `yaml:"readyPath" json:"readyPath"`
	LivePath     string        `yaml:"livePath" json:"livePath"`
	CheckTimeout time.Duration `yaml:"checkTimeout" json:"checkTimeout"`
	AutoDiscover bool          `yaml:"autoDiscover" json:"autoDiscover"`
}

HealthCheckerConfig holds configuration for the HealthChecker module.

func DefaultHealthCheckerConfig

func DefaultHealthCheckerConfig() HealthCheckerConfig

DefaultHealthCheckerConfig returns the default configuration.

type HealthHTTPHandler

type HealthHTTPHandler struct {
	Handler http.HandlerFunc
}

HealthHTTPHandler adapts an http.HandlerFunc to the HTTPHandler interface

func (*HealthHTTPHandler) Handle

Handle implements the HTTPHandler interface

type InMemoryMessageBroker

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

InMemoryMessageBroker provides a simple in-memory implementation of MessageBroker

func NewInMemoryMessageBroker

func NewInMemoryMessageBroker(name string) *InMemoryMessageBroker

NewInMemoryMessageBroker creates a new in-memory message broker

func NewInMemoryMessageBrokerWithNamespace

func NewInMemoryMessageBrokerWithNamespace(name string, namespace ModuleNamespaceProvider) *InMemoryMessageBroker

NewInMemoryMessageBrokerWithNamespace creates a new in-memory message broker with namespace support

func NewStandardInMemoryMessageBroker

func NewStandardInMemoryMessageBroker(namespace ModuleNamespaceProvider) *InMemoryMessageBroker

NewStandardInMemoryMessageBroker creates an in-memory message broker with the standard name

func (*InMemoryMessageBroker) Consumer

func (b *InMemoryMessageBroker) Consumer() MessageConsumer

Consumer returns the message consumer interface

func (*InMemoryMessageBroker) DeliveryTimeout

func (b *InMemoryMessageBroker) DeliveryTimeout() time.Duration

DeliveryTimeout returns the configured delivery timeout.

func (*InMemoryMessageBroker) Init

Init initializes the module with the application context

func (*InMemoryMessageBroker) MaxQueueSize

func (b *InMemoryMessageBroker) MaxQueueSize() int

MaxQueueSize returns the configured maximum queue size per topic.

func (*InMemoryMessageBroker) Name

func (b *InMemoryMessageBroker) Name() string

Name returns the unique identifier for this module

func (*InMemoryMessageBroker) Producer

func (b *InMemoryMessageBroker) Producer() MessageProducer

Producer returns the message producer interface

func (*InMemoryMessageBroker) ProvidesServices

func (b *InMemoryMessageBroker) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns a list of services provided by this module

func (*InMemoryMessageBroker) RequiresServices

func (b *InMemoryMessageBroker) RequiresServices() []modular.ServiceDependency

RequiresServices returns a list of services required by this module

func (*InMemoryMessageBroker) SendMessage

func (b *InMemoryMessageBroker) SendMessage(topic string, message []byte) error

SendMessage is a convenience method to send a message to a topic

func (*InMemoryMessageBroker) SetDeliveryTimeout

func (b *InMemoryMessageBroker) SetDeliveryTimeout(d time.Duration)

SetDeliveryTimeout sets the message delivery timeout.

func (*InMemoryMessageBroker) SetMaxQueueSize

func (b *InMemoryMessageBroker) SetMaxQueueSize(n int)

SetMaxQueueSize sets the maximum message queue size per topic.

func (*InMemoryMessageBroker) Start

Start starts the message broker

func (*InMemoryMessageBroker) Stop

Stop stops the message broker

func (*InMemoryMessageBroker) Subscribe

func (b *InMemoryMessageBroker) Subscribe(topic string, handler MessageHandler) error

Subscribe is a convenience method to subscribe a handler to a topic

type IntegrationConnector

type IntegrationConnector interface {
	// Connect establishes a connection to the external service
	Connect(ctx context.Context) error

	// Disconnect closes the connection to the external service
	Disconnect(ctx context.Context) error

	// Execute performs an action on the external service
	Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error)

	// GetName returns the name of the connector
	GetName() string

	// IsConnected checks if the connector is connected
	IsConnected() bool
}

IntegrationConnector represents a connector to a third-party service

type IntegrationRegistry

type IntegrationRegistry interface {
	// Name returns the name of the registry
	Name() string
	// Init initializes the registry
	Init(app modular.Application) error
	// Start starts the registry
	Start() error
	// Stop stops the registry
	Stop() error
	// RegisterConnector registers a new integration connector
	RegisterConnector(connector IntegrationConnector)
	// GetConnector retrieves a connector by name
	GetConnector(name string) (IntegrationConnector, error)
	// ListConnectors lists all registered connectors
	ListConnectors() []string
}

type JQStep

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

JQStep applies JQ expressions to pipeline data for complex transformations. It uses the gojq library (a pure-Go JQ implementation) to support the full JQ expression language including field access, pipes, map/select, object construction, arithmetic, conditionals, and more.

func (*JQStep) Execute

func (s *JQStep) Execute(_ context.Context, pc *PipelineContext) (*StepResult, error)

Execute applies the compiled JQ expression to the pipeline context's current data and returns the result. If input_from is configured, the expression is applied to the value at that path instead of the full current map.

func (*JQStep) Name

func (s *JQStep) Name() string

Name returns the step name.

type JSONResponseStep

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

JSONResponseStep writes an HTTP JSON response with a custom status code and stops the pipeline.

func (*JSONResponseStep) Execute

func (*JSONResponseStep) Name

func (s *JSONResponseStep) Name() string

type JWTAuthModule

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

JWTAuthModule handles JWT authentication with an in-memory user store. When an auth.user-store service is available, it delegates user CRUD to it; otherwise it uses its own internal map for backward compatibility.

func NewJWTAuthModule

func NewJWTAuthModule(name, secret string, tokenExpiry time.Duration, issuer string) *JWTAuthModule

NewJWTAuthModule creates a new JWT auth module

func (*JWTAuthModule) Authenticate

func (j *JWTAuthModule) Authenticate(tokenStr string) (bool, map[string]any, error)

Authenticate implements AuthProvider

func (*JWTAuthModule) Handle

func (j *JWTAuthModule) Handle(w http.ResponseWriter, r *http.Request)

Handle routes auth requests

func (*JWTAuthModule) Init

func (j *JWTAuthModule) Init(app modular.Application) error

Init initializes the module

func (*JWTAuthModule) Name

func (j *JWTAuthModule) Name() string

Name returns the module name

func (*JWTAuthModule) ProvidesServices

func (j *JWTAuthModule) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module

func (*JWTAuthModule) RequiresServices

func (j *JWTAuthModule) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module

func (*JWTAuthModule) SetResponseFormat

func (j *JWTAuthModule) SetResponseFormat(format string)

SetResponseFormat sets the response format for auth endpoints. "v1" returns {access_token, refresh_token, expires_in, user} and adds /auth/refresh, /auth/me, /auth/logout handlers. "standard" (default) returns {token, user}.

func (*JWTAuthModule) SetSeedFile

func (j *JWTAuthModule) SetSeedFile(path string)

SetSeedFile sets the path to a JSON file of seed users to load on start.

func (*JWTAuthModule) Start

func (j *JWTAuthModule) Start(ctx context.Context) error

Start loads persisted users if available, then seed users.

func (*JWTAuthModule) Stop

func (j *JWTAuthModule) Stop(ctx context.Context) error

Stop is a no-op

type Job

type Job interface {
	Execute(ctx context.Context) error
}

Job represents a scheduled job

type KafkaBroker

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

KafkaBroker implements the MessageBroker interface using Apache Kafka via Sarama.

func NewKafkaBroker

func NewKafkaBroker(name string) *KafkaBroker

NewKafkaBroker creates a new Kafka message broker.

func (*KafkaBroker) Consumer

func (b *KafkaBroker) Consumer() MessageConsumer

Consumer returns the message consumer interface.

func (*KafkaBroker) HealthStatus

func (b *KafkaBroker) HealthStatus() HealthCheckResult

HealthStatus implements the HealthCheckable interface.

func (*KafkaBroker) Init

func (b *KafkaBroker) Init(app modular.Application) error

Init initializes the module with the application context.

func (*KafkaBroker) Name

func (b *KafkaBroker) Name() string

Name returns the module name.

func (*KafkaBroker) Producer

func (b *KafkaBroker) Producer() MessageProducer

Producer returns the message producer interface.

func (*KafkaBroker) ProvidesServices

func (b *KafkaBroker) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*KafkaBroker) RequiresServices

func (b *KafkaBroker) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module.

func (*KafkaBroker) SetBrokers

func (b *KafkaBroker) SetBrokers(brokers []string)

SetBrokers sets the Kafka broker addresses.

func (*KafkaBroker) SetGroupID

func (b *KafkaBroker) SetGroupID(groupID string)

SetGroupID sets the Kafka consumer group ID.

func (*KafkaBroker) Start

func (b *KafkaBroker) Start(ctx context.Context) error

Start connects to Kafka and begins consuming.

func (*KafkaBroker) Stop

func (b *KafkaBroker) Stop(_ context.Context) error

Stop disconnects from Kafka.

func (*KafkaBroker) Subscribe

func (b *KafkaBroker) Subscribe(topic string, handler MessageHandler) error

Subscribe is a convenience method to subscribe a handler to a topic.

type ListenerAdapter

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

ListenerAdapter adapts a TransitionListener function to a TransitionHandler

func NewListenerAdapter

func NewListenerAdapter(listener TransitionListener) *ListenerAdapter

NewListenerAdapter creates a new adapter for a transition listener

func (*ListenerAdapter) HandleTransition

func (a *ListenerAdapter) HandleTransition(ctx context.Context, event TransitionEvent) error

HandleTransition implements the TransitionHandler interface

type LocalStorageModule

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

LocalStorageModule wraps a store.LocalStorage as a modular.Module.

func NewLocalStorageModule

func NewLocalStorageModule(name, rootDir string) *LocalStorageModule

NewLocalStorageModule creates a new local filesystem storage module.

func (*LocalStorageModule) Delete

func (m *LocalStorageModule) Delete(ctx context.Context, path string) error

func (*LocalStorageModule) Get

func (*LocalStorageModule) Init

func (*LocalStorageModule) List

func (m *LocalStorageModule) List(ctx context.Context, prefix string) ([]store.FileInfo, error)

func (*LocalStorageModule) Name

func (m *LocalStorageModule) Name() string

func (*LocalStorageModule) ProvidesServices

func (m *LocalStorageModule) ProvidesServices() []modular.ServiceProvider

func (*LocalStorageModule) Put

func (m *LocalStorageModule) Put(ctx context.Context, path string, reader io.Reader) error

func (*LocalStorageModule) RequiresServices

func (m *LocalStorageModule) RequiresServices() []modular.ServiceDependency

func (*LocalStorageModule) Start

func (*LocalStorageModule) Stat

func (*LocalStorageModule) Stop

func (*LocalStorageModule) Storage

Storage returns the underlying StorageProvider, or nil if not started.

type LogCollector

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

LogCollector collects log entries from modules implementing LogEmitter and exposes them via a /logs HTTP endpoint.

func NewLogCollector

func NewLogCollector(name string, cfg LogCollectorConfig) *LogCollector

NewLogCollector creates a new LogCollector module.

func (*LogCollector) AddEntry

func (lc *LogCollector) AddEntry(entry LogEntry)

AddEntry adds a single log entry to the collector.

func (*LogCollector) CollectFromEmitters

func (lc *LogCollector) CollectFromEmitters()

CollectFromEmitters scans the service registry for LogEmitter services and drains their log entries.

func (*LogCollector) Entries

func (lc *LogCollector) Entries() []LogEntry

Entries returns a copy of the current log entries.

func (*LogCollector) Init

func (lc *LogCollector) Init(app modular.Application) error

Init registers the log collector as a service.

func (*LogCollector) LogHandler

func (lc *LogCollector) LogHandler() http.HandlerFunc

LogHandler returns an HTTP handler that serves collected logs.

func (*LogCollector) Name

func (lc *LogCollector) Name() string

Name returns the module name.

func (*LogCollector) ProvidesServices

func (lc *LogCollector) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*LogCollector) RequiresServices

func (lc *LogCollector) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*LogCollector) StartCollectionLoop

func (lc *LogCollector) StartCollectionLoop(ctx context.Context, interval time.Duration) context.CancelFunc

StartCollectionLoop runs a background goroutine that periodically collects logs from emitters. Call the returned cancel function to stop.

type LogCollectorConfig

type LogCollectorConfig struct {
	LogLevel      string `yaml:"logLevel" json:"logLevel"`
	OutputFormat  string `yaml:"outputFormat" json:"outputFormat"`
	RetentionDays int    `yaml:"retentionDays" json:"retentionDays"`
}

LogCollectorConfig holds the configuration for the log collector module.

type LogEmitter

type LogEmitter interface {
	DrainLogs() []LogEntry
}

LogEmitter is implemented by modules that produce log entries. The log collector auto-discovers services implementing this interface.

type LogEntry

type LogEntry struct {
	Timestamp time.Time `json:"timestamp"`
	Module    string    `json:"module"`
	Level     string    `json:"level"`
	Message   string    `json:"message"`
}

LogEntry represents a single log message collected from a module.

type LogHTTPHandler

type LogHTTPHandler struct {
	Handler http.HandlerFunc
}

LogHTTPHandler adapts an http.HandlerFunc to the HTTPHandler interface.

func (*LogHTTPHandler) Handle

func (h *LogHTTPHandler) Handle(w http.ResponseWriter, r *http.Request)

Handle implements the HTTPHandler interface.

type LogStep

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

LogStep logs a template-resolved message at a specified level.

func (*LogStep) Execute

func (s *LogStep) Execute(_ context.Context, pc *PipelineContext) (*StepResult, error)

Execute resolves the message template and logs it at the configured level.

func (*LogStep) Name

func (s *LogStep) Name() string

Name returns the step name.

type LoggingMiddleware

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

LoggingMiddleware provides request logging

func NewLoggingMiddleware

func NewLoggingMiddleware(name string, logLevel string) *LoggingMiddleware

NewLoggingMiddleware creates a new logging middleware

func (*LoggingMiddleware) Init

Init initializes the middleware

func (*LoggingMiddleware) Name

func (m *LoggingMiddleware) Name() string

Name returns the module name

func (*LoggingMiddleware) Process

func (m *LoggingMiddleware) Process(next http.Handler) http.Handler

Process implements middleware processing

func (*LoggingMiddleware) ProvidesServices

func (m *LoggingMiddleware) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this middleware

func (*LoggingMiddleware) RequiresServices

func (m *LoggingMiddleware) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this middleware

type MessageBroker

type MessageBroker interface {
	Producer() MessageProducer
	Consumer() MessageConsumer
	Subscribe(topic string, handler MessageHandler) error
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

MessageBroker interface for message broker modules

type MessageConsumer

type MessageConsumer interface {
	Subscribe(topic string, handler MessageHandler) error
	Unsubscribe(topic string) error
}

MessageConsumer interface for consuming messages

type MessageHandler

type MessageHandler interface {
	HandleMessage(message []byte) error
}

MessageHandler interface for handling messages

type MessageHandlerAdapter

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

MessageHandlerAdapter adapts a function to the MessageHandler interface

func (*MessageHandlerAdapter) HandleMessage

func (a *MessageHandlerAdapter) HandleMessage(msg []byte) error

HandleMessage implements the MessageHandler interface

type MessageHandlerJobAdapter

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

MessageHandlerJobAdapter adapts a MessageHandler to the Job interface

func NewMessageHandlerJobAdapter

func NewMessageHandlerJobAdapter(handler MessageHandler) *MessageHandlerJobAdapter

NewMessageHandlerJobAdapter creates a new adapter from MessageHandler to Job

func (*MessageHandlerJobAdapter) Execute

Execute runs the job by calling HandleMessage with an empty message

type MessageProducer

type MessageProducer interface {
	SendMessage(topic string, message []byte) error
}

MessageProducer interface for producing messages

type MetricsCollector

type MetricsCollector struct {
	WorkflowExecutions  *prometheus.CounterVec
	WorkflowDuration    *prometheus.HistogramVec
	HTTPRequestsTotal   *prometheus.CounterVec
	HTTPRequestDuration *prometheus.HistogramVec
	ModuleOperations    *prometheus.CounterVec
	ActiveWorkflows     *prometheus.GaugeVec
	// contains filtered or unexported fields
}

MetricsCollector wraps Prometheus metrics for the workflow engine. It registers as service "metrics.collector" and provides pre-defined metric vectors.

func NewMetricsCollector

func NewMetricsCollector(name string) *MetricsCollector

NewMetricsCollector creates a new MetricsCollector with its own Prometheus registry.

func NewMetricsCollectorWithConfig

func NewMetricsCollectorWithConfig(name string, cfg MetricsCollectorConfig) *MetricsCollector

NewMetricsCollectorWithConfig creates a new MetricsCollector with the given config.

func (*MetricsCollector) Handler

func (m *MetricsCollector) Handler() http.Handler

Handler returns an HTTP handler that serves Prometheus metrics.

func (*MetricsCollector) Init

Init registers the metrics collector as a service.

func (*MetricsCollector) MetricsPath

func (m *MetricsCollector) MetricsPath() string

MetricsPath returns the configured metrics endpoint path.

func (*MetricsCollector) Name

func (m *MetricsCollector) Name() string

Name returns the module name.

func (*MetricsCollector) ProvidesServices

func (m *MetricsCollector) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*MetricsCollector) RecordHTTPRequest

func (m *MetricsCollector) RecordHTTPRequest(method, path string, statusCode int, duration time.Duration)

RecordHTTPRequest records an HTTP request metric.

func (*MetricsCollector) RecordModuleOperation

func (m *MetricsCollector) RecordModuleOperation(module, operation, status string)

RecordModuleOperation records a module operation metric.

func (*MetricsCollector) RecordWorkflowDuration

func (m *MetricsCollector) RecordWorkflowDuration(workflowType, action string, duration time.Duration)

RecordWorkflowDuration records the duration of a workflow execution.

func (*MetricsCollector) RecordWorkflowExecution

func (m *MetricsCollector) RecordWorkflowExecution(workflowType, action, status string)

RecordWorkflowExecution increments the workflow execution counter.

func (*MetricsCollector) RequiresServices

func (m *MetricsCollector) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*MetricsCollector) SetActiveWorkflows

func (m *MetricsCollector) SetActiveWorkflows(workflowType string, count float64)

SetActiveWorkflows sets the gauge for active workflows of a given type.

type MetricsCollectorConfig

type MetricsCollectorConfig struct {
	Namespace      string   `yaml:"namespace" json:"namespace"`
	Subsystem      string   `yaml:"subsystem" json:"subsystem"`
	MetricsPath    string   `yaml:"metricsPath" json:"metricsPath"`
	EnabledMetrics []string `yaml:"enabledMetrics" json:"enabledMetrics"`
}

MetricsCollectorConfig holds configuration for the MetricsCollector module.

func DefaultMetricsCollectorConfig

func DefaultMetricsCollectorConfig() MetricsCollectorConfig

DefaultMetricsCollectorConfig returns the default configuration.

type MetricsHTTPHandler

type MetricsHTTPHandler struct {
	Handler http.Handler
}

MetricsHTTPHandler adapts an http.Handler to the HTTPHandler interface

func (*MetricsHTTPHandler) Handle

Handle implements the HTTPHandler interface

type MockApplication

type MockApplication struct {
	Services         map[string]any
	Config           map[string]any
	ConfigSectionMap map[string]modular.ConfigProvider
	MockLogger       *MockLogger
	Modules          map[string]modular.Module
}

MockApplication is a mock implementation of modular.Application for testing

func NewMockApplication

func NewMockApplication() *MockApplication

NewMockApplication creates a new instance of a MockApplication

func (*MockApplication) ConfigProvider

func (a *MockApplication) ConfigProvider() modular.ConfigProvider

func (*MockApplication) ConfigSections

func (a *MockApplication) ConfigSections() map[string]modular.ConfigProvider

func (*MockApplication) GetAllModules

func (a *MockApplication) GetAllModules() map[string]modular.Module

GetAllModules returns a map of all registered modules

func (*MockApplication) GetConfig

func (a *MockApplication) GetConfig() map[string]any

func (*MockApplication) GetConfigSection

func (a *MockApplication) GetConfigSection(section string) (modular.ConfigProvider, error)

func (*MockApplication) GetModule

func (a *MockApplication) GetModule(name string) modular.Module

GetModule returns the module with the given name

func (*MockApplication) GetService

func (a *MockApplication) GetService(name string, out any) error

func (*MockApplication) GetServiceEntry

func (a *MockApplication) GetServiceEntry(serviceName string) (*modular.ServiceRegistryEntry, bool)

GetServiceEntry retrieves detailed information about a registered service

func (*MockApplication) GetServicesByInterface

func (a *MockApplication) GetServicesByInterface(interfaceType reflect.Type) []*modular.ServiceRegistryEntry

GetServicesByInterface returns all services that implement the given interface

func (*MockApplication) GetServicesByModule

func (a *MockApplication) GetServicesByModule(moduleName string) []string

GetServicesByModule returns all services provided by a specific module

func (*MockApplication) Init

func (a *MockApplication) Init() error

func (*MockApplication) IsVerboseConfig

func (a *MockApplication) IsVerboseConfig() bool

IsVerboseConfig returns whether verbose config debugging is enabled

func (*MockApplication) Logger

func (a *MockApplication) Logger() modular.Logger

func (*MockApplication) OnConfigLoaded

func (a *MockApplication) OnConfigLoaded(hook func(modular.Application) error)

OnConfigLoaded registers a callback to run after config loading

func (*MockApplication) RegisterConfigSection

func (a *MockApplication) RegisterConfigSection(name string, config modular.ConfigProvider)

func (*MockApplication) RegisterModule

func (a *MockApplication) RegisterModule(module modular.Module)

RegisterModule registers a module with the application

func (*MockApplication) RegisterService

func (a *MockApplication) RegisterService(name string, service any) error

func (*MockApplication) Run

func (a *MockApplication) Run() error

Run satisfies the modular.Application interface

func (*MockApplication) SetLogger

func (a *MockApplication) SetLogger(logger modular.Logger)

SetLogger sets the application's logger

func (*MockApplication) SetVerboseConfig

func (a *MockApplication) SetVerboseConfig(enabled bool)

SetVerboseConfig sets verbose config debugging (no-op for tests)

func (*MockApplication) Start

func (a *MockApplication) Start() error

func (*MockApplication) StartTime

func (a *MockApplication) StartTime() time.Time

StartTime returns the time when the application was started

func (*MockApplication) Stop

func (a *MockApplication) Stop() error

func (*MockApplication) SvcRegistry

func (a *MockApplication) SvcRegistry() modular.ServiceRegistry

SvcRegistry satisfies the modular.Application interface

type MockConfigProvider

type MockConfigProvider struct {
	Config map[string]any // Changed from lowercase config to Config to match usage elsewhere
}

MockConfigProvider is a mock implementation of modular.ConfigProvider for testing

func (*MockConfigProvider) GetConfig

func (p *MockConfigProvider) GetConfig() any

type MockLogger

type MockLogger struct {
	Messages []string
}

MockLogger implements modular.Logger for testing

func (*MockLogger) Debug

func (l *MockLogger) Debug(format string, args ...any)

func (*MockLogger) Error

func (l *MockLogger) Error(format string, args ...any)

func (*MockLogger) Fatal

func (l *MockLogger) Fatal(format string, args ...any)

func (*MockLogger) Info

func (l *MockLogger) Info(format string, args ...any)

func (*MockLogger) Warn

func (l *MockLogger) Warn(format string, args ...any)

type MockScheduler

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

MockScheduler is a mock implementation of the Scheduler interface

func NewMockScheduler

func NewMockScheduler() *MockScheduler

func (*MockScheduler) Init

func (s *MockScheduler) Init(registry modular.ServiceRegistry) error

func (*MockScheduler) Name

func (s *MockScheduler) Name() string

func (*MockScheduler) Schedule

func (s *MockScheduler) Schedule(job Job) error

func (*MockScheduler) SetCronExpression

func (s *MockScheduler) SetCronExpression(index int, cronExpression string)

For our tests, we'll add this method to set the cron expression for a scheduled job

func (*MockScheduler) Start

func (s *MockScheduler) Start(ctx context.Context) error

func (*MockScheduler) Stop

func (s *MockScheduler) Stop(ctx context.Context) error

type MockWorkflowEngine

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

MockWorkflowEngine is a mock implementation of the WorkflowEngine interface

func NewMockWorkflowEngine

func NewMockWorkflowEngine() *MockWorkflowEngine

func (*MockWorkflowEngine) TriggerWorkflow

func (e *MockWorkflowEngine) TriggerWorkflow(ctx context.Context, workflowType string, action string, data map[string]any) error

type ModuleNamespace

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

ModuleNamespace represents the legacy struct (for backward compatibility)

func NewModuleNamespace

func NewModuleNamespace(prefix string, suffix string) *ModuleNamespace

NewModuleNamespace creates a new module namespace with optional prefix and suffix

func (*ModuleNamespace) FormatName

func (ns *ModuleNamespace) FormatName(baseName string) string

FormatName formats a module name with the namespace prefix/suffix

func (*ModuleNamespace) ResolveDependency

func (ns *ModuleNamespace) ResolveDependency(dependencyName string) string

ResolveDependency formats a dependency name with the namespace prefix/suffix

func (*ModuleNamespace) ResolveServiceName

func (ns *ModuleNamespace) ResolveServiceName(serviceName string) string

ResolveServiceName formats a service name with the namespace prefix/suffix

type ModuleNamespaceProvider

type ModuleNamespaceProvider interface {
	// FormatName formats a module name with the namespace
	FormatName(baseName string) string

	// ResolveDependency formats a dependency name with the namespace
	ResolveDependency(dependencyName string) string

	// ResolveServiceName formats a service name with the namespace
	ResolveServiceName(serviceName string) string

	// ValidateModuleName checks if a module name conforms to namespace requirements
	ValidateModuleName(moduleName string) error
}

ModuleNamespaceProvider defines the interface for module namespace functionality

type ModuleNamespaceProviderFunc

type ModuleNamespaceProviderFunc struct {
	FormatNameFunc         func(baseName string) string
	ResolveDependencyFunc  func(dependencyName string) string
	ResolveServiceNameFunc func(serviceName string) string
	ValidateModuleNameFunc func(moduleName string) error
}

ModuleNamespaceProviderFunc provides a functional implementation of ModuleNamespaceProvider

func (ModuleNamespaceProviderFunc) FormatName

func (m ModuleNamespaceProviderFunc) FormatName(baseName string) string

FormatName formats a base name with the namespace

func (ModuleNamespaceProviderFunc) ResolveDependency

func (m ModuleNamespaceProviderFunc) ResolveDependency(dependencyName string) string

ResolveDependency resolves a dependency name with the namespace

func (ModuleNamespaceProviderFunc) ResolveServiceName

func (m ModuleNamespaceProviderFunc) ResolveServiceName(serviceName string) string

ResolveServiceName resolves a service name with the namespace

func (ModuleNamespaceProviderFunc) ValidateModuleName

func (m ModuleNamespaceProviderFunc) ValidateModuleName(moduleName string) error

ValidateModuleName validates a module name

type NATSBroker

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

NATSBroker implements the MessageBroker interface using NATS.

func NewNATSBroker

func NewNATSBroker(name string) *NATSBroker

NewNATSBroker creates a new NATS message broker.

func (*NATSBroker) Consumer

func (b *NATSBroker) Consumer() MessageConsumer

Consumer returns the message consumer interface.

func (*NATSBroker) Init

func (b *NATSBroker) Init(app modular.Application) error

Init initializes the module with the application context.

func (*NATSBroker) Name

func (b *NATSBroker) Name() string

Name returns the module name.

func (*NATSBroker) Producer

func (b *NATSBroker) Producer() MessageProducer

Producer returns the message producer interface.

func (*NATSBroker) ProvidesServices

func (b *NATSBroker) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*NATSBroker) RequiresServices

func (b *NATSBroker) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module.

func (*NATSBroker) SetURL

func (b *NATSBroker) SetURL(url string)

SetURL sets the NATS server URL.

func (*NATSBroker) Start

func (b *NATSBroker) Start(ctx context.Context) error

Start connects to NATS and activates any pending subscriptions.

func (*NATSBroker) Stop

func (b *NATSBroker) Stop(_ context.Context) error

Stop disconnects from NATS.

func (*NATSBroker) Subscribe

func (b *NATSBroker) Subscribe(topic string, handler MessageHandler) error

Subscribe is a convenience method to subscribe a handler to a topic.

type OTelTracing

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

OTelTracing provides OpenTelemetry distributed tracing. It implements the modular.Module interface.

func NewOTelTracing

func NewOTelTracing(name string) *OTelTracing

NewOTelTracing creates a new OpenTelemetry tracing module.

func (*OTelTracing) Init

func (o *OTelTracing) Init(app modular.Application) error

Init initializes the module with the application context.

func (*OTelTracing) Name

func (o *OTelTracing) Name() string

Name returns the module name.

func (*OTelTracing) ProvidesServices

func (o *OTelTracing) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*OTelTracing) RequiresServices

func (o *OTelTracing) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module.

func (*OTelTracing) SetEndpoint

func (o *OTelTracing) SetEndpoint(endpoint string)

SetEndpoint sets the OTLP endpoint.

func (*OTelTracing) SetServiceName

func (o *OTelTracing) SetServiceName(serviceName string)

SetServiceName sets the service name used in traces.

func (*OTelTracing) Start

func (o *OTelTracing) Start(ctx context.Context) error

Start initializes the OTLP exporter and TracerProvider.

func (*OTelTracing) Stop

func (o *OTelTracing) Stop(ctx context.Context) error

Stop shuts down the TracerProvider gracefully.

type OpenAPIComponents

type OpenAPIComponents struct {
	Schemas map[string]*OpenAPISchema `json:"schemas,omitempty" yaml:"schemas,omitempty"`
}

OpenAPIComponents holds reusable schema components.

type OpenAPIConsumer

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

OpenAPIConsumer parses an external OpenAPI spec and generates typed HTTP client methods matching the spec operations. It provides an ExternalAPIClient service that other modules can use to call the external API.

func NewOpenAPIConsumer

func NewOpenAPIConsumer(name string, config OpenAPIConsumerConfig) *OpenAPIConsumer

NewOpenAPIConsumer creates a new OpenAPI consumer module.

func (*OpenAPIConsumer) CallOperation

func (c *OpenAPIConsumer) CallOperation(ctx context.Context, operationID string, data map[string]any) (map[string]any, error)

CallOperation invokes an external API operation by its operation ID. It resolves path parameters from the provided data map, applies field mappings, and returns the response.

func (*OpenAPIConsumer) GetFieldMapping

func (c *OpenAPIConsumer) GetFieldMapping() *FieldMapping

GetFieldMapping returns the current field mapping.

func (*OpenAPIConsumer) GetSpec

func (c *OpenAPIConsumer) GetSpec() *OpenAPISpec

GetSpec returns the loaded OpenAPI spec.

func (*OpenAPIConsumer) Init

Init registers the consumer as a service and loads the spec.

func (*OpenAPIConsumer) ListOperations

func (c *OpenAPIConsumer) ListOperations() []ExternalOperation

ListOperations returns all operations defined in the loaded spec.

func (*OpenAPIConsumer) Name

func (c *OpenAPIConsumer) Name() string

Name returns the module name.

func (*OpenAPIConsumer) ProvidesServices

func (c *OpenAPIConsumer) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*OpenAPIConsumer) RequiresServices

func (c *OpenAPIConsumer) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*OpenAPIConsumer) ServeOperations

func (c *OpenAPIConsumer) ServeOperations(w http.ResponseWriter, _ *http.Request)

ServeOperations serves the list of available operations as JSON.

func (*OpenAPIConsumer) ServeSpec

func (c *OpenAPIConsumer) ServeSpec(w http.ResponseWriter, _ *http.Request)

ServeSpec serves the loaded spec directly.

func (*OpenAPIConsumer) SetClient

func (c *OpenAPIConsumer) SetClient(client *http.Client)

SetClient sets a custom HTTP client (useful for testing).

func (*OpenAPIConsumer) SetFieldMapping

func (c *OpenAPIConsumer) SetFieldMapping(fm *FieldMapping)

SetFieldMapping sets the field mapping for transforming data between local workflow data and external API schemas.

type OpenAPIConsumerConfig

type OpenAPIConsumerConfig struct {
	SpecURL  string `json:"specUrl" yaml:"specUrl"`
	SpecFile string `json:"specFile" yaml:"specFile"`
}

OpenAPIConsumerConfig holds configuration for the OpenAPI consumer module.

type OpenAPIGenerator

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

OpenAPIGenerator is a module that scans workflow route definitions and generates an OpenAPI 3.0 specification, serving it at configurable endpoints.

func NewOpenAPIGenerator

func NewOpenAPIGenerator(name string, config OpenAPIGeneratorConfig) *OpenAPIGenerator

NewOpenAPIGenerator creates a new OpenAPI generator module.

func (*OpenAPIGenerator) ApplySchemas

func (g *OpenAPIGenerator) ApplySchemas()

ApplySchemas applies all registered component schemas and operation schema overrides to the current spec. Call this after BuildSpec.

func (*OpenAPIGenerator) BuildSpec

func (g *OpenAPIGenerator) BuildSpec(workflows map[string]any)

BuildSpec scans the workflow config and builds the OpenAPI spec. This should be called after all modules and workflows are registered.

func (*OpenAPIGenerator) BuildSpecFromRoutes

func (g *OpenAPIGenerator) BuildSpecFromRoutes(routes []RouteDefinition)

BuildSpecFromRoutes builds an OpenAPI spec from explicit route definitions.

func (*OpenAPIGenerator) GetSpec

func (g *OpenAPIGenerator) GetSpec() *OpenAPISpec

GetSpec returns the current OpenAPI spec.

func (*OpenAPIGenerator) Handle

func (g *OpenAPIGenerator) Handle(w http.ResponseWriter, r *http.Request)

Handle dispatches to JSON or YAML handler based on path suffix.

func (*OpenAPIGenerator) Init

Init registers the generator as a service and builds the initial spec.

func (*OpenAPIGenerator) Name

func (g *OpenAPIGenerator) Name() string

Name returns the module name.

func (*OpenAPIGenerator) ProvidesServices

func (g *OpenAPIGenerator) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*OpenAPIGenerator) RegisterComponentSchema

func (g *OpenAPIGenerator) RegisterComponentSchema(name string, schema *OpenAPISchema)

RegisterComponentSchema adds a named schema to the components/schemas section. Call this before BuildSpec or after BuildSpec to add reusable schemas.

func (*OpenAPIGenerator) RequiresServices

func (g *OpenAPIGenerator) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*OpenAPIGenerator) ServeHTTP

func (g *OpenAPIGenerator) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler.

func (*OpenAPIGenerator) ServeJSON

func (g *OpenAPIGenerator) ServeJSON(w http.ResponseWriter, _ *http.Request)

ServeJSON serves the OpenAPI spec as JSON.

func (*OpenAPIGenerator) ServeYAML

func (g *OpenAPIGenerator) ServeYAML(w http.ResponseWriter, _ *http.Request)

ServeYAML serves the OpenAPI spec as YAML.

func (*OpenAPIGenerator) SetOperationSchema

func (g *OpenAPIGenerator) SetOperationSchema(method, path string, req, resp *OpenAPISchema)

SetOperationSchema sets request/response schemas for a specific operation. The method and path must match what appears in the workflow route definitions.

func (*OpenAPIGenerator) SortedPaths

func (g *OpenAPIGenerator) SortedPaths() []string

SortedPaths returns the spec paths sorted alphabetically (useful for stable output).

type OpenAPIGeneratorConfig

type OpenAPIGeneratorConfig struct {
	Title       string   `json:"title" yaml:"title"`
	Version     string   `json:"version" yaml:"version"`
	Description string   `json:"description" yaml:"description"`
	Servers     []string `json:"servers" yaml:"servers"`
}

OpenAPIGeneratorConfig holds configuration for the OpenAPI generator module.

type OpenAPIHTTPHandler

type OpenAPIHTTPHandler struct {
	Handler http.HandlerFunc
}

OpenAPIHTTPHandler adapts the OpenAPIGenerator to the HTTPHandler interface.

func (*OpenAPIHTTPHandler) Handle

Handle implements the HTTPHandler interface.

type OpenAPIInfo

type OpenAPIInfo struct {
	Title       string `json:"title" yaml:"title"`
	Version     string `json:"version" yaml:"version"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
}

OpenAPIInfo holds API metadata.

type OpenAPIMediaType

type OpenAPIMediaType struct {
	Schema *OpenAPISchema `json:"schema,omitempty" yaml:"schema,omitempty"`
}

OpenAPIMediaType describes a media type with schema.

type OpenAPIOperation

type OpenAPIOperation struct {
	Summary     string                      `json:"summary,omitempty" yaml:"summary,omitempty"`
	OperationID string                      `json:"operationId,omitempty" yaml:"operationId,omitempty"`
	Tags        []string                    `json:"tags,omitempty" yaml:"tags,omitempty"`
	Parameters  []OpenAPIParameter          `json:"parameters,omitempty" yaml:"parameters,omitempty"`
	RequestBody *OpenAPIRequestBody         `json:"requestBody,omitempty" yaml:"requestBody,omitempty"`
	Responses   map[string]*OpenAPIResponse `json:"responses" yaml:"responses"`
}

OpenAPIOperation describes an API operation.

type OpenAPIParameter

type OpenAPIParameter struct {
	Name        string         `json:"name" yaml:"name"`
	In          string         `json:"in" yaml:"in"` // path, query, header
	Required    bool           `json:"required,omitempty" yaml:"required,omitempty"`
	Description string         `json:"description,omitempty" yaml:"description,omitempty"`
	Schema      *OpenAPISchema `json:"schema,omitempty" yaml:"schema,omitempty"`
}

OpenAPIParameter describes a path/query/header parameter.

type OpenAPIPath

type OpenAPIPath struct {
	Get     *OpenAPIOperation `json:"get,omitempty" yaml:"get,omitempty"`
	Post    *OpenAPIOperation `json:"post,omitempty" yaml:"post,omitempty"`
	Put     *OpenAPIOperation `json:"put,omitempty" yaml:"put,omitempty"`
	Delete  *OpenAPIOperation `json:"delete,omitempty" yaml:"delete,omitempty"`
	Patch   *OpenAPIOperation `json:"patch,omitempty" yaml:"patch,omitempty"`
	Options *OpenAPIOperation `json:"options,omitempty" yaml:"options,omitempty"`
}

OpenAPIPath holds operations for a single path.

type OpenAPIRequestBody

type OpenAPIRequestBody struct {
	Required    bool                         `json:"required,omitempty" yaml:"required,omitempty"`
	Description string                       `json:"description,omitempty" yaml:"description,omitempty"`
	Content     map[string]*OpenAPIMediaType `json:"content,omitempty" yaml:"content,omitempty"`
}

OpenAPIRequestBody describes a request body.

type OpenAPIResponse

type OpenAPIResponse struct {
	Description string                       `json:"description" yaml:"description"`
	Content     map[string]*OpenAPIMediaType `json:"content,omitempty" yaml:"content,omitempty"`
}

OpenAPIResponse describes a response.

type OpenAPISchema

type OpenAPISchema struct {
	Ref                  string                    `json:"$ref,omitempty" yaml:"$ref,omitempty"`
	Type                 string                    `json:"type,omitempty" yaml:"type,omitempty"`
	Format               string                    `json:"format,omitempty" yaml:"format,omitempty"`
	Description          string                    `json:"description,omitempty" yaml:"description,omitempty"`
	Properties           map[string]*OpenAPISchema `json:"properties,omitempty" yaml:"properties,omitempty"`
	Items                *OpenAPISchema            `json:"items,omitempty" yaml:"items,omitempty"`
	Required             []string                  `json:"required,omitempty" yaml:"required,omitempty"`
	Enum                 []string                  `json:"enum,omitempty" yaml:"enum,omitempty"`
	AdditionalProperties *OpenAPISchema            `json:"additionalProperties,omitempty" yaml:"additionalProperties,omitempty"`
	Nullable             bool                      `json:"nullable,omitempty" yaml:"nullable,omitempty"`
	Example              any                       `json:"example,omitempty" yaml:"example,omitempty"`
}

OpenAPISchema is a minimal JSON Schema subset for OpenAPI.

func SchemaArray

func SchemaArray(items *OpenAPISchema) *OpenAPISchema

SchemaArray returns a schema for an array of the given item schema.

func SchemaRef

func SchemaRef(name string) *OpenAPISchema

SchemaRef returns an OpenAPISchema that is a $ref to a component schema.

type OpenAPIServer

type OpenAPIServer struct {
	URL         string `json:"url" yaml:"url"`
	Description string `json:"description,omitempty" yaml:"description,omitempty"`
}

OpenAPIServer describes a server URL.

type OpenAPISpec

type OpenAPISpec struct {
	OpenAPI    string                  `json:"openapi" yaml:"openapi"`
	Info       OpenAPIInfo             `json:"info" yaml:"info"`
	Servers    []OpenAPIServer         `json:"servers,omitempty" yaml:"servers,omitempty"`
	Paths      map[string]*OpenAPIPath `json:"paths" yaml:"paths"`
	Components *OpenAPIComponents      `json:"components,omitempty" yaml:"components,omitempty"`
}

OpenAPISpec represents a minimal OpenAPI 3.0 specification document.

type PatternMatch

type PatternMatch struct {
	PatternID   string      `json:"patternId"`
	Events      []EventData `json:"events"`
	MatchedTime time.Time   `json:"matchedTime"`
}

PatternMatch represents a successful pattern match

type PersistenceStore

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

PersistenceStore provides SQLite-backed persistence for workflow instances, resources, and users.

func NewPersistenceStore

func NewPersistenceStore(name, dbServiceName string) *PersistenceStore

NewPersistenceStore creates a new PersistenceStore module.

func (*PersistenceStore) DeleteResource

func (p *PersistenceStore) DeleteResource(resourceType, id string) error

DeleteResource deletes a resource by type and ID.

func (*PersistenceStore) Init

Init looks up the WorkflowDatabase service and runs schema migrations.

func (*PersistenceStore) LoadResources

func (p *PersistenceStore) LoadResources(resourceType string) (map[string]map[string]any, error)

LoadResources loads all resources for a given type, keyed by ID. Encrypted PII fields are decrypted transparently on read.

func (*PersistenceStore) LoadUsers

func (p *PersistenceStore) LoadUsers() ([]UserRecord, error)

LoadUsers loads all user records. Encrypted PII fields (name, email) are decrypted transparently on read.

func (*PersistenceStore) LoadWorkflowInstances

func (p *PersistenceStore) LoadWorkflowInstances(workflowType string) ([]*WorkflowInstance, error)

LoadWorkflowInstances loads all instances for a given workflow type.

func (*PersistenceStore) Name

func (p *PersistenceStore) Name() string

Name returns the module name.

func (*PersistenceStore) Ping

func (p *PersistenceStore) Ping(ctx context.Context) error

Ping verifies the database connection is alive.

func (*PersistenceStore) ProvidesServices

func (p *PersistenceStore) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns services provided by this module.

func (*PersistenceStore) RequiresServices

func (p *PersistenceStore) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*PersistenceStore) SaveResource

func (p *PersistenceStore) SaveResource(resourceType, id string, data map[string]any) error

SaveResource upserts a resource. PII fields within the data map are encrypted before writing to SQLite when ENCRYPTION_KEY is set.

func (*PersistenceStore) SaveUser

func (p *PersistenceStore) SaveUser(user UserRecord) error

SaveUser upserts a user record. PII fields (name, email) are encrypted before writing to SQLite when ENCRYPTION_KEY is set.

func (*PersistenceStore) SaveWorkflowInstance

func (p *PersistenceStore) SaveWorkflowInstance(instance *WorkflowInstance) error

SaveWorkflowInstance upserts a workflow instance. PII fields within instance data are encrypted before writing to SQLite when ENCRYPTION_KEY is set.

func (*PersistenceStore) SetDB

func (p *PersistenceStore) SetDB(db *sql.DB)

SetDB sets the underlying database connection directly (useful for testing).

func (*PersistenceStore) SetEncryptor

func (p *PersistenceStore) SetEncryptor(enc *FieldEncryptor)

SetEncryptor sets a custom field encryptor (useful for testing).

func (*PersistenceStore) Start

func (p *PersistenceStore) Start(ctx context.Context) error

Start is a no-op; data loading can be triggered explicitly.

func (*PersistenceStore) Stop

func (p *PersistenceStore) Stop(ctx context.Context) error

Stop is a no-op; the database lifecycle is owned by WorkflowDatabase.

type Pipeline

type Pipeline struct {
	Name         string
	Steps        []PipelineStep
	OnError      ErrorStrategy
	Timeout      time.Duration
	Compensation []PipelineStep
	Logger       *slog.Logger
	// Metadata is pre-seeded metadata merged into the PipelineContext.
	// Used to pass HTTP context (request/response) for delegate steps.
	Metadata map[string]any
	// RoutePattern is the original route path pattern (e.g., "/api/v1/admin/companies/{id}")
	// used by step.request_parse for path parameter extraction.
	RoutePattern string

	// EventRecorder is an optional recorder for execution events.
	// When nil (the default), no events are recorded. Events are best-effort:
	// recording failures are logged but never fail the pipeline.
	EventRecorder EventRecorder

	// ExecutionID identifies this pipeline execution for event correlation.
	// Set by the caller when event recording is desired.
	ExecutionID string
	// contains filtered or unexported fields
}

Pipeline is an ordered sequence of steps with error handling.

func (*Pipeline) Execute

func (p *Pipeline) Execute(ctx context.Context, triggerData map[string]any) (*PipelineContext, error)

Execute runs the pipeline from trigger data.

type PipelineContext

type PipelineContext struct {
	// TriggerData is the original data from the trigger (immutable after creation).
	TriggerData map[string]any

	// StepOutputs maps step-name -> output from each completed step.
	StepOutputs map[string]map[string]any

	// Current is the merged state: trigger data + all step outputs.
	// Steps read from Current and their output is merged back into it.
	Current map[string]any

	// Metadata holds execution metadata (pipeline name, trace ID, etc.)
	Metadata map[string]any
}

PipelineContext carries data through a pipeline execution.

func NewPipelineContext

func NewPipelineContext(triggerData map[string]any, metadata map[string]any) *PipelineContext

NewPipelineContext creates a PipelineContext initialized with trigger data.

func (*PipelineContext) MergeStepOutput

func (pc *PipelineContext) MergeStepOutput(stepName string, output map[string]any)

MergeStepOutput records a step's output and merges it into Current.

type PipelineStep

type PipelineStep interface {
	// Name returns the step's unique name within the pipeline.
	Name() string

	// Execute runs the step with the pipeline context.
	// It receives accumulated data from previous steps and returns
	// its own output to be merged into the context.
	Execute(ctx context.Context, pc *PipelineContext) (*StepResult, error)
}

PipelineStep is a single composable unit of work in a pipeline.

type ProcessingStep

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

ProcessingStep bridges dynamic components to state machine transitions. It implements TransitionHandler, wrapping an Executor with retry and compensation logic.

func NewProcessingStep

func NewProcessingStep(name string, config ProcessingStepConfig) *ProcessingStep

NewProcessingStep creates a new ProcessingStep module.

func (*ProcessingStep) HandleTransition

func (ps *ProcessingStep) HandleTransition(ctx context.Context, event TransitionEvent) error

HandleTransition implements the TransitionHandler interface. It executes the wrapped dynamic component with retry and exponential backoff.

func (*ProcessingStep) Init

func (ps *ProcessingStep) Init(app modular.Application) error

Init resolves dependencies from the service registry. Note: service registration is handled by ProvidesServices() — the framework calls it after Init completes, so we don't register here.

func (*ProcessingStep) Name

func (ps *ProcessingStep) Name() string

Name returns the module name.

func (*ProcessingStep) ProvidesServices

func (ps *ProcessingStep) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the service provided by this module.

func (*ProcessingStep) RequiresServices

func (ps *ProcessingStep) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

func (*ProcessingStep) Start

func (ps *ProcessingStep) Start(_ context.Context) error

Start is a no-op for the processing step.

func (*ProcessingStep) Stop

func (ps *ProcessingStep) Stop(_ context.Context) error

Stop is a no-op for the processing step.

type ProcessingStepConfig

type ProcessingStepConfig struct {
	ComponentID          string // service name to look up in registry
	SuccessTransition    string // transition to fire on success
	CompensateTransition string // transition to fire on permanent failure
	MaxRetries           int    // default 2
	RetryBackoffMs       int    // base backoff in ms, default 1000
	TimeoutSeconds       int    // per-attempt timeout, default 30
}

ProcessingStepConfig holds configuration for a processing step module.

type PublishStep

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

PublishStep publishes data to an EventBus topic or a MessageBroker.

func (*PublishStep) Execute

func (s *PublishStep) Execute(ctx context.Context, pc *PipelineContext) (*StepResult, error)

Execute resolves the payload templates and publishes to the configured target.

func (*PublishStep) Name

func (s *PublishStep) Name() string

Name returns the step name.

type QueryFunc

type QueryFunc func(ctx context.Context, r *http.Request) (any, error)

QueryFunc is a read-only query function that returns data or an error.

type QueryHandler

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

QueryHandler dispatches GET requests to named query functions. Each query is registered by name and dispatched by extracting the last path segment from the request URL. Route pipelines can be attached for composable per-route processing. A delegate service can be configured to handle requests that don't match any registered query name.

func NewQueryHandler

func NewQueryHandler(name string) *QueryHandler

NewQueryHandler creates a new QueryHandler with the given name.

func (*QueryHandler) Handle

func (h *QueryHandler) Handle(w http.ResponseWriter, r *http.Request)

Handle dispatches an HTTP request to the appropriate query function.

func (*QueryHandler) Init

func (h *QueryHandler) Init(app modular.Application) error

Init initializes the query handler and resolves the delegate service.

func (*QueryHandler) Name

func (h *QueryHandler) Name() string

Name returns the unique identifier for this module.

func (*QueryHandler) ProvidesServices

func (h *QueryHandler) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns a list of services provided by this module.

func (*QueryHandler) RegisterQuery

func (h *QueryHandler) RegisterQuery(name string, fn QueryFunc)

RegisterQuery adds a named query function to the handler.

func (*QueryHandler) RequiresServices

func (h *QueryHandler) RequiresServices() []modular.ServiceDependency

RequiresServices returns a list of services required by this module.

func (*QueryHandler) ResolveDelegatePostStart

func (h *QueryHandler) ResolveDelegatePostStart()

ResolveDelegatePostStart is called after engine.Start to resolve delegates that may not have been available during Init (e.g., services registered by post-start hooks).

func (*QueryHandler) ServeHTTP

func (h *QueryHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface. It looks up a route pipeline by the full "METHOD /path" pattern (set by Go 1.22+ ServeMux), falling back to the last path segment for backward compatibility with registered queries. Dispatch chain: RegisteredQueryFunc -> RoutePipeline -> DelegateHandler -> 404

func (*QueryHandler) SetDelegate

func (h *QueryHandler) SetDelegate(name string)

SetDelegate sets the delegate service name. The service must implement http.Handler and will be resolved from the service registry during Init.

func (*QueryHandler) SetDelegateHandler

func (h *QueryHandler) SetDelegateHandler(handler http.Handler)

SetDelegateHandler directly sets the HTTP handler used for delegation.

func (*QueryHandler) SetExecutionTracker

func (h *QueryHandler) SetExecutionTracker(t *ExecutionTracker)

SetExecutionTracker sets the execution tracker for recording pipeline executions.

func (*QueryHandler) SetRoutePipeline

func (h *QueryHandler) SetRoutePipeline(routePath string, pipeline *Pipeline)

SetRoutePipeline attaches a pipeline to a specific route path.

type QueryResult

type QueryResult struct {
	Columns []string         `json:"columns"`
	Rows    []map[string]any `json:"rows"`
	Count   int              `json:"count"`
}

QueryResult represents the result of a query

type RESTAPIHandler

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

RESTAPIHandler provides CRUD operations for a REST API

func NewRESTAPIHandler

func NewRESTAPIHandler(name, resourceName string) *RESTAPIHandler

NewRESTAPIHandler creates a new REST API handler

func (*RESTAPIHandler) Constructor

func (h *RESTAPIHandler) Constructor() modular.ModuleConstructor

Constructor returns a function to construct this module with dependencies

func (*RESTAPIHandler) Handle

func (h *RESTAPIHandler) Handle(w http.ResponseWriter, r *http.Request)

Handle implements the HTTPHandler interface

func (*RESTAPIHandler) Init

func (h *RESTAPIHandler) Init(app modular.Application) error

Init initializes the module with the application context

func (*RESTAPIHandler) Name

func (h *RESTAPIHandler) Name() string

Name returns the unique identifier for this module

func (*RESTAPIHandler) ProvidesServices

func (h *RESTAPIHandler) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module

func (*RESTAPIHandler) RequiresServices

func (h *RESTAPIHandler) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module

func (*RESTAPIHandler) SetFieldMapping

func (h *RESTAPIHandler) SetFieldMapping(fm *FieldMapping)

SetFieldMapping sets a custom field mapping, merged on top of defaults.

func (*RESTAPIHandler) SetInitialTransition

func (h *RESTAPIHandler) SetInitialTransition(t string)

SetInitialTransition sets the first transition to trigger after creating a workflow instance.

func (*RESTAPIHandler) SetSeedFile

func (h *RESTAPIHandler) SetSeedFile(path string)

SetSeedFile sets the path to a JSON seed data file.

func (*RESTAPIHandler) SetSourceResourceName

func (h *RESTAPIHandler) SetSourceResourceName(name string)

SetSourceResourceName sets a different resource name for read operations (e.g., queue reads from conversations).

func (*RESTAPIHandler) SetStateFilter

func (h *RESTAPIHandler) SetStateFilter(state string)

SetStateFilter restricts GET responses to resources matching the given state.

func (*RESTAPIHandler) SetSummaryFields

func (h *RESTAPIHandler) SetSummaryFields(fields []string)

SetSummaryFields sets the list of fields to include in summary responses.

func (*RESTAPIHandler) SetTransitionMap

func (h *RESTAPIHandler) SetTransitionMap(tm map[string]string)

SetTransitionMap sets a custom sub-action to transition name mapping.

func (*RESTAPIHandler) SetWorkflowEngine

func (h *RESTAPIHandler) SetWorkflowEngine(we string)

SetWorkflowEngine sets the name of the workflow engine service to use.

func (*RESTAPIHandler) SetWorkflowType

func (h *RESTAPIHandler) SetWorkflowType(wt string)

SetWorkflowType sets the workflow type for state machine operations.

func (*RESTAPIHandler) Start

func (h *RESTAPIHandler) Start(ctx context.Context) error

Start loads persisted resources (if available) and seed data.

func (*RESTAPIHandler) Stop

func (h *RESTAPIHandler) Stop(ctx context.Context) error

Stop is a no-op for this handler

type RESTAPIHandlerConfig

type RESTAPIHandlerConfig struct {
	ResourceName     string `json:"resourceName" yaml:"resourceName"`
	PublishEvents    bool   `json:"publishEvents" yaml:"publishEvents"`
	WorkflowType     string `json:"workflowType" yaml:"workflowType"`         // The type of workflow to use for state machine operations
	WorkflowEngine   string `json:"workflowEngine" yaml:"workflowEngine"`     // The name of the workflow engine to use
	InstanceIDPrefix string `json:"instanceIDPrefix" yaml:"instanceIDPrefix"` // Optional prefix for workflow instance IDs
	InstanceIDField  string `json:"instanceIDField" yaml:"instanceIDField"`   // Field in resource data to use for instance ID (defaults to "id")
}

RESTAPIHandlerConfig contains configuration for a REST API handler

type RESTResource

type RESTResource struct {
	ID         string         `json:"id"`
	Data       map[string]any `json:"data"`
	State      string         `json:"state,omitempty"`
	LastUpdate string         `json:"lastUpdate,omitempty"`
}

RESTResource represents a simple in-memory resource store for REST APIs

type RateLimitMiddleware

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

RateLimitMiddleware implements a rate limiting middleware

func NewRateLimitMiddleware

func NewRateLimitMiddleware(name string, requestsPerMinute, burstSize int) *RateLimitMiddleware

NewRateLimitMiddleware creates a new rate limiting middleware with IP-based strategy.

func NewRateLimitMiddlewareWithStrategy

func NewRateLimitMiddlewareWithStrategy(name string, requestsPerMinute, burstSize int, strategy RateLimitStrategy) *RateLimitMiddleware

NewRateLimitMiddlewareWithStrategy creates a rate limiting middleware with a specific client identification strategy.

func (*RateLimitMiddleware) Init

Init initializes the middleware

func (*RateLimitMiddleware) Name

func (m *RateLimitMiddleware) Name() string

Name returns the module name

func (*RateLimitMiddleware) Process

func (m *RateLimitMiddleware) Process(next http.Handler) http.Handler

Process implements middleware processing

func (*RateLimitMiddleware) ProvidesServices

func (m *RateLimitMiddleware) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this middleware

func (*RateLimitMiddleware) RequiresServices

func (m *RateLimitMiddleware) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this middleware

func (*RateLimitMiddleware) SetTokenHeader

func (m *RateLimitMiddleware) SetTokenHeader(header string)

SetTokenHeader sets a custom header name for token-based rate limiting.

func (*RateLimitMiddleware) Start

Start begins the stale client cleanup goroutine.

func (*RateLimitMiddleware) Stop

Stop terminates the cleanup goroutine.

func (*RateLimitMiddleware) Strategy

func (m *RateLimitMiddleware) Strategy() RateLimitStrategy

Strategy returns the current rate limiting strategy.

type RateLimitStrategy

type RateLimitStrategy string

RateLimitStrategy controls how clients are identified for rate limiting.

const (
	// RateLimitByIP identifies clients by their IP address (default).
	RateLimitByIP RateLimitStrategy = "ip"
	// RateLimitByToken identifies clients by the Authorization header token.
	RateLimitByToken RateLimitStrategy = "token"
	// RateLimitByIPAndToken uses both IP and token for identification.
	RateLimitByIPAndToken RateLimitStrategy = "ip_and_token"
)

type RequestIDMiddleware

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

RequestIDMiddleware reads X-Request-ID header or generates a UUID, sets it on the context and response header.

func NewRequestIDMiddleware

func NewRequestIDMiddleware(name string) *RequestIDMiddleware

NewRequestIDMiddleware creates a new RequestIDMiddleware.

func (*RequestIDMiddleware) Init

Init registers the middleware as a service.

func (*RequestIDMiddleware) Middleware

func (m *RequestIDMiddleware) Middleware() func(http.Handler) http.Handler

Middleware returns the HTTP middleware function.

func (*RequestIDMiddleware) Name

func (m *RequestIDMiddleware) Name() string

Name returns the module name.

func (*RequestIDMiddleware) Process

func (m *RequestIDMiddleware) Process(next http.Handler) http.Handler

Process implements the HTTPMiddleware interface.

func (*RequestIDMiddleware) ProvidesServices

func (m *RequestIDMiddleware) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*RequestIDMiddleware) RequiresServices

func (m *RequestIDMiddleware) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

type RequestParseStep

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

RequestParseStep extracts path parameters, query parameters, and request body from the HTTP request stored in pipeline metadata.

func (*RequestParseStep) Execute

Execute extracts path parameters, query parameters, and/or request body from the HTTP request stored in pipeline context metadata.

func (*RequestParseStep) Name

func (s *RequestParseStep) Name() string

Name returns the step name.

type ResourceStateMapping

type ResourceStateMapping struct {
	ResourceType  string // Type of resource (e.g., "orders", "users")
	StateMachine  string // Name of the state machine
	InstanceIDKey string // Field in resource data that maps to state machine instance ID
}

ResourceStateMapping defines how a resource maps to a state machine

type Route

type Route struct {
	Method      string
	Path        string
	Handler     HTTPHandler
	Middlewares []HTTPMiddleware
}

Route represents an HTTP route

type RouteDefinition

type RouteDefinition struct {
	Method      string
	Path        string
	Handler     string
	Middlewares []string
	Summary     string
	Tags        []string
}

RouteDefinition is a simplified route for external spec building.

type S3Storage

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

S3Storage provides object storage operations using AWS S3. It implements the modular.Module interface.

func NewS3Storage

func NewS3Storage(name string) *S3Storage

NewS3Storage creates a new S3 storage module.

func (*S3Storage) DeleteObject

func (s *S3Storage) DeleteObject(ctx context.Context, key string) error

DeleteObject removes an object from S3.

func (*S3Storage) GetObject

func (s *S3Storage) GetObject(ctx context.Context, key string) (io.ReadCloser, error)

GetObject retrieves an object from S3.

func (*S3Storage) Init

func (s *S3Storage) Init(app modular.Application) error

Init initializes the module with the application context.

func (*S3Storage) Name

func (s *S3Storage) Name() string

Name returns the module name.

func (*S3Storage) ProvidesServices

func (s *S3Storage) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*S3Storage) PutObject

func (s *S3Storage) PutObject(ctx context.Context, key string, body io.Reader) error

PutObject uploads an object to S3.

func (*S3Storage) RequiresServices

func (s *S3Storage) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module.

func (*S3Storage) SetBucket

func (s *S3Storage) SetBucket(bucket string)

SetBucket sets the S3 bucket name.

func (*S3Storage) SetClient

func (s *S3Storage) SetClient(client *s3.Client)

SetClient sets a custom S3 client (useful for testing).

func (*S3Storage) SetEndpoint

func (s *S3Storage) SetEndpoint(endpoint string)

SetEndpoint sets a custom endpoint (for LocalStack/MinIO).

func (*S3Storage) SetRegion

func (s *S3Storage) SetRegion(region string)

SetRegion sets the AWS region.

func (*S3Storage) Start

func (s *S3Storage) Start(ctx context.Context) error

Start initializes the S3 client.

func (*S3Storage) Stop

func (s *S3Storage) Stop(_ context.Context) error

Stop is a no-op for S3 storage.

type SQLiteStorage

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

SQLiteStorage is a module that provides a SQLite database connection as a service. Other modules can depend on it for local SQL storage.

func NewSQLiteStorage

func NewSQLiteStorage(name, dbPath string) *SQLiteStorage

NewSQLiteStorage creates a new SQLite storage module.

func (*SQLiteStorage) DB

func (s *SQLiteStorage) DB() *sql.DB

DB returns the underlying *sql.DB connection.

func (*SQLiteStorage) Init

func (s *SQLiteStorage) Init(app modular.Application) error

func (*SQLiteStorage) Name

func (s *SQLiteStorage) Name() string

func (*SQLiteStorage) ProvidesServices

func (s *SQLiteStorage) ProvidesServices() []modular.ServiceProvider

func (*SQLiteStorage) RequiresServices

func (s *SQLiteStorage) RequiresServices() []modular.ServiceDependency

func (*SQLiteStorage) SetMaxConnections

func (s *SQLiteStorage) SetMaxConnections(n int)

SetMaxConnections sets the maximum number of database connections.

func (*SQLiteStorage) SetWALMode

func (s *SQLiteStorage) SetWALMode(enabled bool)

SetWALMode enables or disables WAL journal mode.

func (*SQLiteStorage) Start

func (s *SQLiteStorage) Start(_ context.Context) error

Start opens the SQLite database connection.

func (*SQLiteStorage) Stop

func (s *SQLiteStorage) Stop(_ context.Context) error

Stop closes the database connection.

type SSEEvent

type SSEEvent struct {
	ID    string `json:"id"`
	Event string `json:"event"` // "step.started", "step.completed", "step.failed", etc.
	Data  string `json:"data"`  // JSON-encoded event data
}

SSEEvent represents a Server-Sent Event for execution tracing.

type SSETracer

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

SSETracer provides Server-Sent Events for live execution tracing. Clients subscribe to a specific execution ID (or "*" for all executions) and receive real-time events as the workflow progresses.

func NewSSETracer

func NewSSETracer(logger *slog.Logger) *SSETracer

NewSSETracer creates a new SSETracer with the given logger.

func (*SSETracer) ActiveSubscribers

func (t *SSETracer) ActiveSubscribers() int

ActiveSubscribers returns the count of currently active subscriber connections.

func (*SSETracer) Handler

func (t *SSETracer) Handler() http.HandlerFunc

Handler returns an HTTP handler for SSE streaming at GET /api/v1/executions/{id}/stream.

The handler:

  • Sets SSE-appropriate headers (Content-Type, Cache-Control, Connection)
  • Extracts the execution ID from the URL path
  • Subscribes to events for that execution ID
  • Writes events in SSE format: "id: ...\nevent: ...\ndata: ...\n\n"
  • Cleans up on client disconnect (context cancellation)

func (*SSETracer) Publish

func (t *SSETracer) Publish(executionID string, event SSEEvent)

Publish sends an event to all subscribers matching the given execution ID. Events are delivered to:

  • subscribers registered for the specific executionID
  • subscribers registered with the wildcard "*"

If a subscriber's channel is full, the event is dropped for that subscriber (non-blocking send to prevent slow consumers from stalling the publisher).

func (*SSETracer) Subscribe

func (t *SSETracer) Subscribe(executionID string) (<-chan SSEEvent, func())

Subscribe registers a new subscriber for the given execution ID. Use "*" as executionID to receive events for all executions. Returns a read-only channel of events and an unsubscribe function. The caller must invoke the unsubscribe function when done to prevent leaks.

type ScanContainerStep

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

ScanContainerStep runs a container vulnerability scanner (e.g., Trivy) against a target image and evaluates findings against a severity gate.

func (*ScanContainerStep) Execute

Execute runs the container scanner and returns findings as a ScanResult.

func (*ScanContainerStep) Name

func (s *ScanContainerStep) Name() string

Name returns the step name.

type ScanDepsStep

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

ScanDepsStep runs a dependency vulnerability scanner (e.g., Grype) against a source path and evaluates findings against a severity gate.

func (*ScanDepsStep) Execute

Execute runs the dependency scanner and returns findings as a ScanResult.

func (*ScanDepsStep) Name

func (s *ScanDepsStep) Name() string

Name returns the step name.

type ScanResult

type ScanResult struct {
	Scanner    string      `json:"scanner"`
	Findings   []Finding   `json:"findings"`
	Summary    ScanSummary `json:"summary"`
	PassedGate bool        `json:"passed_gate"`
}

ScanResult holds the output of a security scanner.

func NewScanResult

func NewScanResult(scanner string) *ScanResult

NewScanResult creates a ScanResult for the given scanner name.

func (*ScanResult) AddFinding

func (sr *ScanResult) AddFinding(f Finding)

AddFinding appends a finding to the scan result.

func (*ScanResult) ComputeSummary

func (sr *ScanResult) ComputeSummary()

ComputeSummary tallies findings by severity level.

func (*ScanResult) EvaluateGate

func (sr *ScanResult) EvaluateGate(threshold string) bool

EvaluateGate checks whether the scan passes a severity gate. The gate passes if no findings are at or above the given threshold severity. For example, threshold "high" means the gate fails if any critical or high findings exist.

type ScanSASTStep

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

ScanSASTStep runs a SAST (Static Application Security Testing) scanner inside a Docker container and evaluates findings against a severity gate.

func (*ScanSASTStep) Execute

Execute runs the SAST scanner and returns findings as a ScanResult.

func (*ScanSASTStep) Name

func (s *ScanSASTStep) Name() string

Name returns the step name.

type ScanSummary

type ScanSummary struct {
	Critical int `json:"critical"`
	High     int `json:"high"`
	Medium   int `json:"medium"`
	Low      int `json:"low"`
	Info     int `json:"info"`
}

ScanSummary counts findings by severity level.

type ScheduleTrigger

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

ScheduleTrigger implements a trigger that starts workflows based on a schedule

func NewScheduleTrigger

func NewScheduleTrigger() *ScheduleTrigger

NewScheduleTrigger creates a new schedule trigger

func NewScheduleTriggerWithNamespace

func NewScheduleTriggerWithNamespace(namespace ModuleNamespaceProvider) *ScheduleTrigger

NewScheduleTriggerWithNamespace creates a new schedule trigger with namespace support

func (*ScheduleTrigger) Configure

func (t *ScheduleTrigger) Configure(app modular.Application, triggerConfig any) error

Configure sets up the trigger from configuration

func (*ScheduleTrigger) Init

Init initializes the trigger

func (*ScheduleTrigger) Name

func (t *ScheduleTrigger) Name() string

Name returns the name of this trigger

func (*ScheduleTrigger) Start

func (t *ScheduleTrigger) Start(ctx context.Context) error

Start starts the trigger

func (*ScheduleTrigger) Stop

func (t *ScheduleTrigger) Stop(ctx context.Context) error

Stop stops the trigger

type ScheduleTriggerConfig

type ScheduleTriggerConfig struct {
	Jobs []ScheduleTriggerJob `json:"jobs" yaml:"jobs"`
}

ScheduleTriggerConfig represents the configuration for a schedule trigger

type ScheduleTriggerJob

type ScheduleTriggerJob struct {
	Cron     string         `json:"cron" yaml:"cron"`
	Workflow string         `json:"workflow" yaml:"workflow"`
	Action   string         `json:"action" yaml:"action"`
	Params   map[string]any `json:"params,omitempty" yaml:"params,omitempty"`
}

ScheduleTriggerJob represents a single scheduled job configuration

type ScheduledJobInfo

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

ScheduledJobInfo captures information about a scheduled job

type ScheduledWindow

type ScheduledWindow struct {
	Weekdays  []time.Weekday
	StartHour int
	EndHour   int
}

ScheduledWindow defines a time window during which a scheduled gate passes.

type Scheduler

type Scheduler interface {
	Schedule(job Job) error
	Start(ctx context.Context) error
	Stop(ctx context.Context) error
}

Scheduler represents a job scheduler

type SecretsAWSModule

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

SecretsAWSModule provides an AWS Secrets Manager secret provider as a modular service.

func NewSecretsAWSModule

func NewSecretsAWSModule(name string) *SecretsAWSModule

NewSecretsAWSModule creates a new AWS Secrets Manager module.

func (*SecretsAWSModule) Get

func (m *SecretsAWSModule) Get(ctx context.Context, key string) (string, error)

Get retrieves a secret from AWS Secrets Manager.

func (*SecretsAWSModule) Init

func (*SecretsAWSModule) Name

func (m *SecretsAWSModule) Name() string

func (*SecretsAWSModule) Provider

func (m *SecretsAWSModule) Provider() secrets.Provider

Provider returns the underlying secrets.Provider.

func (*SecretsAWSModule) ProvidesServices

func (m *SecretsAWSModule) ProvidesServices() []modular.ServiceProvider

func (*SecretsAWSModule) RequiresServices

func (m *SecretsAWSModule) RequiresServices() []modular.ServiceDependency

func (*SecretsAWSModule) SetAccessKeyID

func (m *SecretsAWSModule) SetAccessKeyID(id string)

SetAccessKeyID sets the AWS access key ID.

func (*SecretsAWSModule) SetRegion

func (m *SecretsAWSModule) SetRegion(region string)

SetRegion sets the AWS region.

func (*SecretsAWSModule) SetSecretAccessKey

func (m *SecretsAWSModule) SetSecretAccessKey(key string)

SetSecretAccessKey sets the AWS secret access key.

func (*SecretsAWSModule) Start

func (m *SecretsAWSModule) Start(_ context.Context) error

Start initializes the AWS Secrets Manager provider.

func (*SecretsAWSModule) Stop

Stop is a no-op.

type SecretsVaultModule

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

SecretsVaultModule provides a HashiCorp Vault secret provider as a modular service.

func NewSecretsVaultModule

func NewSecretsVaultModule(name string) *SecretsVaultModule

NewSecretsVaultModule creates a new Vault secrets module.

func (*SecretsVaultModule) Get

func (m *SecretsVaultModule) Get(ctx context.Context, key string) (string, error)

Get retrieves a secret from Vault.

func (*SecretsVaultModule) Init

func (*SecretsVaultModule) Name

func (m *SecretsVaultModule) Name() string

func (*SecretsVaultModule) Provider

func (m *SecretsVaultModule) Provider() secrets.Provider

Provider returns the underlying secrets.Provider.

func (*SecretsVaultModule) ProvidesServices

func (m *SecretsVaultModule) ProvidesServices() []modular.ServiceProvider

func (*SecretsVaultModule) RequiresServices

func (m *SecretsVaultModule) RequiresServices() []modular.ServiceDependency

func (*SecretsVaultModule) SetAddress

func (m *SecretsVaultModule) SetAddress(addr string)

SetAddress sets the Vault server address.

func (*SecretsVaultModule) SetMountPath

func (m *SecretsVaultModule) SetMountPath(path string)

SetMountPath sets the KV v2 mount path.

func (*SecretsVaultModule) SetNamespace

func (m *SecretsVaultModule) SetNamespace(ns string)

SetNamespace sets the Vault namespace.

func (*SecretsVaultModule) SetToken

func (m *SecretsVaultModule) SetToken(token string)

SetToken sets the Vault authentication token.

func (*SecretsVaultModule) Start

Start initializes the Vault provider.

func (*SecretsVaultModule) Stop

Stop is a no-op.

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	ContentSecurityPolicy string `` /* 149-byte string literal not displayed */
	FrameOptions          string `yaml:"frameOptions" default:"DENY"`
	ContentTypeOptions    string `yaml:"contentTypeOptions" default:"nosniff"`
	HSTSMaxAge            int    `yaml:"hstsMaxAge" default:"31536000"`
	ReferrerPolicy        string `yaml:"referrerPolicy" default:"strict-origin-when-cross-origin"`
	PermissionsPolicy     string `yaml:"permissionsPolicy" default:"camera=(), microphone=(), geolocation=()"`
}

SecurityHeadersConfig holds configuration for the security headers middleware.

type SecurityHeadersMiddleware

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

SecurityHeadersMiddleware adds standard security headers to HTTP responses.

func NewSecurityHeadersMiddleware

func NewSecurityHeadersMiddleware(name string, cfg SecurityHeadersConfig) *SecurityHeadersMiddleware

NewSecurityHeadersMiddleware creates a new SecurityHeadersMiddleware.

func (*SecurityHeadersMiddleware) Init

Init registers the middleware as a service.

func (*SecurityHeadersMiddleware) Middleware

func (m *SecurityHeadersMiddleware) Middleware() func(http.Handler) http.Handler

Middleware returns the HTTP middleware function.

func (*SecurityHeadersMiddleware) Name

Name returns the module name.

func (*SecurityHeadersMiddleware) Process

Process implements the HTTPMiddleware interface.

func (*SecurityHeadersMiddleware) ProvidesServices

func (m *SecurityHeadersMiddleware) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*SecurityHeadersMiddleware) RequiresServices

func (m *SecurityHeadersMiddleware) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module.

type ServiceInfo

type ServiceInfo struct {
	Name       string   `json:"name"`
	Type       string   `json:"type"`
	Implements []string `json:"implements"`
}

ServiceInfo describes a registered service for API responses.

type ServiceModule

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

ServiceModule wraps any Go object as a modular.Module, registering it in the service registry under the given name. This allows delegate-based dispatch: a QueryHandler or CommandHandler can name a delegate service, and that service (if it implements http.Handler) handles the actual HTTP dispatch.

func NewServiceModule

func NewServiceModule(name string, svc any) *ServiceModule

NewServiceModule creates a ServiceModule that registers svc under name.

func (*ServiceModule) Init

func (*ServiceModule) Name

func (m *ServiceModule) Name() string

func (*ServiceModule) ProvidesServices

func (m *ServiceModule) ProvidesServices() []modular.ServiceProvider

func (*ServiceModule) RequiresServices

func (m *ServiceModule) RequiresServices() []modular.ServiceDependency

type ServiceRegistry

type ServiceRegistry interface {
	// GetService returns a service by name
	GetService(name string, out any) error

	// RegisterService registers a service with the application
	RegisterService(name string, service any) error
}

ServiceRegistry defines the interface for registering and retrieving services

type SetStep

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

SetStep sets template-resolved values in the pipeline context.

func (*SetStep) Execute

func (s *SetStep) Execute(_ context.Context, pc *PipelineContext) (*StepResult, error)

Execute resolves template expressions in the configured values and returns them as the step output.

func (*SetStep) Name

func (s *SetStep) Name() string

Name returns the step name.

type ShellExecStep

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

ShellExecStep executes shell commands inside a Docker container, optionally collecting output artifacts.

func (*ShellExecStep) Execute

func (s *ShellExecStep) Execute(ctx context.Context, pc *PipelineContext) (*StepResult, error)

Execute runs each command in a Docker sandbox and collects artifacts.

func (*ShellExecStep) Name

func (s *ShellExecStep) Name() string

Name returns the step name.

type SimpleHTTPHandler

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

SimpleHTTPHandler provides a basic implementation of an HTTP handler

func NewSimpleHTTPHandler

func NewSimpleHTTPHandler(name string, contentType string) *SimpleHTTPHandler

NewSimpleHTTPHandler creates a new HTTP handler with the given name

func (*SimpleHTTPHandler) Handle

Handle implements the HTTPHandler interface

func (*SimpleHTTPHandler) Init

Init initializes the HTTP handler

func (*SimpleHTTPHandler) Name

func (h *SimpleHTTPHandler) Name() string

Name returns the unique identifier for this module

func (*SimpleHTTPHandler) ProvidesServices

func (h *SimpleHTTPHandler) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns a list of services provided by this module

func (*SimpleHTTPHandler) RequiresServices

func (h *SimpleHTTPHandler) RequiresServices() []modular.ServiceDependency

RequiresServices returns a list of services required by this module

func (*SimpleHTTPHandler) ServeHTTP

func (h *SimpleHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface

func (*SimpleHTTPHandler) SetHandleFunc

func (h *SimpleHTTPHandler) SetHandleFunc(fn func(w http.ResponseWriter, r *http.Request))

SetHandleFunc sets a custom handler function

type SimpleMessageHandler

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

SimpleMessageHandler provides a basic implementation of a message handler

func NewSimpleMessageHandler

func NewSimpleMessageHandler(name string) *SimpleMessageHandler

NewSimpleMessageHandler creates a new message handler with the given name

func NewSimpleMessageHandlerWithNamespace

func NewSimpleMessageHandlerWithNamespace(name string, namespace ModuleNamespaceProvider) *SimpleMessageHandler

NewSimpleMessageHandlerWithNamespace creates a new message handler with namespace support

func NewStandardSimpleMessageHandler

func NewStandardSimpleMessageHandler(handlerType string, namespace ModuleNamespaceProvider) *SimpleMessageHandler

NewStandardSimpleMessageHandler creates a message handler with standard name

func (*SimpleMessageHandler) Constructor

Constructor returns a function to construct this module with dependencies

func (*SimpleMessageHandler) Dependencies

func (h *SimpleMessageHandler) Dependencies() []string

Dependencies returns the names of other modules this module depends on

func (*SimpleMessageHandler) HandleMessage

func (h *SimpleMessageHandler) HandleMessage(message []byte) error

HandleMessage implements the MessageHandler interface

func (*SimpleMessageHandler) Init

Init initializes the module with the application context

func (*SimpleMessageHandler) Name

func (h *SimpleMessageHandler) Name() string

Name returns the unique identifier for this module

func (*SimpleMessageHandler) ProvidesServices

func (h *SimpleMessageHandler) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns a list of services provided by this module

func (*SimpleMessageHandler) RequiresServices

func (h *SimpleMessageHandler) RequiresServices() []modular.ServiceDependency

RequiresServices returns a list of services required by this module

func (*SimpleMessageHandler) SetBrokerDependencies

func (h *SimpleMessageHandler) SetBrokerDependencies(brokerNames []string)

SetBrokerDependencies sets which message broker modules this handler depends on

func (*SimpleMessageHandler) SetHandleFunc

func (h *SimpleMessageHandler) SetHandleFunc(fn func(message []byte) error)

SetHandleFunc sets a custom handler function

func (*SimpleMessageHandler) SetProducer

func (h *SimpleMessageHandler) SetProducer(producer MessageProducer)

SetProducer sets the message producer for forwarding

func (*SimpleMessageHandler) SetTargetTopics

func (h *SimpleMessageHandler) SetTargetTopics(topics []string)

SetTargetTopics configures topics to forward messages to

func (*SimpleMessageHandler) Start

func (h *SimpleMessageHandler) Start(ctx context.Context) error

Start is a no-op for handler (implements Startable interface)

func (*SimpleMessageHandler) Stop

Stop is a no-op for handler (implements Stoppable interface)

type SimpleProxy

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

SimpleProxy is a lightweight reverse proxy module that forwards requests to backend services based on path prefix matching.

func NewSimpleProxy

func NewSimpleProxy(name string) *SimpleProxy

NewSimpleProxy creates a new simple reverse proxy module.

func (*SimpleProxy) Handle

func (p *SimpleProxy) Handle(w http.ResponseWriter, r *http.Request)

Handle proxies the request to the appropriate backend based on path prefix.

func (*SimpleProxy) Init

func (p *SimpleProxy) Init(_ modular.Application) error

Init initializes the module.

func (*SimpleProxy) Name

func (p *SimpleProxy) Name() string

Name returns the module name.

func (*SimpleProxy) ProvidesServices

func (p *SimpleProxy) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*SimpleProxy) RequiresServices

func (p *SimpleProxy) RequiresServices() []modular.ServiceDependency

RequiresServices returns no dependencies.

func (*SimpleProxy) SetTargets

func (p *SimpleProxy) SetTargets(targets map[string]string) error

SetTargets configures the proxy targets from a map of path prefix -> backend URL strings.

func (*SimpleProxy) Start

func (p *SimpleProxy) Start(_ context.Context) error

Start is a no-op.

func (*SimpleProxy) Stop

func (p *SimpleProxy) Stop(_ context.Context) error

Stop is a no-op.

type SimpleTokenProvider

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

SimpleTokenProvider implements a simple token-based auth provider

func (*SimpleTokenProvider) Authenticate

func (p *SimpleTokenProvider) Authenticate(token string) (bool, map[string]any, error)

Authenticate checks if the token is valid and returns associated claims

type SlackNotification

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

SlackNotification sends messages to a Slack webhook URL. It implements both the MessageHandler and modular.Module interfaces.

func NewSlackNotification

func NewSlackNotification(name string) *SlackNotification

NewSlackNotification creates a new Slack notification module.

func (*SlackNotification) HandleMessage

func (s *SlackNotification) HandleMessage(message []byte) error

HandleMessage sends a message to the configured Slack webhook.

func (*SlackNotification) Init

Init initializes the module with the application context.

func (*SlackNotification) Name

func (s *SlackNotification) Name() string

Name returns the module name.

func (*SlackNotification) ProvidesServices

func (s *SlackNotification) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module.

func (*SlackNotification) RequiresServices

func (s *SlackNotification) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module.

func (*SlackNotification) SetChannel

func (s *SlackNotification) SetChannel(channel string)

SetChannel sets the Slack channel.

func (*SlackNotification) SetClient

func (s *SlackNotification) SetClient(client *http.Client)

SetClient sets a custom HTTP client (useful for testing).

func (*SlackNotification) SetUsername

func (s *SlackNotification) SetUsername(username string)

SetUsername sets the Slack username.

func (*SlackNotification) SetWebhookURL

func (s *SlackNotification) SetWebhookURL(url string)

SetWebhookURL sets the Slack webhook URL.

type StandardHTTPHandler

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

StandardHTTPHandler adapts a function to the HTTPHandler interface

func (*StandardHTTPHandler) Handle

Handle implements the HTTPHandler interface

func (*StandardHTTPHandler) ServeHTTP

func (h *StandardHTTPHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, params map[string]string)

ServeHTTP implements the http.Handler interface (for compatibility)

type StandardHTTPRouter

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

StandardHTTPRouter implements both HTTPRouter and http.Handler interfaces

func NewStandardHTTPRouter

func NewStandardHTTPRouter(name string) *StandardHTTPRouter

NewStandardHTTPRouter creates a new HTTP router

func (*StandardHTTPRouter) AddRoute

func (r *StandardHTTPRouter) AddRoute(method, path string, handler HTTPHandler)

AddRoute adds a route to the router

func (*StandardHTTPRouter) AddRouteWithMiddleware

func (r *StandardHTTPRouter) AddRouteWithMiddleware(method, path string, handler HTTPHandler, middlewares []HTTPMiddleware)

AddRouteWithMiddleware adds a route with middleware to the router

func (*StandardHTTPRouter) Constructor

func (r *StandardHTTPRouter) Constructor() modular.ModuleConstructor

Constructor returns a function to construct this module with dependencies

func (*StandardHTTPRouter) Dependencies

func (r *StandardHTTPRouter) Dependencies() []string

Dependencies returns names of other modules this module depends on

func (*StandardHTTPRouter) HasRoute

func (r *StandardHTTPRouter) HasRoute(method, path string) bool

HasRoute checks if a route with the given method and path already exists

func (*StandardHTTPRouter) Init

Init initializes the module with the application context

func (*StandardHTTPRouter) Name

func (r *StandardHTTPRouter) Name() string

Name returns the unique identifier for this module

func (*StandardHTTPRouter) ProvidesServices

func (r *StandardHTTPRouter) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns a list of services provided by this module

func (*StandardHTTPRouter) RequiresServices

func (r *StandardHTTPRouter) RequiresServices() []modular.ServiceDependency

RequiresServices returns a list of services required by this module

func (*StandardHTTPRouter) ServeHTTP

func (r *StandardHTTPRouter) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface

func (*StandardHTTPRouter) SetServerDependencies

func (r *StandardHTTPRouter) SetServerDependencies(serverNames []string)

SetServerDependencies sets which HTTP server modules this router depends on

func (*StandardHTTPRouter) Start

func (r *StandardHTTPRouter) Start(ctx context.Context) error

Start is a no-op for router (implements Startable interface)

func (*StandardHTTPRouter) Stop

func (r *StandardHTTPRouter) Stop(ctx context.Context) error

Stop is a no-op for router (implements Stoppable interface)

type StandardHTTPServer

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

StandardHTTPServer implements the HTTPServer interface and modular.Module interfaces

func NewStandardHTTPServer

func NewStandardHTTPServer(name, address string) *StandardHTTPServer

NewStandardHTTPServer creates a new HTTP server with the given name and address

func (*StandardHTTPServer) AddRouter

func (s *StandardHTTPServer) AddRouter(router HTTPRouter)

AddRouter adds a router to the HTTP server

func (*StandardHTTPServer) Init

Init initializes the module with the application context

func (*StandardHTTPServer) Name

func (s *StandardHTTPServer) Name() string

Name returns the unique identifier for this module

func (*StandardHTTPServer) ProvidesServices

func (s *StandardHTTPServer) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns a list of services provided by this module

func (*StandardHTTPServer) RequiresServices

func (s *StandardHTTPServer) RequiresServices() []modular.ServiceDependency

RequiresServices returns a list of services required by this module

func (*StandardHTTPServer) Start

func (s *StandardHTTPServer) Start(ctx context.Context) error

Start starts the HTTP server

func (*StandardHTTPServer) Stop

func (s *StandardHTTPServer) Stop(ctx context.Context) error

Stop stops the HTTP server

type StandardNamespace

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

StandardNamespace provides a standard implementation of ModuleNamespaceProvider

func NewStandardNamespace

func NewStandardNamespace(prefix string, suffix string) *StandardNamespace

NewStandardNamespace creates a new standard namespace with optional prefix and suffix

func (*StandardNamespace) FormatName

func (ns *StandardNamespace) FormatName(baseName string) string

FormatName formats a module name with the namespace prefix/suffix

func (*StandardNamespace) ResolveDependency

func (ns *StandardNamespace) ResolveDependency(dependencyName string) string

ResolveDependency formats a dependency name with the namespace prefix/suffix

func (*StandardNamespace) ResolveServiceName

func (ns *StandardNamespace) ResolveServiceName(serviceName string) string

ResolveServiceName formats a service name with the namespace prefix/suffix

func (*StandardNamespace) ValidateModuleName

func (ns *StandardNamespace) ValidateModuleName(moduleName string) error

ValidateModuleName checks if a module name conforms to namespace requirements

type State

type State struct {
	Name        string         `json:"name" yaml:"name"`
	Description string         `json:"description,omitempty" yaml:"description,omitempty"`
	Data        map[string]any `json:"data,omitempty" yaml:"data,omitempty"`
	IsFinal     bool           `json:"isFinal" yaml:"isFinal"`
	IsError     bool           `json:"isError" yaml:"isError"`
}

State represents a workflow state

type StateChangeListener

type StateChangeListener func(previousState, newState string, resourceID string, data map[string]any)

StateChangeListener is a function that gets called when state changes

type StateInfo

type StateInfo struct {
	ID            string         `json:"id"`
	ResourceType  string         `json:"resourceType"`
	CurrentState  string         `json:"currentState"`
	PreviousState string         `json:"previousState,omitempty"`
	LastUpdate    time.Time      `json:"lastUpdate"`
	Data          map[string]any `json:"data,omitempty"`
}

StateInfo represents state information for a resource

type StateMachineDefinition

type StateMachineDefinition struct {
	Name         string                 `json:"name" yaml:"name"`
	Description  string                 `json:"description,omitempty" yaml:"description,omitempty"`
	States       map[string]*State      `json:"states" yaml:"states"`
	Transitions  map[string]*Transition `json:"transitions" yaml:"transitions"`
	InitialState string                 `json:"initialState" yaml:"initialState"`
	Data         map[string]any         `json:"data,omitempty" yaml:"data,omitempty"`
}

StateMachineDefinition defines a state machine workflow

type StateMachineEngine

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

StateMachineEngine implements a workflow state machine engine

func NewStandardStateMachineEngine

func NewStandardStateMachineEngine(namespace ModuleNamespaceProvider) *StateMachineEngine

NewStandardStateMachineEngine creates a state machine engine with the standard name

func NewStateMachineEngine

func NewStateMachineEngine(name string) *StateMachineEngine

NewStateMachineEngine creates a new state machine engine

func NewStateMachineEngineWithNamespace

func NewStateMachineEngineWithNamespace(name string, namespace ModuleNamespaceProvider) *StateMachineEngine

NewStateMachineEngineWithNamespace creates a new state machine engine with namespace support

func (*StateMachineEngine) AddGlobalTransitionHandler

func (e *StateMachineEngine) AddGlobalTransitionHandler(handler TransitionHandler)

AddGlobalTransitionHandler adds a handler for all transitions

func (*StateMachineEngine) AddTransitionListener

func (e *StateMachineEngine) AddTransitionListener(listener TransitionListener)

AddTransitionListener registers a function to be called on every transition

func (*StateMachineEngine) CreateWorkflow

func (e *StateMachineEngine) CreateWorkflow(
	workflowType string,
	id string,
	initialData map[string]any,
) (*WorkflowInstance, error)

CreateWorkflow creates a new workflow instance

func (*StateMachineEngine) GetAllInstances

func (e *StateMachineEngine) GetAllInstances() ([]*WorkflowInstance, error)

GetAllInstances returns all workflow instances

func (*StateMachineEngine) GetInstance

func (e *StateMachineEngine) GetInstance(id string) (*WorkflowInstance, error)

GetInstance retrieves a workflow instance by ID

func (*StateMachineEngine) GetInstancesByType

func (e *StateMachineEngine) GetInstancesByType(workflowType string) ([]*WorkflowInstance, error)

GetInstancesByType retrieves workflow instances by type

func (*StateMachineEngine) GetOrphanedInstances

func (e *StateMachineEngine) GetOrphanedInstances() []*WorkflowInstance

GetOrphanedInstances returns workflow instances whose current state does not exist in the corresponding state machine definition. This helps operators discover instances affected by configuration drift.

func (*StateMachineEngine) GetTransitionHandler

func (e *StateMachineEngine) GetTransitionHandler() TransitionHandler

GetTransitionHandler returns the current transition handler

func (*StateMachineEngine) HasTransitionHandler

func (e *StateMachineEngine) HasTransitionHandler() bool

HasTransitionHandler checks if a transition handler is set

func (*StateMachineEngine) Init

Init initializes the state machine engine

func (*StateMachineEngine) InstanceTTL

func (e *StateMachineEngine) InstanceTTL() time.Duration

InstanceTTL returns the configured TTL for idle instances.

func (*StateMachineEngine) LoadAllPersistedInstances

func (e *StateMachineEngine) LoadAllPersistedInstances() error

LoadAllPersistedInstances loads workflow instances from persistence for all registered definition types and populates the in-memory maps. Instances that already exist in memory are skipped.

func (*StateMachineEngine) MaxInstances

func (e *StateMachineEngine) MaxInstances() int

MaxInstances returns the configured maximum number of concurrent instances.

func (*StateMachineEngine) Name

func (e *StateMachineEngine) Name() string

Name returns the module name

func (*StateMachineEngine) ProvidesServices

func (e *StateMachineEngine) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns services provided by this module

func (*StateMachineEngine) RecoverProcessingInstances

func (e *StateMachineEngine) RecoverProcessingInstances(ctx context.Context, processingStates []string) int

RecoverProcessingInstances finds instances stuck in intermediate processing states and re-triggers their transitions so processing can resume after a restart. It resets each stuck instance back to PreviousState and re-fires the transition that originally moved it into the processing state.

func (*StateMachineEngine) RegisterDefinition

func (e *StateMachineEngine) RegisterDefinition(def *StateMachineDefinition) error

RegisterDefinition registers a state machine definition

func (*StateMachineEngine) RegisterWorkflow

func (e *StateMachineEngine) RegisterWorkflow(def ExternalStateMachineDefinition) error

RegisterWorkflow registers a workflow definition

func (*StateMachineEngine) RequiresServices

func (e *StateMachineEngine) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module

func (*StateMachineEngine) SetInstanceTTL

func (e *StateMachineEngine) SetInstanceTTL(d time.Duration)

SetInstanceTTL sets the TTL for idle workflow instances.

func (*StateMachineEngine) SetMaxInstances

func (e *StateMachineEngine) SetMaxInstances(n int)

SetMaxInstances sets the maximum number of concurrent workflow instances.

func (*StateMachineEngine) SetPersistence

func (e *StateMachineEngine) SetPersistence(ps *PersistenceStore)

SetPersistence sets the optional write-through persistence backend.

func (*StateMachineEngine) SetTransitionHandler

func (e *StateMachineEngine) SetTransitionHandler(handler TransitionHandler)

SetTransitionHandler sets the handler for all state transitions

func (*StateMachineEngine) Start

func (e *StateMachineEngine) Start(ctx context.Context) error

Start starts the state machine engine

func (*StateMachineEngine) Stop

func (e *StateMachineEngine) Stop(ctx context.Context) error

Stop stops the state machine engine. It waits for in-flight goroutines to finish (or context to expire) and flushes all instances to persistence.

func (*StateMachineEngine) TrackGoroutine

func (e *StateMachineEngine) TrackGoroutine(fn func())

TrackGoroutine spawns a goroutine tracked by the engine's WaitGroup so that Stop() can drain in-flight work before shutdown.

func (*StateMachineEngine) TriggerTransition

func (e *StateMachineEngine) TriggerTransition(
	ctx context.Context,
	workflowID string,
	transitionName string,
	data map[string]any,
) error

TriggerTransition attempts to transition a workflow's state

type StateMachineStateConfig

type StateMachineStateConfig struct {
	ID          string         `json:"id" yaml:"id"`
	Description string         `json:"description,omitempty" yaml:"description,omitempty"`
	IsFinal     bool           `json:"isFinal" yaml:"isFinal"`
	IsError     bool           `json:"isError" yaml:"isError"`
	Data        map[string]any `json:"data,omitempty" yaml:"data,omitempty"`
}

StateMachineStateConfig represents configuration for a state machine state

type StateMachineStateConnector

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

StateMachineStateConnector connects state machines to state tracking

func NewStateMachineStateConnector

func NewStateMachineStateConnector(name string) *StateMachineStateConnector

NewStateMachineStateConnector creates a new connector

func (*StateMachineStateConnector) Configure

func (c *StateMachineStateConnector) Configure(mappings []ResourceStateMapping) error

Configure sets up the connector with resource mappings

func (*StateMachineStateConnector) GetEngineForResourceType

func (c *StateMachineStateConnector) GetEngineForResourceType(resourceType string) (string, bool)

GetEngineForResourceType finds the state machine engine for a resource type

func (*StateMachineStateConnector) GetResourceState

func (c *StateMachineStateConnector) GetResourceState(resourceType, resourceID string) (string, map[string]any, error)

GetResourceState gets the current state for a resource

func (*StateMachineStateConnector) Init

Init initializes the connector

func (*StateMachineStateConnector) Name

Name returns the service name

func (*StateMachineStateConnector) ProvidesServices

func (c *StateMachineStateConnector) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module

func (*StateMachineStateConnector) RegisterMapping

func (c *StateMachineStateConnector) RegisterMapping(resourceType, stateMachine, instanceIDKey string)

RegisterMapping adds a resource mapping

func (*StateMachineStateConnector) RequiresServices

func (c *StateMachineStateConnector) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module

func (*StateMachineStateConnector) Start

Start connects to state machines and sets up listeners

func (*StateMachineStateConnector) Stop

Stop stops the connector

func (*StateMachineStateConnector) UpdateResourceState

func (c *StateMachineStateConnector) UpdateResourceState(resourceType, resourceID string) error

UpdateResourceState gets the current state from the state machine and updates the tracker

type StateMachineTransitionConfig

type StateMachineTransitionConfig struct {
	ID            string         `json:"id" yaml:"id"`
	FromState     string         `json:"fromState" yaml:"fromState"`
	ToState       string         `json:"toState" yaml:"toState"`
	Condition     string         `json:"condition,omitempty" yaml:"condition,omitempty"`
	AutoTransform bool           `json:"autoTransform" yaml:"autoTransform"`
	Data          map[string]any `json:"data,omitempty" yaml:"data,omitempty"`
}

StateMachineTransitionConfig represents configuration for a state transition

type StateTracker

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

StateTracker provides a generic service for tracking state

func NewStateTracker

func NewStateTracker(name string) *StateTracker

NewStateTracker creates a new state tracker service

func (*StateTracker) AddStateChangeListener

func (s *StateTracker) AddStateChangeListener(resourceType string, listener StateChangeListener)

AddStateChangeListener adds a listener for state changes of a specific resource type

func (*StateTracker) GetState

func (s *StateTracker) GetState(resourceType, resourceID string) (StateInfo, bool)

GetState retrieves state information for a resource

func (*StateTracker) Init

func (s *StateTracker) Init(app modular.Application) error

Init initializes the service

func (*StateTracker) Name

func (s *StateTracker) Name() string

Name returns the service name

func (*StateTracker) ProvidesServices

func (s *StateTracker) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module

func (*StateTracker) RequiresServices

func (s *StateTracker) RequiresServices() []modular.ServiceDependency

RequiresServices returns the services required by this module

func (*StateTracker) RetentionDays

func (s *StateTracker) RetentionDays() int

RetentionDays returns the configured retention period in days.

func (*StateTracker) SetRetentionDays

func (s *StateTracker) SetRetentionDays(days int)

SetRetentionDays sets the state history retention in days.

func (*StateTracker) SetState

func (s *StateTracker) SetState(resourceType, resourceID, state string, data map[string]any)

SetState updates the state for a resource

func (*StateTracker) Start

func (s *StateTracker) Start(ctx context.Context) error

Start starts the service

func (*StateTracker) Stop

func (s *StateTracker) Stop(ctx context.Context) error

Stop stops the service

type StaticFileServer

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

StaticFileServer serves static files from a directory with optional SPA fallback

func NewStaticFileServer

func NewStaticFileServer(name, root, prefix string, spaFallback bool, cacheMaxAge int) *StaticFileServer

NewStaticFileServer creates a new static file server module

func (*StaticFileServer) Handle

func (s *StaticFileServer) Handle(w http.ResponseWriter, r *http.Request)

Handle serves static files

func (*StaticFileServer) Init

Init initializes the module

func (*StaticFileServer) Name

func (s *StaticFileServer) Name() string

Name returns the module name

func (*StaticFileServer) Prefix

func (s *StaticFileServer) Prefix() string

Prefix returns the URL prefix for this file server

func (*StaticFileServer) ProvidesServices

func (s *StaticFileServer) ProvidesServices() []modular.ServiceProvider

ProvidesServices returns the services provided by this module

func (*StaticFileServer) RequiresServices

func (s *StaticFileServer) RequiresServices() []modular.ServiceDependency

RequiresServices returns services required by this module

func (*StaticFileServer) RouterName

func (s *StaticFileServer) RouterName() string

RouterName returns the optional router name this file server should attach to. An empty string means attach to the first available router.

func (*StaticFileServer) SetRouterName

func (s *StaticFileServer) SetRouterName(name string)

SetRouterName sets the router name this file server should attach to.

func (*StaticFileServer) Start

func (s *StaticFileServer) Start(ctx context.Context) error

Start is a no-op

func (*StaticFileServer) Stop

func (s *StaticFileServer) Stop(ctx context.Context) error

Stop is a no-op

type StdIntegrationRegistry

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

StdIntegrationRegistry manages available integration connectors

func NewIntegrationRegistry

func NewIntegrationRegistry(name string) *StdIntegrationRegistry

NewIntegrationRegistry creates a new integration registry

func (*StdIntegrationRegistry) GetConnector

func (r *StdIntegrationRegistry) GetConnector(name string) (IntegrationConnector, error)

GetConnector retrieves a connector by name

func (*StdIntegrationRegistry) Init

Init initializes the registry with service dependencies

func (*StdIntegrationRegistry) ListConnectors

func (r *StdIntegrationRegistry) ListConnectors() []string

ListConnectors returns all registered connectors

func (*StdIntegrationRegistry) Name

func (r *StdIntegrationRegistry) Name() string

Name returns the module name

func (*StdIntegrationRegistry) RegisterConnector

func (r *StdIntegrationRegistry) RegisterConnector(connector IntegrationConnector)

RegisterConnector adds a connector to the registry

func (*StdIntegrationRegistry) Start

func (r *StdIntegrationRegistry) Start() error

Start starts all registered connectors

func (*StdIntegrationRegistry) Stop

func (r *StdIntegrationRegistry) Stop() error

Stop stops all registered connectors

type StepFactory

type StepFactory func(name string, config map[string]any, app modular.Application) (PipelineStep, error)

StepFactory creates a PipelineStep from its name and config.

func NewArtifactPullStepFactory

func NewArtifactPullStepFactory() StepFactory

NewArtifactPullStepFactory returns a StepFactory that creates ArtifactPullStep instances.

func NewArtifactPushStepFactory

func NewArtifactPushStepFactory() StepFactory

NewArtifactPushStepFactory returns a StepFactory that creates ArtifactPushStep instances.

func NewConditionalStepFactory

func NewConditionalStepFactory() StepFactory

NewConditionalStepFactory returns a StepFactory that creates ConditionalStep instances.

func NewDBExecStepFactory

func NewDBExecStepFactory() StepFactory

NewDBExecStepFactory returns a StepFactory that creates DBExecStep instances.

func NewDBQueryStepFactory

func NewDBQueryStepFactory() StepFactory

NewDBQueryStepFactory returns a StepFactory that creates DBQueryStep instances.

func NewDelegateStepFactory

func NewDelegateStepFactory() StepFactory

NewDelegateStepFactory returns a StepFactory that creates DelegateStep instances.

func NewDeployStepFactory

func NewDeployStepFactory() StepFactory

NewDeployStepFactory returns a StepFactory that creates DeployStep instances.

func NewDockerBuildStepFactory

func NewDockerBuildStepFactory() StepFactory

NewDockerBuildStepFactory returns a StepFactory that creates DockerBuildStep instances.

func NewDockerPushStepFactory

func NewDockerPushStepFactory() StepFactory

NewDockerPushStepFactory returns a StepFactory that creates DockerPushStep instances.

func NewDockerRunStepFactory

func NewDockerRunStepFactory() StepFactory

NewDockerRunStepFactory returns a StepFactory that creates DockerRunStep instances.

func NewGateStepFactory

func NewGateStepFactory() StepFactory

NewGateStepFactory returns a StepFactory that creates GateStep instances.

func NewHTTPCallStepFactory

func NewHTTPCallStepFactory() StepFactory

NewHTTPCallStepFactory returns a StepFactory that creates HTTPCallStep instances.

func NewJQStepFactory

func NewJQStepFactory() StepFactory

NewJQStepFactory returns a StepFactory that creates JQStep instances.

func NewJSONResponseStepFactory

func NewJSONResponseStepFactory() StepFactory

NewJSONResponseStepFactory returns a StepFactory that creates JSONResponseStep instances.

func NewLogStepFactory

func NewLogStepFactory() StepFactory

NewLogStepFactory returns a StepFactory that creates LogStep instances.

func NewPublishStepFactory

func NewPublishStepFactory() StepFactory

NewPublishStepFactory returns a StepFactory that creates PublishStep instances.

func NewRequestParseStepFactory

func NewRequestParseStepFactory() StepFactory

NewRequestParseStepFactory returns a StepFactory that creates RequestParseStep instances.

func NewScanContainerStepFactory

func NewScanContainerStepFactory() StepFactory

NewScanContainerStepFactory returns a StepFactory that creates ScanContainerStep instances.

func NewScanDepsStepFactory

func NewScanDepsStepFactory() StepFactory

NewScanDepsStepFactory returns a StepFactory that creates ScanDepsStep instances.

func NewScanSASTStepFactory

func NewScanSASTStepFactory() StepFactory

NewScanSASTStepFactory returns a StepFactory that creates ScanSASTStep instances.

func NewSetStepFactory

func NewSetStepFactory() StepFactory

NewSetStepFactory returns a StepFactory that creates SetStep instances.

func NewShellExecStepFactory

func NewShellExecStepFactory() StepFactory

NewShellExecStepFactory returns a StepFactory that creates ShellExecStep instances.

func NewTransformStepFactory

func NewTransformStepFactory() StepFactory

NewTransformStepFactory returns a StepFactory that creates TransformStep instances.

func NewValidateStepFactory

func NewValidateStepFactory() StepFactory

NewValidateStepFactory returns a StepFactory that creates ValidateStep instances.

type StepLifecycleEvent

type StepLifecycleEvent struct {
	WorkflowType string         `json:"workflowType"`
	StepName     string         `json:"stepName"`
	Connector    string         `json:"connector"`
	Action       string         `json:"action"`
	Status       string         `json:"status"`
	Timestamp    time.Time      `json:"timestamp"`
	Duration     time.Duration  `json:"duration,omitempty"`
	Data         map[string]any `json:"data,omitempty"`
	Error        string         `json:"error,omitempty"`
	Results      map[string]any `json:"results,omitempty"`
}

StepLifecycleEvent is the payload published for step-level lifecycle events.

type StepRegistry

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

StepRegistry maps step type strings to factory functions.

func NewStepRegistry

func NewStepRegistry() *StepRegistry

NewStepRegistry creates an empty StepRegistry.

func (*StepRegistry) Create

func (r *StepRegistry) Create(stepType, name string, config map[string]any, app modular.Application) (PipelineStep, error)

Create instantiates a PipelineStep of the given type.

func (*StepRegistry) Register

func (r *StepRegistry) Register(stepType string, factory StepFactory)

Register adds a step factory for the given type string.

func (*StepRegistry) Types

func (r *StepRegistry) Types() []string

Types returns all registered step type names.

type StepResult

type StepResult struct {
	// Output is the data produced by this step.
	Output map[string]any

	// NextStep overrides the default next step (for conditional routing).
	// Empty string means continue to the next step in sequence.
	NextStep string

	// Stop indicates the pipeline should stop after this step (success).
	Stop bool
}

StepResult is the output of a single pipeline step execution.

type TemplateEngine

type TemplateEngine struct{}

TemplateEngine resolves {{ .field }} expressions against a PipelineContext.

func NewTemplateEngine

func NewTemplateEngine() *TemplateEngine

NewTemplateEngine creates a new TemplateEngine.

func (*TemplateEngine) Resolve

func (te *TemplateEngine) Resolve(tmplStr string, pc *PipelineContext) (string, error)

Resolve evaluates a template string against a PipelineContext. If the string does not contain {{ }}, it is returned as-is.

func (*TemplateEngine) ResolveMap

func (te *TemplateEngine) ResolveMap(data map[string]any, pc *PipelineContext) (map[string]any, error)

ResolveMap evaluates all string values in a map that contain {{ }} expressions. Non-string values and nested maps/slices are processed recursively.

type TestHelper

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

TestHelper provides utilities for module tests

func NewTestHelper

func NewTestHelper(app modular.Application) *TestHelper

NewTestHelper creates a new test helper

type TestLogger

type TestLogger struct {
	Entries []string
}

TestLogger is a simple logger for testing

func NewTestApplication

func NewTestApplication() (modular.Application, *TestLogger)

NewTestApplication creates an isolated test application

func (*TestLogger) Debug

func (l *TestLogger) Debug(msg string, args ...any)

func (*TestLogger) Error

func (l *TestLogger) Error(msg string, args ...any)

func (*TestLogger) Fatal

func (l *TestLogger) Fatal(msg string, args ...any)

func (*TestLogger) Info

func (l *TestLogger) Info(msg string, args ...any)

func (*TestLogger) Warn

func (l *TestLogger) Warn(msg string, args ...any)

type TransformOperation

type TransformOperation struct {
	Type   string         `json:"type" yaml:"type"` // "extract", "map", "convert", "filter"
	Config map[string]any `json:"config" yaml:"config"`
}

TransformOperation defines a single transformation step

type TransformPipeline

type TransformPipeline struct {
	Name       string               `json:"name" yaml:"name"`
	Operations []TransformOperation `json:"operations" yaml:"operations"`
}

TransformPipeline is a named sequence of operations

type TransformStep

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

TransformStep applies a DataTransformer to the pipeline context's current data.

func (*TransformStep) Execute

func (s *TransformStep) Execute(ctx context.Context, pc *PipelineContext) (*StepResult, error)

Execute runs the transformation and returns the result under the "data" key.

func (*TransformStep) Name

func (s *TransformStep) Name() string

Name returns the step name.

type Transition

type Transition struct {
	Name          string         `json:"name" yaml:"name"`
	FromState     string         `json:"fromState" yaml:"fromState"`
	ToState       string         `json:"toState" yaml:"toState"`
	Condition     string         `json:"condition,omitempty" yaml:"condition,omitempty"`
	AutoTransform bool           `json:"autoTransform" yaml:"autoTransform"`
	Data          map[string]any `json:"data,omitempty" yaml:"data,omitempty"`
}

Transition defines a possible state transition

type TransitionEvent

type TransitionEvent struct {
	WorkflowID   string         `json:"workflowId"`
	TransitionID string         `json:"transitionId"`
	FromState    string         `json:"fromState"`
	ToState      string         `json:"toState"`
	Timestamp    time.Time      `json:"timestamp"`
	Data         map[string]any `json:"data,omitempty"`
}

TransitionEvent represents a state transition event

func (TransitionEvent) InstanceID

func (e TransitionEvent) InstanceID() string

InstanceID returns the workflow instance ID This method is provided for backward compatibility with code that expects an InstanceID field

type TransitionHandler

type TransitionHandler interface {
	HandleTransition(ctx context.Context, event TransitionEvent) error
}

TransitionHandler handles workflow state transitions

type TransitionListener

type TransitionListener func(event TransitionEvent)

TransitionListener is a function that gets called when a transition occurs

type TransitionTrigger

type TransitionTrigger interface {
	TriggerTransition(ctx context.Context, workflowID, transitionName string, data map[string]any) error
}

type Trigger

type Trigger interface {
	modular.Module
	modular.Startable
	modular.Stoppable

	// Configure sets up the trigger from configuration
	Configure(app modular.Application, triggerConfig any) error
}

Trigger defines what can start a workflow execution

type TriggerRegistry

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

TriggerRegistry manages registered triggers and allows finding them by name

func NewTriggerRegistry

func NewTriggerRegistry() *TriggerRegistry

NewTriggerRegistry creates a new trigger registry

func (*TriggerRegistry) GetAllTriggers

func (r *TriggerRegistry) GetAllTriggers() map[string]Trigger

GetAllTriggers returns all registered triggers

func (*TriggerRegistry) GetTrigger

func (r *TriggerRegistry) GetTrigger(name string) (Trigger, bool)

GetTrigger returns a trigger by name

func (*TriggerRegistry) RegisterTrigger

func (r *TriggerRegistry) RegisterTrigger(trigger Trigger)

RegisterTrigger adds a trigger to the registry

type TriggerWorkflower

type TriggerWorkflower interface {
	TriggerWorkflow(ctx context.Context, workflowType string, action string, data map[string]any) error
}

TriggerWorkflower is the subset of the engine interface needed for routing.

type User

type User struct {
	ID           string         `json:"id"`
	Email        string         `json:"email"`
	Name         string         `json:"name"`
	PasswordHash string         `json:"-"`
	Metadata     map[string]any `json:"metadata,omitempty"`
	CreatedAt    time.Time      `json:"createdAt"`
}

User represents a user in the in-memory store

type UserRecord

type UserRecord struct {
	ID           string         `json:"id"`
	Email        string         `json:"email"`
	Name         string         `json:"name"`
	PasswordHash string         `json:"-"`
	Metadata     map[string]any `json:"metadata,omitempty"`
	CreatedAt    time.Time      `json:"createdAt"`
}

UserRecord represents a user for persistence

type UserStore

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

UserStore provides user CRUD operations backed by an in-memory store with optional persistence write-through. It can be consumed by auth modules (e.g. auth.jwt) and management APIs.

func NewUserStore

func NewUserStore(name string) *UserStore

NewUserStore creates a new user store module.

func (*UserStore) CreateUser

func (u *UserStore) CreateUser(email, name, password string, metadata map[string]any) (*User, error)

CreateUser creates a new user with the given email, name, and password.

func (*UserStore) DeleteUser

func (u *UserStore) DeleteUser(id string) error

DeleteUser removes a user by ID.

func (*UserStore) GetUser

func (u *UserStore) GetUser(email string) (*User, bool)

GetUser returns a user by email.

func (*UserStore) GetUserByID

func (u *UserStore) GetUserByID(id string) (*User, bool)

GetUserByID returns a user by ID.

func (*UserStore) Init

func (u *UserStore) Init(app modular.Application) error

func (*UserStore) ListUsers

func (u *UserStore) ListUsers() []*User

ListUsers returns all users.

func (*UserStore) LoadSeedFile

func (u *UserStore) LoadSeedFile(path string) error

LoadSeedFile loads users from a JSON file.

func (*UserStore) Name

func (u *UserStore) Name() string

func (*UserStore) ProvidesServices

func (u *UserStore) ProvidesServices() []modular.ServiceProvider

func (*UserStore) RequiresServices

func (u *UserStore) RequiresServices() []modular.ServiceDependency

func (*UserStore) Start

func (u *UserStore) Start(_ context.Context) error

Start is a no-op.

func (*UserStore) Stop

func (u *UserStore) Stop(_ context.Context) error

Stop is a no-op.

func (*UserStore) UpdateUserMetadata

func (u *UserStore) UpdateUserMetadata(id string, metadata map[string]any) error

UpdateUserMetadata updates the metadata for a user identified by ID.

func (*UserStore) UserCount

func (u *UserStore) UserCount() int

UserCount returns the number of users.

func (*UserStore) VerifyPassword

func (u *UserStore) VerifyPassword(email, password string) (*User, error)

VerifyPassword checks if the password matches the stored hash for the given email.

type V1APIHandler

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

V1APIHandler handles the /api/v1/admin/ CRUD endpoints for companies, projects, and workflows. It is wired as a fallback on the admin-v1-queries and admin-v1-commands CQRS handler modules.

func NewV1APIHandler

func NewV1APIHandler(store *V1Store, jwtSecret string) *V1APIHandler

NewV1APIHandler creates a new handler backed by the given store.

func (*V1APIHandler) HandleV1

func (h *V1APIHandler) HandleV1(w http.ResponseWriter, r *http.Request)

HandleV1 dispatches v1 API requests by parsing path segments and delegating to resource-specific handlers. Each handler is self-contained and manages its own HTTP method routing.

func (*V1APIHandler) ServeHTTP

func (h *V1APIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for config-driven delegate dispatch.

func (*V1APIHandler) SetReloadFunc

func (h *V1APIHandler) SetReloadFunc(fn func(configYAML string) error)

SetReloadFunc sets the callback invoked when deploying the system workflow.

func (*V1APIHandler) SetWorkspaceHandler

func (h *V1APIHandler) SetWorkspaceHandler(wh *WorkspaceHandler)

SetWorkspaceHandler sets the optional workspace file management handler.

type V1Company

type V1Company struct {
	ID        string `json:"id"`
	Name      string `json:"name"`
	Slug      string `json:"slug"`
	OwnerID   string `json:"owner_id"`
	ParentID  string `json:"parent_id,omitempty"`
	IsSystem  bool   `json:"is_system,omitempty"`
	Metadata  string `json:"metadata,omitempty"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

V1Company represents a company or organization.

type V1Project

type V1Project struct {
	ID          string `json:"id"`
	CompanyID   string `json:"company_id"`
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	Description string `json:"description,omitempty"`
	IsSystem    bool   `json:"is_system,omitempty"`
	Metadata    string `json:"metadata,omitempty"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at"`
}

V1Project represents a project.

type V1Store

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

V1Store is a SQLite-backed data store for the v1 API.

func OpenV1Store

func OpenV1Store(dbPath string) (*V1Store, error)

OpenV1Store opens (or creates) a SQLite database at dbPath and initializes the schema.

func (*V1Store) Close

func (s *V1Store) Close() error

Close closes the database connection.

func (*V1Store) CompleteExecution

func (s *V1Store) CompleteExecution(id, status string, completedAt time.Time, durationMs int64, errorMsg string) error

CompleteExecution updates an execution record to completed or failed.

func (*V1Store) CompleteExecutionStep

func (s *V1Store) CompleteExecutionStep(id, status string, completedAt time.Time, durationMs int64, errorMsg string) error

CompleteExecutionStep updates a step record to completed or failed.

func (*V1Store) CountExecutionsByWorkflow

func (s *V1Store) CountExecutionsByWorkflow(workflowID string) (map[string]int, error)

CountExecutionsByWorkflow returns execution counts grouped by status for a workflow.

func (*V1Store) CountLogsByWorkflow

func (s *V1Store) CountLogsByWorkflow(workflowID string) (map[string]int, error)

CountLogsByWorkflow returns log counts grouped by level for a workflow.

func (*V1Store) CreateCompany

func (s *V1Store) CreateCompany(name, slug, ownerID string) (*V1Company, error)

CreateCompany inserts a new top-level company.

func (*V1Store) CreateOrganization

func (s *V1Store) CreateOrganization(parentID, name, slug, ownerID string) (*V1Company, error)

CreateOrganization inserts a child company under a parent company.

func (*V1Store) CreateProject

func (s *V1Store) CreateProject(companyID, name, slug, description string) (*V1Project, error)

CreateProject creates a project under an organization.

func (*V1Store) CreateWorkflow

func (s *V1Store) CreateWorkflow(projectID, name, slug, description, configYAML, createdBy string) (*V1Workflow, error)

CreateWorkflow creates a workflow under a project.

func (*V1Store) DB

func (s *V1Store) DB() *sql.DB

DB returns the underlying *sql.DB connection.

func (*V1Store) DeleteWorkflow

func (s *V1Store) DeleteWorkflow(id string) error

DeleteWorkflow deletes a workflow by ID. Returns an error if the workflow is a system workflow.

func (*V1Store) EnsureSystemHierarchy

func (s *V1Store) EnsureSystemHierarchy(ownerID, adminConfigYAML string) (companyID, orgID, projectID, workflowID string, err error)

EnsureSystemHierarchy creates the system company, organization, project, and admin workflow if they don't already exist. Returns the IDs of all created entities.

func (*V1Store) GetCompany

func (s *V1Store) GetCompany(id string) (*V1Company, error)

GetCompany retrieves a company by ID.

func (*V1Store) GetProject

func (s *V1Store) GetProject(id string) (*V1Project, error)

GetProject retrieves a project by ID.

func (*V1Store) GetSystemWorkflow

func (s *V1Store) GetSystemWorkflow() (*V1Workflow, error)

GetSystemWorkflow returns the system workflow if it exists.

func (*V1Store) GetVersion

func (s *V1Store) GetVersion(workflowID string, version int) (*V1WorkflowVersion, error)

GetVersion retrieves a specific version of a workflow.

func (*V1Store) GetWorkflow

func (s *V1Store) GetWorkflow(id string) (*V1Workflow, error)

GetWorkflow retrieves a workflow by ID.

func (*V1Store) InsertExecution

func (s *V1Store) InsertExecution(id, workflowID, triggerType, status string, startedAt time.Time) error

InsertExecution creates a new workflow execution record.

func (*V1Store) InsertExecutionStep

func (s *V1Store) InsertExecutionStep(id, executionID, stepName, stepType, status string, seqNum int, startedAt time.Time) error

InsertExecutionStep creates a new execution step record.

func (*V1Store) ListCompanies

func (s *V1Store) ListCompanies(ownerID string) ([]V1Company, error)

ListCompanies lists top-level companies (parent_id IS NULL).

func (*V1Store) ListOrganizations

func (s *V1Store) ListOrganizations(parentID string) ([]V1Company, error)

ListOrganizations lists child companies under a parent.

func (*V1Store) ListProjects

func (s *V1Store) ListProjects(companyID string) ([]V1Project, error)

ListProjects lists projects for a given organization (company_id).

func (*V1Store) ListVersions

func (s *V1Store) ListVersions(workflowID string) ([]V1WorkflowVersion, error)

ListVersions returns version history for a workflow.

func (*V1Store) ListWorkflows

func (s *V1Store) ListWorkflows(projectID string) ([]V1Workflow, error)

ListWorkflows lists workflows for a project. If projectID is empty, lists all.

func (*V1Store) ResetSystemWorkflow

func (s *V1Store) ResetSystemWorkflow(configYAML string) error

ResetSystemWorkflow resets the system workflow config to the given YAML, incrementing the version and saving a version snapshot.

func (*V1Store) SaveVersion

func (s *V1Store) SaveVersion(workflowID, configYAML, createdBy string) error

SaveVersion stores a version snapshot.

func (*V1Store) SetWorkflowStatus

func (s *V1Store) SetWorkflowStatus(id, status string) (*V1Workflow, error)

SetWorkflowStatus updates a workflow's status field.

func (*V1Store) UpdateWorkflow

func (s *V1Store) UpdateWorkflow(id string, name, description, configYAML, updatedBy string) (*V1Workflow, error)

UpdateWorkflow updates a workflow's fields and auto-increments version. If config_yaml changed, a version snapshot is saved.

type V1Workflow

type V1Workflow struct {
	ID          string `json:"id"`
	ProjectID   string `json:"project_id"`
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	Description string `json:"description,omitempty"`
	ConfigYAML  string `json:"config_yaml"`
	Version     int    `json:"version"`
	Status      string `json:"status"`
	IsSystem    bool   `json:"is_system,omitempty"`
	CreatedBy   string `json:"created_by"`
	UpdatedBy   string `json:"updated_by"`
	CreatedAt   string `json:"created_at"`
	UpdatedAt   string `json:"updated_at"`
}

V1Workflow represents a workflow record.

type V1WorkflowVersion

type V1WorkflowVersion struct {
	ID         string `json:"id"`
	WorkflowID string `json:"workflow_id"`
	Version    int    `json:"version"`
	ConfigYAML string `json:"config_yaml"`
	CreatedBy  string `json:"created_by"`
	CreatedAt  string `json:"created_at"`
}

V1WorkflowVersion represents a snapshot of a workflow at a specific version.

type ValidateStep

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

ValidateStep validates data in the pipeline context against a schema or a list of required fields.

func (*ValidateStep) Execute

Execute validates pc.Current according to the configured strategy.

func (*ValidateStep) Name

func (s *ValidateStep) Name() string

Name returns the step name.

type ValidatingNamespace

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

ValidatingNamespace adds validation to any namespace provider

func WithValidation

func WithValidation(base ModuleNamespaceProvider) *ValidatingNamespace

WithValidation creates a validating namespace wrapper around any namespace provider

func (*ValidatingNamespace) FormatName

func (vn *ValidatingNamespace) FormatName(baseName string) string

FormatName formats and validates a module name

func (*ValidatingNamespace) ResolveDependency

func (vn *ValidatingNamespace) ResolveDependency(dependencyName string) string

ResolveDependency formats and validates a dependency name

func (*ValidatingNamespace) ResolveServiceName

func (vn *ValidatingNamespace) ResolveServiceName(serviceName string) string

ResolveServiceName formats and validates a service name

func (*ValidatingNamespace) ValidateModuleName

func (vn *ValidatingNamespace) ValidateModuleName(moduleName string) error

ValidateModuleName validates a module name

type ValidationIssue

type ValidationIssue struct {
	Severity ValidationSeverity
	Field    string
	Message  string
}

ValidationIssue represents a single problem found during module validation.

func ValidateModule

func ValidateModule(m modular.Module) []ValidationIssue

ValidateModule checks a module implementation for common issues and returns all detected problems. A well-implemented module should produce zero issues.

func (ValidationIssue) String

func (v ValidationIssue) String() string

type ValidationSeverity

type ValidationSeverity string

ValidationSeverity indicates how severe a validation issue is.

const (
	SeverityError   ValidationSeverity = "error"
	SeverityWarning ValidationSeverity = "warning"
	SeverityInfo    ValidationSeverity = "info"
)

type WebhookConfig

type WebhookConfig struct {
	MaxRetries        int           `json:"maxRetries" yaml:"maxRetries"`
	InitialBackoff    time.Duration `json:"initialBackoff" yaml:"initialBackoff"`
	MaxBackoff        time.Duration `json:"maxBackoff" yaml:"maxBackoff"`
	BackoffMultiplier float64       `json:"backoffMultiplier" yaml:"backoffMultiplier"`
	Timeout           time.Duration `json:"timeout" yaml:"timeout"`
}

WebhookConfig holds configuration for the webhook sender

type WebhookDelivery

type WebhookDelivery struct {
	ID          string            `json:"id"`
	URL         string            `json:"url"`
	Payload     []byte            `json:"payload"`
	Headers     map[string]string `json:"headers"`
	Status      string            `json:"status"` // "pending", "delivered", "failed", "dead_letter"
	Attempts    int               `json:"attempts"`
	LastError   string            `json:"lastError,omitempty"`
	CreatedAt   time.Time         `json:"createdAt"`
	DeliveredAt *time.Time        `json:"deliveredAt,omitempty"`
}

WebhookDelivery tracks a webhook delivery attempt

type WebhookIntegrationConnector

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

WebhookIntegrationConnector implements a connector that receives webhook callbacks

func NewWebhookIntegrationConnector

func NewWebhookIntegrationConnector(name, path string, port int) *WebhookIntegrationConnector

NewWebhookIntegrationConnector creates a new webhook integration connector

func (*WebhookIntegrationConnector) Connect

Connect establishes the webhook server

func (*WebhookIntegrationConnector) Disconnect

func (c *WebhookIntegrationConnector) Disconnect(ctx context.Context) error

Disconnect stops the webhook server

func (*WebhookIntegrationConnector) Execute

func (c *WebhookIntegrationConnector) Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error)

Execute is a no-op for webhook connectors (they are passive)

func (*WebhookIntegrationConnector) GetName

func (c *WebhookIntegrationConnector) GetName() string

GetName returns the connector name

func (*WebhookIntegrationConnector) IsConnected

func (c *WebhookIntegrationConnector) IsConnected() bool

IsConnected checks if the connector is connected

func (*WebhookIntegrationConnector) RegisterEventHandler

func (c *WebhookIntegrationConnector) RegisterEventHandler(eventType string, handler func(context.Context, map[string]any) error)

RegisterEventHandler registers a handler for a specific event type

type WebhookSender

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

WebhookSender sends webhooks with retry logic

func NewWebhookSender

func NewWebhookSender(name string, config WebhookConfig) *WebhookSender

NewWebhookSender creates a new WebhookSender with sensible defaults

func (*WebhookSender) GetDeadLetters

func (ws *WebhookSender) GetDeadLetters() []*WebhookDelivery

GetDeadLetters returns all dead letter deliveries

func (*WebhookSender) Init

func (ws *WebhookSender) Init(app modular.Application) error

Init registers the webhook sender as a service

func (*WebhookSender) Name

func (ws *WebhookSender) Name() string

Name returns the module name

func (*WebhookSender) RetryDeadLetter

func (ws *WebhookSender) RetryDeadLetter(ctx context.Context, id string) (*WebhookDelivery, error)

RetryDeadLetter retries a dead letter delivery

func (*WebhookSender) Send

func (ws *WebhookSender) Send(ctx context.Context, url string, payload []byte, headers map[string]string) (*WebhookDelivery, error)

Send sends a webhook with retry logic

func (*WebhookSender) SetClient

func (ws *WebhookSender) SetClient(client *http.Client)

SetClient sets a custom HTTP client (useful for testing)

type WorkflowDatabase

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

WorkflowDatabase wraps database/sql for workflow use

func NewWorkflowDatabase

func NewWorkflowDatabase(name string, config DatabaseConfig) *WorkflowDatabase

NewWorkflowDatabase creates a new WorkflowDatabase module

func (*WorkflowDatabase) Close

func (w *WorkflowDatabase) Close() error

Close closes the database connection

func (*WorkflowDatabase) DB

func (w *WorkflowDatabase) DB() *sql.DB

DB returns the underlying *sql.DB

func (*WorkflowDatabase) DeleteRows

func (w *WorkflowDatabase) DeleteRows(ctx context.Context, table string, where string, whereArgs ...any) (int64, error)

DeleteRows builds and executes a DELETE statement

func (*WorkflowDatabase) Execute

func (w *WorkflowDatabase) Execute(ctx context.Context, sqlStr string, args ...any) (int64, error)

Execute executes a statement and returns rows affected

func (*WorkflowDatabase) Init

Init registers the database as a service

func (*WorkflowDatabase) InsertRow

func (w *WorkflowDatabase) InsertRow(ctx context.Context, table string, data map[string]any) (int64, error)

InsertRow builds and executes an INSERT statement

func (*WorkflowDatabase) Name

func (w *WorkflowDatabase) Name() string

Name returns the module name

func (*WorkflowDatabase) Open

func (w *WorkflowDatabase) Open() (*sql.DB, error)

Open opens the database connection using config

func (*WorkflowDatabase) Ping

func (w *WorkflowDatabase) Ping(ctx context.Context) error

Ping checks the database connection

func (*WorkflowDatabase) ProvidesServices

func (w *WorkflowDatabase) ProvidesServices() []modular.ServiceProvider

ProvidesServices declares the service this module provides, enabling proper dependency ordering in the modular framework.

func (*WorkflowDatabase) Query

func (w *WorkflowDatabase) Query(ctx context.Context, sqlStr string, args ...any) (*QueryResult, error)

Query executes a query and returns structured results

func (*WorkflowDatabase) RequiresServices

func (w *WorkflowDatabase) RequiresServices() []modular.ServiceDependency

RequiresServices returns no dependencies.

func (*WorkflowDatabase) UpdateRows

func (w *WorkflowDatabase) UpdateRows(ctx context.Context, table string, data map[string]any, where string, whereArgs ...any) (int64, error)

UpdateRows builds and executes an UPDATE statement

type WorkflowEngine

type WorkflowEngine interface {
	TriggerWorkflow(ctx context.Context, workflowType string, action string, data map[string]any) error
}

WorkflowEngine defines the interface for triggering workflows

type WorkflowEventEmitter

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

WorkflowEventEmitter publishes workflow and step lifecycle events to the EventBus. All methods are safe to call when the EventBus is unavailable (nil); they silently become no-ops.

func NewWorkflowEventEmitter

func NewWorkflowEventEmitter(app modular.Application) *WorkflowEventEmitter

NewWorkflowEventEmitter creates a new emitter. It attempts to resolve the "eventbus.provider" service from the application. If the service is unavailable the emitter still works but all Emit* calls are no-ops.

func (*WorkflowEventEmitter) EmitStepCompleted

func (e *WorkflowEventEmitter) EmitStepCompleted(ctx context.Context, workflowType, stepName, connector, action string, duration time.Duration, results map[string]any)

EmitStepCompleted publishes a "completed" lifecycle event for a workflow step.

func (*WorkflowEventEmitter) EmitStepFailed

func (e *WorkflowEventEmitter) EmitStepFailed(ctx context.Context, workflowType, stepName, connector, action string, duration time.Duration, err error)

EmitStepFailed publishes a "failed" lifecycle event for a workflow step.

func (*WorkflowEventEmitter) EmitStepStarted

func (e *WorkflowEventEmitter) EmitStepStarted(ctx context.Context, workflowType, stepName, connector, action string)

EmitStepStarted publishes a "started" lifecycle event for a workflow step.

func (*WorkflowEventEmitter) EmitWorkflowCompleted

func (e *WorkflowEventEmitter) EmitWorkflowCompleted(ctx context.Context, workflowType, action string, duration time.Duration, results map[string]any)

EmitWorkflowCompleted publishes a "completed" lifecycle event for a workflow.

func (*WorkflowEventEmitter) EmitWorkflowFailed

func (e *WorkflowEventEmitter) EmitWorkflowFailed(ctx context.Context, workflowType, action string, duration time.Duration, err error)

EmitWorkflowFailed publishes a "failed" lifecycle event for a workflow.

func (*WorkflowEventEmitter) EmitWorkflowStarted

func (e *WorkflowEventEmitter) EmitWorkflowStarted(ctx context.Context, workflowType, action string, data map[string]any)

EmitWorkflowStarted publishes a "started" lifecycle event for a workflow.

type WorkflowInstance

type WorkflowInstance struct {
	ID            string         `json:"id"`
	WorkflowType  string         `json:"workflowType"`
	CurrentState  string         `json:"currentState"`
	PreviousState string         `json:"previousState"`
	Data          map[string]any `json:"data"`
	StartTime     time.Time      `json:"startTime"`
	LastUpdated   time.Time      `json:"lastUpdated"`
	Completed     bool           `json:"completed"`
	Error         string         `json:"error,omitempty"`
}

WorkflowInstance represents an instance of a state machine workflow

type WorkflowLifecycleEvent

type WorkflowLifecycleEvent struct {
	WorkflowType string         `json:"workflowType"`
	Action       string         `json:"action"`
	Status       string         `json:"status"`
	Timestamp    time.Time      `json:"timestamp"`
	Duration     time.Duration  `json:"duration,omitempty"`
	Data         map[string]any `json:"data,omitempty"`
	Error        string         `json:"error,omitempty"`
	Results      map[string]any `json:"results,omitempty"`
}

WorkflowLifecycleEvent is the payload published for workflow-level lifecycle events.

type WorkflowRegistry

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

WorkflowRegistry is a module that provides the V1Store as a service, making the workflow data store (companies, projects, workflows) available to other modules via the service registry. It can either use a shared SQLiteStorage backend (via storageBackend config) or open its own database.

func NewWorkflowRegistry

func NewWorkflowRegistry(name, storageBackend string) *WorkflowRegistry

NewWorkflowRegistry creates a new workflow registry module. If storageBackend is non-empty, it uses that SQLiteStorage service's DB; otherwise it opens its own database at the default path.

func (*WorkflowRegistry) Init

func (*WorkflowRegistry) Name

func (w *WorkflowRegistry) Name() string

func (*WorkflowRegistry) ProvidesServices

func (w *WorkflowRegistry) ProvidesServices() []modular.ServiceProvider

func (*WorkflowRegistry) RequiresServices

func (w *WorkflowRegistry) RequiresServices() []modular.ServiceDependency

func (*WorkflowRegistry) Start

func (w *WorkflowRegistry) Start(_ context.Context) error

Start initializes the V1Store, using the shared storage backend or its own DB.

func (*WorkflowRegistry) Stop

Stop closes the database if using standalone storage.

func (*WorkflowRegistry) Store

func (w *WorkflowRegistry) Store() *V1Store

Store returns the underlying V1Store.

type WorkflowTriggerInfo

type WorkflowTriggerInfo struct {
	WorkflowType string
	Action       string
	Data         map[string]any
}

WorkflowTriggerInfo captures information about a workflow that was triggered

type WorkflowUIHandler

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

WorkflowUIHandler serves the workflow editor UI and provides API endpoints for managing workflow configurations.

func NewWorkflowUIHandler

func NewWorkflowUIHandler(cfg *config.WorkflowConfig) *WorkflowUIHandler

NewWorkflowUIHandler creates a new handler with an optional initial config.

func (*WorkflowUIHandler) HandleGetConfig

func (h *WorkflowUIHandler) HandleGetConfig(w http.ResponseWriter, r *http.Request)

HandleGetConfig serves the workflow configuration (GET /engine/config).

func (*WorkflowUIHandler) HandleGetModules

func (h *WorkflowUIHandler) HandleGetModules(w http.ResponseWriter, r *http.Request)

HandleGetModules lists available module types (GET /engine/modules).

func (*WorkflowUIHandler) HandleGetServices

func (h *WorkflowUIHandler) HandleGetServices(w http.ResponseWriter, r *http.Request)

HandleGetServices serves the services list (GET /engine/services).

func (*WorkflowUIHandler) HandleManagement

func (h *WorkflowUIHandler) HandleManagement(w http.ResponseWriter, r *http.Request)

HandleManagement dispatches management API requests to the appropriate handler based on the request path. This is intended to be used as a handler function for an http.handler module via SetHandleFunc.

func (*WorkflowUIHandler) HandlePutConfig

func (h *WorkflowUIHandler) HandlePutConfig(w http.ResponseWriter, r *http.Request)

HandlePutConfig updates the workflow configuration (PUT /engine/config).

func (*WorkflowUIHandler) HandleReload

func (h *WorkflowUIHandler) HandleReload(w http.ResponseWriter, r *http.Request)

HandleReload reloads the engine with the current configuration (POST /engine/reload).

func (*WorkflowUIHandler) HandleStatus

func (h *WorkflowUIHandler) HandleStatus(w http.ResponseWriter, r *http.Request)

HandleStatus returns the engine status (GET /engine/status).

func (*WorkflowUIHandler) HandleValidate

func (h *WorkflowUIHandler) HandleValidate(w http.ResponseWriter, r *http.Request)

HandleValidate validates a workflow configuration (POST /engine/validate).

func (*WorkflowUIHandler) RegisterRoutes

func (h *WorkflowUIHandler) RegisterRoutes(mux *http.ServeMux)

RegisterRoutes registers all workflow UI routes on the given mux.

func (*WorkflowUIHandler) ServeHTTP

func (h *WorkflowUIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements http.Handler for config-driven delegate dispatch. It handles both query (GET) and command (PUT/POST) operations for engine management, dispatching based on the last path segment.

func (*WorkflowUIHandler) SetReloadFunc

func (h *WorkflowUIHandler) SetReloadFunc(fn func(*config.WorkflowConfig) error)

SetReloadFunc sets the callback for reloading the engine with new config.

func (*WorkflowUIHandler) SetServiceRegistry

func (h *WorkflowUIHandler) SetServiceRegistry(fn func() map[string]any)

SetServiceRegistry sets the callback for accessing the service registry.

func (*WorkflowUIHandler) SetStatusFunc

func (h *WorkflowUIHandler) SetStatusFunc(fn func() map[string]any)

SetStatusFunc sets the callback for getting engine status.

type WorkspaceHandler

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

WorkspaceHandler handles file management API endpoints for project workspaces.

func NewWorkspaceHandler

func NewWorkspaceHandler(wm *store.WorkspaceManager) *WorkspaceHandler

NewWorkspaceHandler creates a new handler backed by the given workspace manager.

func (*WorkspaceHandler) HandleWorkspace

func (h *WorkspaceHandler) HandleWorkspace(w http.ResponseWriter, r *http.Request)

HandleWorkspace dispatches workspace file API requests. Expected paths:

POST   /api/v1/workspaces/{project-id}/files       (upload)
GET    /api/v1/workspaces/{project-id}/files        (list)
GET    /api/v1/workspaces/{project-id}/files/{path} (download)
DELETE /api/v1/workspaces/{project-id}/files/{path} (delete)
POST   /api/v1/workspaces/{project-id}/mkdir        (create directory)

Source Files

Jump to

Keyboard shortcuts

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