forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsonschema.go
233 lines (199 loc) · 6.56 KB
/
jsonschema.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
package processor
import (
"errors"
"fmt"
"strings"
"time"
"github.com/dafanshu/benthos/v3/internal/docs"
"github.com/dafanshu/benthos/v3/internal/tracing"
"github.com/dafanshu/benthos/v3/lib/log"
"github.com/dafanshu/benthos/v3/lib/metrics"
"github.com/dafanshu/benthos/v3/lib/response"
"github.com/dafanshu/benthos/v3/lib/types"
jsonschema "github.com/xeipuuv/gojsonschema"
)
//------------------------------------------------------------------------------
func init() {
Constructors[TypeJSONSchema] = TypeSpec{
constructor: NewJSONSchema,
Categories: []Category{
CategoryMapping,
},
Summary: `
Checks messages against a provided JSONSchema definition but does not change the
payload under any circumstances. If a message does not match the schema it can
be caught using error handling methods outlined [here](/docs/configuration/error_handling).`,
Description: `
Please refer to the [JSON Schema website](https://json-schema.org/) for
information and tutorials regarding the syntax of the schema.`,
Footnotes: `
## Examples
With the following JSONSchema document:
` + "```json" + `
{
"$id": "https://example.com/person.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person's first name."
},
"lastName": {
"type": "string",
"description": "The person's last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
}
` + "```" + `
And the following Benthos configuration:
` + "```yaml" + `
pipeline:
processors:
- json_schema:
schema_path: "file://path_to_schema.json"
- catch:
- log:
level: ERROR
message: "Schema validation failed due to: ${!error()}"
- bloblang: 'root = deleted()' # Drop messages that fail
` + "```" + `
If a payload being processed looked like:
` + "```json" + `
{"firstName":"John","lastName":"Doe","age":-21}
` + "```" + `
Then a log message would appear explaining the fault and the payload would be
dropped.`,
FieldSpecs: docs.FieldSpecs{
docs.FieldCommon("schema", "A schema to apply. Use either this or the `schema_path` field."),
docs.FieldCommon("schema_path", "The path of a schema document to apply. Use either this or the `schema` field."),
PartsFieldSpec,
},
}
}
//------------------------------------------------------------------------------
// JSONSchemaConfig is a configuration struct containing fields for the
// jsonschema processor.
type JSONSchemaConfig struct {
Parts []int `json:"parts" yaml:"parts"`
SchemaPath string `json:"schema_path" yaml:"schema_path"`
Schema string `json:"schema" yaml:"schema"`
}
// NewJSONSchemaConfig returns a JSONSchemaConfig with default values.
func NewJSONSchemaConfig() JSONSchemaConfig {
return JSONSchemaConfig{
Parts: []int{},
SchemaPath: "",
Schema: "",
}
}
//------------------------------------------------------------------------------
// JSONSchema is a processor that validates messages against a specified json schema.
type JSONSchema struct {
conf JSONSchemaConfig
stats metrics.Type
log log.Modular
schema *jsonschema.Schema
mCount metrics.StatCounter
mErrJSONP metrics.StatCounter
mErr metrics.StatCounter
mSent metrics.StatCounter
mBatchSent metrics.StatCounter
}
// NewJSONSchema returns a JSONSchema processor.
func NewJSONSchema(
conf Config, mgr types.Manager, log log.Modular, stats metrics.Type,
) (Type, error) {
var schema *jsonschema.Schema
var err error
// load JSONSchema definition
if schemaPath := conf.JSONSchema.SchemaPath; schemaPath != "" {
if !(strings.HasPrefix(schemaPath, "file://") || strings.HasPrefix(schemaPath, "http://")) {
return nil, fmt.Errorf("invalid schema_path provided, must start with file:// or http://")
}
schema, err = jsonschema.NewSchema(jsonschema.NewReferenceLoader(conf.JSONSchema.SchemaPath))
if err != nil {
return nil, fmt.Errorf("failed to load JSON schema definition: %v", err)
}
} else if conf.JSONSchema.Schema != "" {
schema, err = jsonschema.NewSchema(jsonschema.NewStringLoader(conf.JSONSchema.Schema))
if err != nil {
return nil, fmt.Errorf("failed to load JSON schema definition: %v", err)
}
} else {
return nil, fmt.Errorf("either schema or schema_path must be provided")
}
return &JSONSchema{
stats: stats,
log: log,
schema: schema,
mCount: stats.GetCounter("count"),
mErrJSONP: stats.GetCounter("error_json_parse"),
mErr: stats.GetCounter("error"),
mSent: stats.GetCounter("sent"),
mBatchSent: stats.GetCounter("batch.sent"),
}, nil
}
//------------------------------------------------------------------------------
// ProcessMessage applies the processor to a message, either creating >0
// resulting messages or a response to be sent back to the message source.
func (s *JSONSchema) ProcessMessage(msg types.Message) ([]types.Message, types.Response) {
s.mCount.Incr(1)
newMsg := msg.Copy()
proc := func(i int, span *tracing.Span, part types.Part) error {
jsonPart, err := msg.Get(i).JSON()
if err != nil {
s.log.Debugf("Failed to parse part into json: %v\n", err)
s.mErrJSONP.Incr(1)
s.mErr.Incr(1)
return err
}
partLoader := jsonschema.NewGoLoader(jsonPart)
result, err := s.schema.Validate(partLoader)
if err != nil {
s.log.Debugf("Failed to validate json: %v\n", err)
s.mErr.Incr(1)
return err
}
if !result.Valid() {
s.log.Debugf("The document is not valid\n")
s.mErr.Incr(1)
var errStr string
for i, desc := range result.Errors() {
if i > 0 {
errStr += "\n"
}
description := strings.ToLower(desc.Description())
if property := desc.Details()["property"]; property != nil {
description = property.(string) + strings.TrimPrefix(description, strings.ToLower(property.(string)))
}
errStr += desc.Field() + " " + description
}
return errors.New(errStr)
}
s.log.Debugf("The document is valid\n")
return nil
}
if newMsg.Len() == 0 {
return nil, response.NewAck()
}
IteratePartsWithSpanV2(TypeJSONSchema, s.conf.Parts, newMsg, proc)
s.mBatchSent.Incr(1)
s.mSent.Incr(int64(newMsg.Len()))
msgs := [1]types.Message{newMsg}
return msgs[:], nil
}
// CloseAsync shuts down the processor and stops processing requests.
func (s *JSONSchema) CloseAsync() {
}
// WaitForClose blocks until the processor has closed down.
func (s *JSONSchema) WaitForClose(timeout time.Duration) error {
return nil
}
//------------------------------------------------------------------------------