-
Notifications
You must be signed in to change notification settings - Fork 12
/
validate.go
293 lines (248 loc) · 7.45 KB
/
validate.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package thema
import (
"bytes"
"fmt"
"strings"
"cuelang.org/go/cue"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/token"
terrors "github.com/grafana/thema/errors"
)
type onesidederr struct {
schpos, datapos []token.Pos
code terrors.ValidationCode
coords coords
val string
}
func (e *onesidederr) Error() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%s: validation failed, data is not an instance:", e.coords)
switch e.code {
case terrors.MissingField:
fmt.Fprintf(&buf, "\n\tschema specifies that field exists with type `%v`", e.val)
for _, pos := range e.schpos {
fmt.Fprintf(&buf, "\n\t\t%s", pos.String())
}
fmt.Fprintf(&buf, "\n\tbut field was absent from data")
for _, pos := range e.datapos {
fmt.Fprintf(&buf, "\n\t\t%s", pos.String())
}
case terrors.ExcessField:
fmt.Fprintf(&buf, "\n\tschema is closed and does not specify field")
for _, pos := range e.schpos {
fmt.Fprintf(&buf, "\n\t\t%s", pos.String())
}
fmt.Fprintf(&buf, "\n\tbut field exists in data with value `%v`", e.val)
for _, pos := range e.datapos {
fmt.Fprintf(&buf, "\n\t\t%s", pos.String())
}
}
return buf.String()
}
func (e *onesidederr) Unwrap() error {
return terrors.ErrInvalidData
}
type twosidederr struct {
schpos, datapos []token.Pos
code terrors.ValidationCode
coords coords
sv, dv string
}
func (e *twosidederr) Error() string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "%s: validation failed, data is not an instance:\n\tschema expected `%s`", e.coords, e.sv)
for _, pos := range e.schpos {
fmt.Fprintf(&buf, "\n\t\t%s", pos.String())
}
fmt.Fprintf(&buf, "\n\tbut data contained `%s`", e.dv)
for _, pos := range e.datapos {
fmt.Fprintf(&buf, "\n\t\t%s", pos.String())
}
return buf.String()
}
func (e *twosidederr) Unwrap() error {
return terrors.ErrInvalidData
}
// TODO differentiate this once we have generic composition to support trimming out irrelevant disj branches
type emptydisjunction struct {
schpos, datapos []token.Pos
coords coords
brancherrs []error
}
func (e *emptydisjunction) Unwrap() error {
return terrors.ErrInvalidData
}
type validationFailure []error
func (vf validationFailure) Unwrap() error {
return terrors.ErrInvalidData
}
func (vf validationFailure) Error() string {
var buf bytes.Buffer
for _, e := range vf {
fmt.Fprint(&buf, e.Error())
fmt.Fprintf(&buf, "\n")
}
return buf.String()
}
// HERE BE DRAGONS, BRING A SWORD.
func mungeValidateErr(err error, sch Schema) error {
_, is := err.(errors.Error)
if !is {
return err
}
var errs validationFailure
for _, ee := range errors.Errors(err) {
inputPositions := ee.InputPositions()
schpos, datapos := splitTokens(inputPositions)
x := coords{
sch: sch,
fieldpath: trimThemaPath(ee.Path()),
}
msg, vals := ee.Msg()
switch len(vals) {
case 1:
val, ok := vals[0].(string)
if !ok {
break
}
err := &onesidederr{
schpos: schpos,
datapos: datapos,
coords: x,
val: humanReadableCUEType(val),
}
if strings.Contains(msg, "incomplete") {
err.code = terrors.MissingField
} else if strings.Contains(msg, "not allowed") {
err.code = terrors.ExcessField
} else {
break
}
errs = append(errs, err)
continue
case 2:
var dataval, schval string
var dvok, svok bool
// data first
if len(inputPositions) > 1 && !strings.HasSuffix(inputPositions[0].Filename(), ".cue") {
schval, svok = vals[1].(string)
dataval, dvok = vals[0].(string)
} else { // schema first
schval, svok = vals[0].(string)
dataval, dvok = vals[1].(string)
}
if !svok || !dvok {
break
}
errs = append(errs, &twosidederr{
schpos: schpos,
datapos: datapos,
coords: x,
sv: humanReadableCUEType(schval),
dv: dataval,
code: terrors.OutOfBounds,
})
continue
case 4:
var svok, dvok, skok, dkok bool
var schval, dataval string
var schkind, datakind cue.Kind
// data first
if len(inputPositions) > 1 && !strings.HasSuffix(inputPositions[0].Filename(), ".cue") {
schval, svok = vals[1].(string)
dataval, dvok = vals[0].(string)
schkind, skok = vals[3].(cue.Kind)
datakind, dkok = vals[2].(cue.Kind)
} else { // schema first
schval, svok = vals[0].(string)
dataval, dvok = vals[1].(string)
schkind, skok = vals[2].(cue.Kind)
datakind, dkok = vals[3].(cue.Kind)
}
if !svok || !dvok || !skok || !dkok {
break
}
err := &twosidederr{
schpos: schpos,
datapos: datapos,
coords: x,
sv: humanReadableCUEType(schval),
dv: dataval,
}
if datakind.IsAnyOf(schkind) {
err.code = terrors.OutOfBounds
} else {
err.code = terrors.KindConflict
}
errs = append(errs, err)
continue
}
}
return errs
}
var schErrMsgFormatMap = map[string]string{
"int & >=0 & <=255": "uint8",
"int & >=0 & <=65535": "uint16",
"int & >=0 & <=4294967295": "uint32",
"int & >=0 & <=18446744073709551615": "uint64",
">=0 & <=255 & int": "uint8",
">=0 & <=65535 & int": "uint16",
">=0 & <=4294967295 & int": "uint32",
">=0 & <=18446744073709551615 & int": "uint64",
"int & >=-128 & <=127": "int8",
">=-128 & <=127 & int": "int8",
"int & >=-32768 & <=32767": "int16",
">=-32768 & <=32767 & int": "int16",
"int & >=-2147483648 & <=2147483647": "int32",
">=-2147483648 & <=2147483647 & int": "int32",
"int & >=-9223372036854775808 & <=9223372036854775807": "int64",
">=-9223372036854775808 & <=9223372036854775807 & int": "int64",
">=-340282346638528859811704183484516925440 & <=340282346638528859811704183484516925440": "float32",
">=-1.797693134862315708145274237317043567981E+308 & <=1.797693134862315708145274237317043567981E+308": "float64",
}
func humanReadableCUEType(value string) string {
parts := strings.Split(value, " | ")
readableParts := make([]string, len(parts))
for i, part := range parts {
if m, ok := schErrMsgFormatMap[part]; ok {
part = m
}
readableParts[i] = part
}
return strings.Join(readableParts, " | ")
}
func splitTokens(poslist []token.Pos) (schpos, datapos []token.Pos) {
if len(poslist) == 0 {
return
}
// Items in poslist don't follow a predictable order.
// References to the schema can come first, then the input. The opposite is
// also true. Or in some cases, they can be mixed.
// That's why we have to rely on a shaky heuristic here: we assume that
// only schema files have `.cue` suffixes, and we separate data from schema
// based on that criteria.
for _, pos := range poslist {
if strings.HasSuffix(pos.Filename(), ".cue") {
schpos = append(schpos, pos)
} else {
datapos = append(datapos, pos)
}
}
return schpos, datapos
}
func trimThemaPath(parts []string) []string {
for i, s := range parts {
if s == "schemas" {
return parts[i+3:]
}
}
// Otherwise, it's one of the defpath patterns - eliminate first element
return parts[1:]
}
type coords struct {
sch Schema
fieldpath []string
}
func (c coords) String() string {
return fmt.Sprintf("<%s@v%s>.%s", c.sch.Lineage().Name(), c.sch.Version(), strings.Join(c.fieldpath, "."))
}