-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathregistry.go
110 lines (85 loc) · 2.18 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package tasks
import (
"sync"
"github.com/ydb-platform/nbs/cloud/tasks/errors"
)
////////////////////////////////////////////////////////////////////////////////
type taskFactory struct {
newTask func() Task
canBeExecuted bool
}
type Registry struct {
taskFactories map[string]taskFactory
taskFactoriesMutex sync.RWMutex
}
func (r *Registry) TaskTypes() []string {
r.taskFactoriesMutex.RLock()
defer r.taskFactoriesMutex.RUnlock()
var taskTypes []string
for taskType := range r.taskFactories {
taskTypes = append(taskTypes, taskType)
}
return taskTypes
}
func (r *Registry) TaskTypesForExecution() []string {
r.taskFactoriesMutex.RLock()
defer r.taskFactoriesMutex.RUnlock()
var taskTypes []string
for taskType, taskFactory := range r.taskFactories {
if taskFactory.canBeExecuted {
taskTypes = append(taskTypes, taskType)
}
}
return taskTypes
}
func (r *Registry) Register(
taskType string,
newTask func() Task,
) error {
return r.register(taskType, newTask, false /* canBeExecuted */)
}
func (r *Registry) RegisterForExecution(
taskType string,
newTask func() Task,
) error {
return r.register(taskType, newTask, true /* canBeExecuted */)
}
func (r *Registry) NewTask(taskType string) (Task, error) {
r.taskFactoriesMutex.RLock()
defer r.taskFactoriesMutex.RUnlock()
factory, ok := r.taskFactories[taskType]
if !ok {
return nil, errors.NewNonRetriableErrorf(
"Task factory with type %v can not be found",
taskType,
)
}
return factory.newTask(), nil
}
////////////////////////////////////////////////////////////////////////////////
func NewRegistry() *Registry {
return &Registry{
taskFactories: make(map[string]taskFactory),
}
}
////////////////////////////////////////////////////////////////////////////////
func (r *Registry) register(
taskType string,
newTask func() Task,
canBeExecuted bool,
) error {
r.taskFactoriesMutex.Lock()
defer r.taskFactoriesMutex.Unlock()
_, ok := r.taskFactories[taskType]
if ok {
return errors.NewNonRetriableErrorf(
"Task factory with type %v already exists",
taskType,
)
}
r.taskFactories[taskType] = taskFactory{
newTask: newTask,
canBeExecuted: canBeExecuted,
}
return nil
}