engine

package
v0.19.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const BudgetWarning = "Storage nearly full"

BudgetWarning is the title of the warning about a nearly full storage budget.

View Source
const NotificationTopic = "incident"

Variables

This section is empty.

Functions

func ErrDisabled

func ErrDisabled(deploymentId string) error

ErrDisabled refuses a start of a deployment that is switched off (DEP-12).

func EventMessageName

func EventMessageName(deploymentId string, elementId string) string

EventMessageName is the message name of a device or import event; it is stable across updates of the deployment (DEP-04).

func IsPermanent

func IsPermanent(err error) bool

Types

type Config

type Config struct {
	// identifies this replica in job locks
	ReplicaId string
	// time zone for timer dates without offset and cron expressions
	Location *time.Location
	// concurrent tokens per instance (LONG-16)
	MaxTokens int
	// JSON size of a single variable and of all variables of an instance (LONG-08)
	MaxVariableBytes          int
	MaxInstanceVariablesBytes int
	// activity log entries per instance, as ring buffer (LONG-03)
	MaxActivities int
	// values in the activity log are truncated to this JSON size
	MaxActivityValueBytes int
	ScriptTimeout         time.Duration
	// shortest timer duration a model may use; cycles, schedules and computed values are
	// limited to it at runtime; 0 allows every duration
	MinTimerDuration time.Duration
	// task defaults if the element sets no senergy:retries and senergy:timeout (TASK-07)
	TaskTimeout time.Duration
	TaskRetries int
	// delay before a failed task is retried, multiplied by the attempt
	TaskRetryBackoff time.Duration
	PollInterval     time.Duration
	BatchSize        int
	// how long message ids are remembered for idempotent correlation (EVT-05)
	ReceiptRetention time.Duration
	// retention of history in days when neither deployment nor namespace set one, and the global
	// maximum, 0 for none (HIST-04)
	RetentionDefaultDays int
	RetentionMaxDays     int
	// newest model versions kept besides those a deployment refers to (MOD-07)
	ModelVersionsKept    int
	HousekeepingInterval time.Duration
	// false in roles that advance processes but do not execute jobs, e.g. the event worker:
	// jobs are created without checking that the task type runs here
	ExecutesTasks bool
	// full states for the history are written every MaxActivities/SnapshotsPerLog activity
	// entries, at least every SnapshotMaxAge, and at most SnapshotsKept are kept (DBG-14)
	SnapshotsPerLog int
	SnapshotMaxAge  time.Duration
	SnapshotsKept   int
	// how long the change stream keeps entries (SYNC-03)
	ChangeRetention time.Duration
	// upper bound of the database in bytes, 0 is unlimited; history is trimmed beyond the
	// retention when it is near (LONG-07)
	StorageBudget int64
}

func DefaultConfig

func DefaultConfig() Config

type CorrelationRequest

type CorrelationRequest struct {
	model.MessageInput
	// restricts correlation to resources of this owner; empty for all (admins)
	OwnerFilter string
}

CorrelationRequest correlates a message with waiting catch events and message start events.

type Effects

type Effects struct {
	// modules to create or replace; the engine sets instance, namespace, owner, creator, element
	// and times
	Modules []model.Module
	// variables of the root instance
	Variables map[string]any
	// messages for the instance of the task, delivered at once when it waits for one of them
	Messages []string
}

Effects are what a task changes besides its output (SMS-04, SMS-12, SMS-13).

type Engine

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

func New

func New(s *store.Store, config Config, namespaces Namespaces, logger *slog.Logger) *Engine

func (*Engine) ActivateVersion

func (this *Engine) ActivateVersion(tx *store.Tx, deploymentId string, version int) error

ActivateVersion registers the message and timer start events of the current version of a deployment; older versions no longer receive new starts.

func (*Engine) ActivityValueLimit

func (this *Engine) ActivityValueLimit() int

ActivityValueLimit is the size above which values are cut in the activity log and in transfers of the debugger (DBG-04).

