engine

package
v0.47.1 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: Apache-2.0 Imports: 24 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 ErrorMessageVariable = "error_message"

ErrorMessageVariable is the local variable of an error boundary event with the error message; camunda:errorMessageVariable names an instance variable that gets it too (BPMN-19).

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

func WithVariables added in v0.38.0

func WithVariables(err error, variables map[string]any) error

WithVariables attaches variables for the error boundary event to a task failure.

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
	// runs per instance with their incidents and element statistics, trimmed by the retention
	// (LONG-03)
	MaxRuns 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
	// the version of the event description a device or import event matched; it reaches only
	// instances on that version (DEP-04). 0 for a message by name, which reaches every version.
	DeploymentVersion int
}

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) ApplyCrashDecisions added in v0.30.0

func (this *Engine) ApplyCrashDecisions(ctx context.Context, decisions []crashbrake.Decision) (remaining []crashbrake.Decision)

ApplyCrashDecisions stops what the crash brake found to have ended the previous process with a fatal error, so that it does not run again after every restart (EXPR-03):

  • a script of an instance: an incident at its element; the deployment version is quarantined and its other running instances get an incident too, because they would run the same script at the element, also one assembled at runtime that no fingerprint catches;
  • the condition of an event: the description is suspended, and the instances waiting for it get an incident;
  • the expression of a start timer, or a script of an instance whose creation the crash rolled back, e.g. started by a message or a timer: the deployment version is quarantined, which disables the deployment, also when it is created only later (applyQuarantine).

The script goes on the blocklist, and the smart service instance that deployed it is stopped (stopOriginator). The deployment is marked faulty, which pauses automatic restarts, and its owner is notified once. A reset of the restarts lifts all of it but the blocklist, an update the suspension and the mark, a newer version or enabling the deployment the quarantine. It returns the decisions it could not apply completely, for the next start; applying one again is harmless.

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). With drain they stay on their version and keep its event descriptions; with stop and restart none stays, and older versions lose their descriptions at once.

func (*Engine) Blocklist added in v0.31.0

func (this *Engine) Blocklist() *script.Blocklist

Blocklist returns the scripts the engine refuses to save, deploy and run (EXPR-03).

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) FailTaskError added in v0.38.0

func (this *Engine) FailTaskError(ctx context.Context, jobId string, taskErr error) (bool, error)

FailTaskError reports the failure of an asynchronous task like FailTask; a PermanentError skips the remaining retries, and variables attached with WithVariables reach the error boundary event that catches the failure (BPMN-19).

func (*Engine) LiftQuarantine added in v0.30.0

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

LiftQuarantine removes the quarantine of a deployment and enables it again; it reports whether there was one. The caller activates the version again, which computes the start timers.

func (*Engine) LoadBlocklist added in v0.31.0

func (this *Engine) LoadBlocklist(ctx context.Context) (revision int64, err error)

LoadBlocklist reads the blocklist from the store.

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). Notifications are not sent here but by ProcessNotifications, so that a notifier without answer does not hold up timers and jobs (SNRGY-5064).

func (*Engine) ProcessNotifications added in v0.20.0

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

ProcessNotifications sends queued notifications; failures are retried with backoff, each with a warning from the loop, and dropped after a day with an error log, so that a notifier outage does not fill the database. Without answer from the notifier, the notifications due after the failed one wait as long as it does, instead of each running into the same timeout (SNRGY-5064).

func (*Engine) ProcessOf added in v0.37.0

func (this *Engine) ProcessOf(v model.DeploymentVersion) (*bpmn.Process, error)

ProcessOf returns the parsed process of a version read with its content, cached as by Process, without a query.

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) RemoveUnusedVersions added in v0.27.0

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

RemoveUnusedVersions removes what older versions of a deployment, of all with an empty id, no longer need; versions in namespaces with keep_versions stay (DEP-04).

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, and evaluates its event conditions again that the crash brake suspended (ApplyCrashDecisions). It does not lift a quarantine: an update calls it too, also a gateway applying again the very version that ended the process. The explicit reset lifts it (LiftQuarantine).

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, labels map[string]string, 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. New variables replace the labels with the given ones, also by none (SNRGY-5107).

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; notifications go out in a loop of their own (SNRGY-5064).

