-
Notifications
You must be signed in to change notification settings - Fork 111
/
extract_policy.go
119 lines (101 loc) · 2.53 KB
/
extract_policy.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
111
112
113
114
115
116
117
118
119
package blob
import (
"fmt"
"strconv"
"strings"
"github.com/c2h5oh/datasize"
"github.com/mitchellh/mapstructure"
)
type ExtractPolicy struct {
RowsStrategy ExtractPolicyStrategy
RowsLimitBytes uint64
FilesStrategy ExtractPolicyStrategy
FilesLimit uint64
}
type ExtractPolicyStrategy int
const (
ExtractPolicyStrategyUnspecified ExtractPolicyStrategy = 0
ExtractPolicyStrategyHead ExtractPolicyStrategy = 1
ExtractPolicyStrategyTail ExtractPolicyStrategy = 2
)
func (s ExtractPolicyStrategy) String() string {
switch s {
case ExtractPolicyStrategyHead:
return "head"
case ExtractPolicyStrategyTail:
return "tail"
default:
return "unspecified"
}
}
type rawExtractPolicy struct {
Rows *struct {
Strategy string `mapstructure:"strategy"`
Size string `mapstructure:"size"`
} `mapstructure:"rows"`
Files *struct {
Strategy string `mapstructure:"strategy"`
Size string `mapstructure:"size"`
} `mapstructure:"files"`
}
func ParseExtractPolicy(cfg map[string]any) (*ExtractPolicy, error) {
if len(cfg) == 0 {
return nil, nil
}
raw := &rawExtractPolicy{}
if err := mapstructure.WeakDecode(cfg, raw); err != nil {
return nil, err
}
res := &ExtractPolicy{}
// Parse files
if raw.Files != nil {
strategy, err := parseStrategy(raw.Files.Strategy)
if err != nil {
return nil, err
}
res.FilesStrategy = strategy
size, err := strconv.ParseUint(raw.Files.Size, 10, 64)
if err != nil {
return nil, fmt.Errorf("invalid size, parse failed with error %w", err)
}
if size <= 0 {
return nil, fmt.Errorf("invalid size %q", size)
}
res.FilesLimit = size
}
// Parse rows
if raw.Rows != nil {
strategy, err := parseStrategy(raw.Rows.Strategy)
if err != nil {
return nil, err
}
res.RowsStrategy = strategy
// TODO: Add support for number of rows
size, err := parseBytes(raw.Rows.Size)
if err != nil {
return nil, fmt.Errorf("invalid size, parse failed with error %w", err)
}
if size <= 0 {
return nil, fmt.Errorf("invalid size %q", size)
}
res.RowsLimitBytes = size
}
return res, nil
}
func parseStrategy(s string) (ExtractPolicyStrategy, error) {
switch strings.ToLower(s) {
case "head":
return ExtractPolicyStrategyHead, nil
case "tail":
return ExtractPolicyStrategyTail, nil
default:
return ExtractPolicyStrategyUnspecified, fmt.Errorf("invalid extract strategy %q", s)
}
}
func parseBytes(str string) (uint64, error) {
var s datasize.ByteSize
if err := s.UnmarshalText([]byte(str)); err != nil {
return 0, err
}
return s.Bytes(), nil
}