/
registry.go
68 lines (56 loc) · 1.87 KB
/
registry.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package automa
import (
"github.com/cockroachdb/errors"
"go.uber.org/zap"
)
// StepRegistry is an implementation of AtomicStepRegistry interface
type StepRegistry struct {
cache map[string]AtomicStep
logger *zap.Logger
}
// NewStepRegistry returns an instance of StepRegistry that implements AtomicStepRegistry
// if logger is nil, it initializes itself with a NoOp logger
func NewStepRegistry(logger *zap.Logger) *StepRegistry {
if logger == nil {
logger = zap.NewNop()
}
return &StepRegistry{cache: map[string]AtomicStep{}, logger: logger}
}
// registerStep registers an AtomicStep with the registry
// If a nil step is provided, it skips adding it to the registry without throwing eny error
// It returns itself so that chaining is possible when registering multiple steps with the registry
func (r *StepRegistry) registerStep(id string, step AtomicStep) *StepRegistry {
if step != nil {
r.cache[id] = step
}
return r
}
// RegisterSteps is a helper method to register multiple AtomicSteps at a time
func (r *StepRegistry) RegisterSteps(steps map[string]AtomicStep) AtomicStepRegistry {
for id, step := range steps {
r.registerStep(id, step)
}
return r
}
// GetStep returns an AtomicStep by the id
// It returns error if a step cannot be found by the given ID
func (r *StepRegistry) GetStep(id string) AtomicStep {
if step, ok := r.cache[id]; ok {
return step
}
return nil
}
// BuildWorkflow is a helper method to build a Workflow from the given set of AtomicStep IDs
func (r *StepRegistry) BuildWorkflow(workflowID string, stepIDs StepIDs) (AtomicWorkflow, error) {
var steps []AtomicStep
for _, stepID := range stepIDs {
step := r.GetStep(stepID)
if step != nil {
steps = append(steps, step)
} else {
return nil, errors.Newf("invalid step: %s", stepID)
}
}
workflow := NewWorkflow(workflowID, WithSteps(steps...), WithLogger(r.logger))
return workflow, nil
}