41 lines
634 B
Go
41 lines
634 B
Go
|
package stepper
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
Error Status = iota
|
||
|
Completed Status = iota
|
||
|
Canceled Status = iota
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
ErrUnsupportedState = "unsupported state"
|
||
|
)
|
||
|
|
||
|
type Status int
|
||
|
|
||
|
type Step func(ctx context.Context, cancelFunc context.CancelFunc, state interface{}) error
|
||
|
|
||
|
func Run(ctx context.Context, state interface{}, steps ...Step) (Status, error) {
|
||
|
|
||
|
ctx, cancel := context.WithCancel(ctx)
|
||
|
defer cancel()
|
||
|
|
||
|
for _, s := range steps {
|
||
|
select {
|
||
|
case <-ctx.Done():
|
||
|
return Canceled, nil
|
||
|
default:
|
||
|
err := s(ctx, cancel, state)
|
||
|
if err != nil {
|
||
|
return Error, err
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return Completed, nil
|
||
|
|
||
|
}
|