func (*Engine) ApplyUpdate

func (this *Engine) ApplyUpdate(tx *store.Tx, deploymentId string, strategy model.UpdateStrategy) error

ApplyUpdate handles running instances after a deployment got a new version (DEP-04).

func (*Engine) CompleteTask

func (this *Engine) CompleteTask(ctx context.Context, jobId string, output map[string]any) (bool, error)

CompleteTask delivers the answer of an asynchronous task; false if the task is no longer waiting, e.g. because the answer is a duplicate or late.

func (*Engine) Correlate

func (this *Engine) Correlate(ctx context.Context, request CorrelationRequest) (result model.CorrelationResult, err error)

Correlate delivers a message by name (EVT-01, EVT-02). Without All exactly one target is allowed. A message that finds no target is not an error (EVT-08). With a message id, each target receives the message at most once (EVT-05).

func (*Engine) DebugState

func (this *Engine) DebugState(tx *store.Tx, inst store.Instance) (model.DebugState, error)

DebugState builds the live state of an instance for the debugger (DBG-02).

func (*Engine) DeleteVariable

func (this *Engine) DeleteVariable(ctx context.Context, instanceId string, name string) error

DeleteVariable removes a variable of an instance in any state (SMS-10).

func (*Engine) FailTask

func (this *Engine) FailTask(ctx context.Context, jobId string, message string) (bool, error)

FailTask reports the failure of an asynchronous task; it is retried or becomes an incident.

func (*Engine) MaxRetention

func (this *Engine) MaxRetention(tx *store.Tx, namespace string, owner string) (int, error)

MaxRetention is the highest value a deployment of owner may set; 0 means unlimited.

func (*Engine) NextScheduleDue

func (this *Engine) NextScheduleDue(s model.Schedule, from time.Time) (*time.Time, error)

NextScheduleDue computes the next start of a schedule after from; nil if disabled. Starts are at least MinTimerDuration apart, counted from the due time s had if it has passed.

func (*Engine) Now

func (this *Engine) Now() time.Time

func (*Engine) Process

func (this *Engine) Process(tx *store.Tx, deploymentId string, version int) (*bpmn.Process, error)

Process returns the parsed BPMN of a deployment version from the cache.

func (*Engine) ProcessDue

func (this *Engine) ProcessDue(ctx context.Context) error

ProcessDue fires due timers and start timers and executes due jobs. Every timer and job is handled in its own transaction that locks the instance (or the deployment for start timers) and checks that the timer or job still exists; a second replica finds nothing to do, so each fires exactly once (RUN-06, OPS-01).

func (*Engine) QueueNotification

func (this *Engine) QueueNotification(ctx context.Context, userId string, namespace string, title string, message string) error

QueueNotification queues a notification to a user, sent after commit with retries; namespace is the one of the resource it is about, empty for none.

func (*Engine) RegisterTaskType

func (this *Engine) RegisterTaskType(name string, taskType TaskType)

func (*Engine) ResetRestarts

func (this *Engine) ResetRestarts(tx *store.Tx, deploymentId string) error

ResetRestarts clears the faulty mark and the restart count of a deployment.

func (*Engine) RestartInstance

func (this *Engine) RestartInstance(ctx context.Context, instanceId string, version int, cause model.RunCause) (result model.Instance, err error)

RestartInstance starts a new run of the instance with its stored start variables; a running run is stopped first. version 0 selects the current deployment version (RUN-11).

func (*Engine) RestartWith

func (this *Engine) RestartWith(ctx context.Context, instanceId string, version int, variables map[string]any, cause model.RunCause) (result model.Instance, err error)

RestartWith restarts with new start variables, e.g. after a parameter change of a smart service (SMS-09); nil keeps the stored ones.

func (*Engine) Retention

func (this *Engine) Retention(namespace string, deploymentDays int) int

