-
Notifications
You must be signed in to change notification settings - Fork 134
/
hooks.go
98 lines (90 loc) · 2.42 KB
/
hooks.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
package config
import (
"fmt"
"reflect"
"strings"
"github.com/apache/pulsar-client-go/pulsar"
"github.com/mitchellh/mapstructure"
"github.com/pkg/errors"
"github.com/spf13/viper"
"k8s.io/apimachinery/pkg/api/resource"
"github.com/armadaproject/armada/internal/common/armadaerrors"
)
var CustomHooks = []viper.DecoderConfigOption{
addDecodeHook(PulsarCompressionTypeHookFunc()),
addDecodeHook(PulsarCompressionLevelHookFunc()),
addDecodeHook(QuantityDecodeHook()),
}
func PulsarCompressionTypeHookFunc() mapstructure.DecodeHookFuncType {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
// check that src and target types are valid
if f.Kind() != reflect.String || t != reflect.TypeOf(pulsar.NoCompression) {
return data, nil
}
switch strings.ToLower(data.(string)) {
case "", "none":
return pulsar.NoCompression, nil
case "lz4":
return pulsar.LZ4, nil
case "zlib":
return pulsar.ZLib, nil
case "zstd":
return pulsar.ZSTD, nil
default:
return nil, errors.WithStack(&armadaerrors.ErrInvalidArgument{
Name: "pulsar.CompressionType",
Value: data,
Message: fmt.Sprintf("Unknown Pulsar compression type %s", data),
})
}
}
}
func PulsarCompressionLevelHookFunc() mapstructure.DecodeHookFuncType {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
// check that src and target types are valid
if f.Kind() != reflect.String || t != reflect.TypeOf(pulsar.Default) {
return data, nil
}
switch strings.ToLower(data.(string)) {
case "", "default":
return pulsar.Default, nil
case "faster":
return pulsar.Faster, nil
case "better":
return pulsar.Better, nil
default:
return pulsar.Default, errors.WithStack(&armadaerrors.ErrInvalidArgument{
Name: "pulsar.CompressionLevel",
Value: data,
Message: fmt.Sprintf("Unknown Pulsar compression level %s", data),
})
}
}
}
func QuantityDecodeHook() mapstructure.DecodeHookFuncType {
return func(
f reflect.Type,
t reflect.Type,
data interface{},
) (interface{}, error) {
if t != reflect.TypeOf(resource.Quantity{}) {
return data, nil
}
return resource.ParseQuantity(fmt.Sprintf("%v", data))
}
}
func addDecodeHook(hook mapstructure.DecodeHookFuncType) viper.DecoderConfigOption {
return func(c *mapstructure.DecoderConfig) {
c.DecodeHook = mapstructure.ComposeDecodeHookFunc(
c.DecodeHook,
hook)
}
}