func (*Engine) ScanBlockedScripts added in v0.31.0

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

ScanBlockedScripts searches the stored deployments for the scripts blocked since the last search (EXPR-03): a deployment whose current version contains one is quarantined, the running instances of every version that contains one are stopped with an incident, conditions with one are suspended, and the smart service instance that created such a deployment is stopped. Deployments of gateways are left to the gateway, which runs their instances.

func (*Engine) SetClock

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

SetClock replaces the time source; for tests. It may be called while the engine runs.

func (*Engine) SetCrashBrake added in v0.30.0

func (this *Engine) SetCrashBrake(brake *crashbrake.Brake)

SetCrashBrake records each script of an instance or a start timer as running in the brake, so that one that ends the process is stopped at the next start (EXPR-03, ApplyCrashDecisions).

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) StartInstanceIn added in v0.44.6

func (this *Engine) StartInstanceIn(tx *store.Tx, request StartRequest) (model.Instance, error)

StartInstanceIn starts an instance in the transaction of the caller, e.g. one that holds the lock of the parent of a maintenance procedure across the start. A given id that exists returns that instance, as with StartInstance, without the retry after a concurrent start.

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) TriggerWait added in v0.22.0

func (this *Engine) TriggerWait(ctx context.Context, instanceId string, elementId string, localVariables map[string]any) error

TriggerWait triggers what an element of a running instance waits for at once, from the debugger (DBG-17): a message or device event without its condition, a timer before it is due. With several tokens waiting at the element the one waiting longest. The entry in the history is that of a correlation or a fired timer, marked with manual.

func (*Engine) UnblockScript added in v0.31.0

func (this *Engine) UnblockScript(ctx context.Context, fingerprint string, by string) error

UnblockScript removes a script from the blocklist and applies it on this replica at once, the others when they see the new revision. Quarantined deployments and stopped instances stay as they are.

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.

func (*Engine) WatchBlocklist added in v0.31.0

func (this *Engine) WatchBlocklist(ctx context.Context, interval time.Duration)

WatchBlocklist reloads the blocklist when another replica changed it, and searches the stored deployments for scripts blocked since the last search, until ctx is done.

type ErrorVariables added in v0.38.0

type ErrorVariables struct {
	Err       error
	Variables map[string]any
}

ErrorVariables is a task failure that names what failed, e.g. the device of a device command. The error boundary event that catches the failure gets the variables as local variables (BPMN-19); without one they are dropped. It can wrap a PermanentError.

func (*ErrorVariables) Error added in v0.38.0

func (this *ErrorVariables) Error() string

func (*ErrorVariables) Unwrap added in v0.38.0

func (this *ErrorVariables) Unwrap() error

type FailureVariables added in v0.38.0

type FailureVariables interface {
	FailureVariables(tx *store.Tx, job store.Job) (map[string]any, error)
}

FailureVariables is implemented by task types that name what failed when a failure carries no variables itself, e.g. a timeout the engine detects (BPMN-19). The engine calls it only when an error boundary event catches the failure, before it removes the job. It runs inside the transaction of the engine and must use tx instead of opening its own.

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)
	// per namespace and owner, for the share of each user in the cost of the task execution
	// (SNRGY-3077)
	Task(taskType string, result string, namespace string, owner 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). An error without answer from the notifier is a NotifierUnreachableError.

type NotifierUnreachableError added in v0.20.0

type NotifierUnreachableError struct {
	Err error
}

NotifierUnreachableError is a failure of the notifier without answer, e.g. a timeout or a refused connection; unlike a refused message it holds for every notification alike.

func (*NotifierUnreachableError) Error added in v0.20.0

func (this *NotifierUnreachableError) Error() string

func (*NotifierUnreachableError) Unwrap added in v0.20.0

func (this *NotifierUnreachableError) Unwrap() error

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
	// display labels of variables, kept with the instance; no part of the idempotency check
	// (SNRGY-5107)
	ValueLabels map[string]string
	// 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
	// the maintenance procedure, by its message name, so that a running one can be found
	// (SNRGY-5143)
	Procedure 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. With Async from Execute, a time before the end of
	// Task.Timeout lets the timeout happen then instead, e.g. at the end of the first of several
	// answer windows of a device group (SNRGY-5093).
	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