stepmachine

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2019 License: MIT Imports: 1 Imported by: 0

README

Step Machine

Easiest way to handle errors that happen in the middle of a proccess

Build Status

Background

When you have a collections of steps that need to run and you need to handle errors when something bad happen you can use this package to run and resume those workloads.

Gettings started

Let see a brief example:

package main

import (
	"fmt"

	"github.com/jaswdr/stepmachine"
)

func sum(last stepmachine.Step, current stepmachine.Step) error {
	result := 2 + 2
	current.Set("result", result)
	return nil
}

func addFive(last stepmachine.Step, current stepmachine.Step) error {
	result := last.Get("result").(int)
	result += 5
	current.Set("result", result)
	return nil
}

func main() {
	// declare all steps
	sumStep := stepmachine.NewStep("sum", sum)
	addFiveStep := stepmachine.NewStep("addFive", addFive)

	// create a new step machine with the sumStep as initial step
	m := stepmachine.NewMachine("my step machine name", sumStep, addFiveStep)

	// run the step machine
	lastStep, err := m.Run("", nil)
	if err != nil {
		panic(err)
	}

	fmt.Println(lastStep.Get("result").(int)) // 9

	// if something bad happen you only need to resume the machine
    	savedValues := map[string]interface{}{
        	"result": 5,
    	}
    	m.Resume("addFiveStep", savedValues)
	_, err = m.Run()
	if err != nil {
		panic(err)
	}

	fmt.Println(m.Get("result").(int)) // 9
}

Logging

Is possible to log inside a step and print in the end, use Step.Println() to log a message and Machine.Stack() to retrieve the log stack with all messages.

Author

Jonathan A. Schweder <jonathanschweder@gmail.com>

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrStepNotFound = errors.New("step not found")
)

Functions

func NewMachine

func NewMachine(name string, steps ...Step) *machine

Types

type Machine

type Machine interface {
	IsSet(key string) bool
	Get(key string) interface{}
	Set(key string, value interface{})
	SetStep(stepID string)
	SetValues(map[string]interface{})
	Values() map[string]interface{}
}

type OnStepChangeFunc

type OnStepChangeFunc func(from, to Step)

OnStepChangeFunc is a function called when the machine changes from one step to another

type OnStepErrorFunc

type OnStepErrorFunc func(step Step, err error)

OnStepErrorFunc is a function called when a step returns an error

type Step

type Step interface {
	ID() string
	SetNext(Step)
	Next() Step
	Run(machine Machine) error
}

func NewStep

func NewStep(id string, runFn StepFunc) Step

type StepFunc

type StepFunc func(machine Machine) error

Jump to

Keyboard shortcuts

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