Retention returns the effective retention in days of a deployment's history: the deployment value or the default, capped by the namespace and the global maximum (HIST-04). The cap of the instance owner is applied separately.

func (*Engine) Rules

func (this *Engine) Rules(namespace model.Namespace) bpmn.Rules

Rules returns the validation rules of a namespace, including the available task types.

func (*Engine) Run

func (this *Engine) Run(ctx context.Context)

Run executes due timers and jobs until ctx is done.

func (*Engine) SetClock

func (this *Engine) SetClock(now func() time.Time)

SetClock replaces the time source; for tests.

func (*Engine) SetMetrics

func (this *Engine) SetMetrics(metrics Metrics)

func (*Engine) SetNotifier

func (this *Engine) SetNotifier(notifier Notifier)

func (*Engine) SetVariable

func (this *Engine) SetVariable(ctx context.Context, instanceId string, name string, value any) error

SetVariable sets a variable of a running instance (RUN-05). SetVariable sets a variable of an instance in any state (RUN-05, SMS-10): variables of a smart service that is ready are read by its maintenance procedures.

func (*Engine) StartInstance

func (this *Engine) StartInstance(ctx context.Context, request StartRequest) (result model.Instance, created bool, err error)

StartInstance creates an instance and runs it until all tokens wait or end. With a given id, a second start with the same content returns the existing instance and created=false; different content is a conflict.

func (*Engine) StopInstance

func (this *Engine) StopInstance(ctx context.Context, instanceId string, reason string) error

StopInstance ends the current run; history stays (RUN-04).

func (*Engine) Store

func (this *Engine) Store() *store.Store

func (*Engine) TaskTypeAvailable

func (this *Engine) TaskTypeAvailable(name string) bool

func (*Engine) VersionsInUse

func (this *Engine) VersionsInUse(tx *store.Tx, d model.Deployment) ([]VersionInUse, error)

VersionsInUse lists the versions of a deployment that are current or still have instances, as smart-service-repository counted its releases (SMS-15); a version that no longer parses is left out.

type JobDefaults

type JobDefaults interface {
	Defaults(input map[string]any) (retries *int, timeout *time.Duration)
}

JobDefaults is implemented by task types that derive retries or a timeout from the task input, e.g. the retries of a device command payload; element attributes take precedence.

type Metrics

type Metrics interface {
	InstanceStarted(namespace, deploymentId, owner string)
	InstanceEnded(namespace, deploymentId, owner string, state model.InstanceState)
	Incident(namespace, deploymentId, owner string)
	Restart(namespace, deploymentId string, performed bool)
	// result is matched, unmatched or duplicate (EVT-08)
	Correlation(result string)
	Task(taskType string, result string, duration time.Duration)
	// delay between due time and firing of a timer
	TimerDelay(delay time.Duration)
}

Metrics receives events of the engine (OPS-05); the labels follow "per deployment and tenant".

type Namespaces

type Namespaces interface {
	Get(name string) (model.Namespace, bool)
}

Namespaces gives the engine the namespace configuration for checks at execution time (NS-03).

type NoMetrics

type NoMetrics struct{}

func (NoMetrics) Correlation

func (NoMetrics) Correlation(string)

func (NoMetrics) Incident

func (NoMetrics) Incident(string, string, string)

func (NoMetrics) InstanceEnded

func (NoMetrics) InstanceEnded(string, string, string, model.InstanceState)

func (NoMetrics) InstanceStarted

func (NoMetrics) InstanceStarted(string, string, string)

func (NoMetrics) Restart

func (NoMetrics) Restart(string, string, bool)

func (NoMetrics) Task

func (NoMetrics) TimerDelay

func (NoMetrics) TimerDelay(time.Duration)

type Notifier

type Notifier interface {
	Notify(ctx context.Context, n store.Notification) error
}

Notifier sends notifications to users; it is called after commit from the outbox (INC-02).

type PermanentError

type PermanentError struct {
	Message string
}

