-
Notifications
You must be signed in to change notification settings - Fork 22
/
strategy.go
100 lines (88 loc) · 1.97 KB
/
strategy.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
package scheduler
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/invopop/jsonschema"
)
type Strategy int
func (s *Strategy) String() string {
if s == nil {
return ""
}
return AllStrategyNames[*s]
}
// MarshalJSON implements json.Marshaler.
func (s *Strategy) MarshalJSON() ([]byte, error) {
var b bytes.Buffer
if s == nil {
b.Write([]byte("null"))
return b.Bytes(), nil
}
b.Write([]byte{'"'})
b.Write([]byte(s.String()))
b.Write([]byte{'"'})
return b.Bytes(), nil
}
// UnmarshalJSON implements json.Unmarshaler.
func (s *Strategy) UnmarshalJSON(b []byte) error {
var name string
if err := json.Unmarshal(b, &name); err != nil {
return err
}
strategy, err := StrategyForName(name)
if err != nil {
return err
}
*s = strategy
return nil
}
func (s *Strategy) Validate() error {
if s == nil {
return errors.New("scheduler strategy is nil")
}
for _, strategy := range AllStrategies {
if strategy == *s {
return nil
}
}
return fmt.Errorf("unknown scheduler strategy: %d", s)
}
func (Strategy) JSONSchema() *jsonschema.Schema {
enum := make([]any, len(AllStrategyNames))
for i, s := range AllStrategyNames {
enum[i] = s
}
return &jsonschema.Schema{
Type: "string",
Enum: enum,
Default: AllStrategyNames[StrategyDFS],
Title: "CloudQuery scheduling strategy",
}
}
var AllStrategies = Strategies{StrategyDFS, StrategyRoundRobin, StrategyShuffle}
var AllStrategyNames = [...]string{
StrategyDFS: "dfs",
StrategyRoundRobin: "round-robin",
StrategyShuffle: "shuffle",
}
func StrategyForName(s string) (Strategy, error) {
for i, name := range AllStrategyNames {
if name == s {
return AllStrategies[i], nil
}
}
return StrategyDFS, fmt.Errorf("unknown scheduler strategy: %s", s)
}
type Strategies []Strategy
func (s Strategies) String() string {
var buffer bytes.Buffer
for i, strategy := range s {
if i > 0 {
buffer.WriteString(", ")
}
buffer.WriteString(strategy.String())
}
return buffer.String()
}