PermanentError fails a task without retries, e.g. an incident the process raises itself.

func (*PermanentError) Error

func (this *PermanentError) Error() string

type StartRequest

type StartRequest struct {
	DeploymentId string
	// 0 selects the current version
	DeploymentVersion int
	// empty: the engine generates a UUID; given: the start is idempotent
	InstanceId string
	Owner      string
	Variables  map[string]any
	// start event; empty selects the start event without definition
	StartElementId string
	// local variables of the start event, e.g. of a message start
	Locals map[string]any
	// the instance a maintenance procedure belongs to (SMS-13)
	ParentId string
	// set by users, e.g. for smart-service instances
	Name, Description string
}

StartRequest starts an instance of a deployment (RUN-01).

type Task

type Task struct {
	JobId        string
	InstanceId   string
	Run          int
	Namespace    string
	DeploymentId string
	ElementId    string
	TaskType     string
	// the owner of the instance; task types act with the owner's rights (SEC-06)
	Owner string
	// the local variables of the task after its input mappings
	Input map[string]any
	// senergy:* attributes of the element
	Attributes map[string]string
	// 1 for the first execution; Attempt > Retries is the last one
	Attempt int
	Retries int
	// the device selection of the element in the deployment (DEP-05), nil if there is none
	Selection *model.Selection
	// the engine cancels ctx after this duration, and an asynchronous task fails after it (TASK-07)
	Timeout time.Duration
	// the instance modules and shared variables belong to: the parent of a maintenance procedure,
	// otherwise the instance itself (SMS-13)
	RootInstanceId string
}

Task is one execution attempt of a service task.

type TaskResult

type TaskResult struct {
	// local variables of the task, e.g. "result" (TASK-10); the output mappings read them
	Output map[string]any
	Async  bool
	// with Async from TimeoutHandler.OnTimeout: the task keeps waiting for its answer until
	// then; zero executes it again at once
	WaitUntil time.Time
	// changes besides the output, applied in the transaction that completes the task
	Effects *Effects
}

TaskResult completes a task with output variables, or announces an asynchronous answer which the task type delivers later through Engine.CompleteTask or Engine.FailTask.

type TaskType

type TaskType interface {
	Execute(ctx context.Context, task Task) (TaskResult, error)
}

TaskType executes service tasks of one type inside the engine (TASK-00). New types are code in the engine, not a network protocol; which types a model may use is decided by its namespace.

type TaskTypeFunc

type TaskTypeFunc func(ctx context.Context, task Task) (TaskResult, error)

TaskTypeFunc adapts a function to TaskType.

func (TaskTypeFunc) Execute

func (this TaskTypeFunc) Execute(ctx context.Context, task Task) (TaskResult, error)

type TimeoutHandler

type TimeoutHandler interface {
	OnTimeout(ctx context.Context, tx *store.Tx, task Task) (*TaskResult, error)
}

TimeoutHandler is implemented by task types that decide what a timeout of an asynchronous task means, e.g. a device group command (TASK-06). The engine calls it on every timeout; Task.Attempt > Task.Retries marks the last attempt. A nil result counts the timeout as failed attempt. A result with Async keeps a waiting task in progress without counting an attempt and without backoff: it waits until WaitUntil, or with a zero WaitUntil the engine executes it again at once in the same attempt with a new lock for Task.Timeout, e.g. to ask the next device of a group. Any other result completes the task. It runs inside the transaction of the engine and must use tx instead of opening its own.

type Undoer

type Undoer interface {
	Undo(ctx context.Context, task Task, effects *Effects, reason error)
}

Undoer is implemented by task types whose effects outlive a failed completion, e.g. an external resource; the engine calls Undo when it could not apply them.

type VersionInUse

type VersionInUse struct {
	Version   int
	CreatedAt time.Time
	Instances int
	Process   *bpmn.Process
}

VersionInUse is a version of a deployment that is current or still has instances.

Jump to

Keyboard shortcuts

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