-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
init.lua
2536 lines (2148 loc) · 70.3 KB
/
init.lua
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local tablex = require "pl.tablex"
local pretty = require "pl.pretty"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local new_tab = require "table.new"
local nkeys = require "table.nkeys"
local is_reference = require "kong.pdk.vault".is_reference
local json = require "kong.db.schema.json"
local cjson_safe = require "cjson.safe"
local setmetatable = setmetatable
local getmetatable = getmetatable
local re_match = ngx.re.match
local re_find = ngx.re.find
local tostring = tostring
local concat = table.concat
local insert = table.insert
local format = string.format
local unpack = unpack
local assert = assert
local yield = utils.yield
local pairs = pairs
local pcall = pcall
local floor = math.floor
local type = type
local next = next
local update_time = ngx.update_time
local ngx_time = ngx.time
local ngx_now = ngx.now
local find = string.find
local null = ngx.null
local max = math.max
local sub = string.sub
local safe_decode = cjson_safe.decode
local random_string = utils.random_string
local uuid = utils.uuid
local json_validate = json.validate
local Schema = {}
Schema.__index = Schema
local _cache = {}
local _workspaceable = {}
local validation_errors = {
-- general message
ERROR = "Validation error: %s",
-- types
ARRAY = "expected an array",
SET = "expected a set",
MAP = "expected a map",
RECORD = "expected a record",
STRING = "expected a string",
NUMBER = "expected a number",
BOOLEAN = "expected a boolean",
INTEGER = "expected an integer",
FUNCTION = "expected a function",
-- validations
EQ = "value must be %s",
NE = "value must not be %s",
GT = "value must be greater than %s",
BETWEEN = "value should be between %d and %d",
LEN_EQ = "length must be %d",
LEN_MIN = "length must be at least %d",
LEN_MAX = "length must be at most %d",
MATCH = "invalid value: %s",
NOT_MATCH = "invalid value: %s",
MATCH_ALL = "invalid value: %s",
MATCH_NONE = "invalid value: %s",
MATCH_ANY = "invalid value: %s",
STARTS_WITH = "should start with: %s",
CONTAINS = "expected to contain: %s",
ONE_OF = "expected one of: %s",
NOT_ONE_OF = "must not be one of: %s",
IS_REGEX = "not a valid regex: %s",
TIMESTAMP = "expected a valid timestamp",
UUID = "expected a valid UUID",
VALIDATION = "failed validating: %s",
-- field presence
BAD_INPUT = "expected an input table",
REQUIRED = "required field missing",
NO_FOREIGN_DEFAULT = "will not generate a default value for a foreign field",
UNKNOWN = "unknown field",
IMMUTABLE = "immutable field cannot be updated",
-- entity checks
REQUIRED_FOR_ENTITY_CHECK = "field required for entity check",
ENTITY_CHECK = "failed entity check: %s(%s)",
ENTITY_CHECK_N_FIELDS = "entity check requires %d fields",
CHECK = "entity check failed",
CONDITIONAL = "failed conditional validation given value of field '%s'",
AT_LEAST_ONE_OF = "at least one of these fields must be non-empty: %s",
CONDITIONAL_AT_LEAST_ONE_OF = "at least one of these fields must be non-empty: %s",
ONLY_ONE_OF = "exactly one of these fields must be non-empty: %s",
DISTINCT = "values of these fields must be distinct: %s",
MUTUALLY_REQUIRED = "all or none of these fields must be set: %s",
MUTUALLY_EXCLUSIVE = "only one or none of these fields must be set: %s",
MUTUALLY_EXCLUSIVE_SETS = "these sets are mutually exclusive: %s",
-- schema error
SCHEMA_NO_DEFINITION = "expected a definition table",
SCHEMA_NO_FIELDS = "error in schema definition: no 'fields' table",
SCHEMA_BAD_REFERENCE = "schema refers to an invalid foreign entity: %s",
SCHEMA_CANNOT_VALIDATE = "error in schema prevents from validating this field",
SCHEMA_TYPE = "invalid type: %s",
-- primary key errors
NOT_PK = "not a primary key",
MISSING_PK = "missing primary key",
-- subschemas
SUBSCHEMA_UNKNOWN = "unknown type: %s",
SUBSCHEMA_BAD_PARENT = "error in definition of '%s': entities of type '%s' cannot have subschemas",
SUBSCHEMA_UNDEFINED_FIELD = "error in definition of '%s': %s: abstract field was not specialized",
SUBSCHEMA_BAD_TYPE = "error in definition of '%s': %s: cannot change type in a specialized field",
SUBSCHEMA_BAD_FIELD = "error in definition of '%s': %s: cannot create a new field",
SUBSCHEMA_ABSTRACT_FIELD = "error in schema definition: abstract field was not specialized",
-- transformations
TRANSFORMATION_ERROR = "transformation failed: %s",
-- json
JSON_ENCODE_ERROR = "value could not be JSON-encoded: %s",
JSON_DECODE_ERROR = "value could not be JSON-decoded: %s",
JSON_SCHEMA_ERROR = "value failed JSON-schema validation: %s",
JSON_PARENT_KEY_MISSING = "validation of %s depends on the parent attribute %s, but it is not set",
JSON_SCHEMA_NOT_FOUND = "mandatory json schema for field (%s) not found"
}
Schema.valid_types = {
array = true,
set = true,
string = true,
number = true,
boolean = true,
integer = true,
foreign = true,
map = true,
record = true,
["function"] = true,
json = true,
}
local uuid_regex = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
local function make_length_validator(err, fn)
return function(value, n, field)
local len = #value
if field.type == "map" then
for _ in pairs(value) do
len = len + 1
end
end
if fn(len, n) then
return true
end
return nil, validation_errors[err]:format(n)
end
end
--- Produce a nicely quoted list:
-- Given `{"foo", "bar", "baz"}` and `"or"`, produces
-- `"'foo', 'bar', 'baz'"`.
-- Given an array of arrays (e.g., `{{"f1", "f2"}, {"f3", "f4"}}`), produces
-- `"('f1', 'f2'), ('f3', 'f4')"`.
-- @param words an array of strings and/or arrays of strings.
-- @return The string of quoted words and/or arrays.
local function quoted_list(words)
local msg = {}
for i = 1, #words do
local word = words[i]
if type(word) == "table" then
insert(msg, ("(%s)"):format(quoted_list(word)))
else
insert(msg, ("'%s'"):format(word))
end
end
return concat(msg, ", ")
end
--- Validator functions available for schemas.
-- A validator can only affect one field.
-- Each validation is registered in a schema field definition as
-- a key-value pair. The key is the validation name and the value
-- is an optional argument (by convention, `true` if the argument
-- is to be ignored). Each validation function takes as inputs
-- the value to be validated and the argument given in the schema
-- definition. The function should return true or nil,
-- optionally followed by an error message. If the error message
-- is not given, the validation name (in uppercase) is used as
-- a key in `validation_errors` to get a message. If it was not
-- registered, a generic fallback error message is produced with
-- `validation_errors.VALIDATION`.
Schema.validators = {
between = function(value, limits)
if value < limits[1] or value > limits[2] then
return nil, validation_errors.BETWEEN:format(limits[1], limits[2])
end
return true
end,
eq = function(value, wanted)
if value == wanted then
return true
end
local str = (wanted == null) and "null" or tostring(wanted)
return nil, validation_errors.EQ:format(str)
end,
ne = function(value, wanted)
if value ~= wanted then
return true
end
local str = (wanted == null) and "null" or tostring(value)
return nil, validation_errors.NE:format(str)
end,
gt = function(value, limit)
if value > limit then
return true
end
return nil, validation_errors.GT:format(tostring(limit))
end,
len_eq = make_length_validator("LEN_EQ", function(len, n)
return len == n
end),
len_min = make_length_validator("LEN_MIN", function(len, n)
return len >= n
end),
len_max = make_length_validator("LEN_MAX", function(len, n)
return len <= n
end),
match = function(value, pattern)
local m = value:match(pattern)
if not m then
return nil, validation_errors.MATCH:format(value)
end
return true
end,
is_regex = function(value)
local _, err = re_match("any string", value)
return err == nil
end,
not_match = function(value, pattern)
local m = value:match(pattern)
if m then
return nil, validation_errors.NOT_MATCH:format(value)
end
return true
end,
match_all = function(value, list)
for i = 1, #list do
local m = value:match(list[i].pattern)
if not m then
return nil, list[i].err
end
end
return true
end,
match_none = function(value, list)
for i = 1, #list do
local m = value:match(list[i].pattern)
if m then
return nil, list[i].err
end
end
return true
end,
match_any = function(value, arg)
local patterns = arg.patterns
for i = 1, #patterns do
local m = value:match(patterns[i])
if m then
return true
end
end
return nil, arg.err
end,
starts_with = function(value, expected)
-- produces simpler error messages than 'match'
if sub(value, 1, #expected) ~= expected then
return nil, validation_errors.STARTS_WITH:format(expected)
end
return true
end,
one_of = function(value, options)
for i = 1, #options do
if value == options[i] then
return true
end
end
return nil, validation_errors.ONE_OF:format(concat(options, ", "))
end,
not_one_of = function(value, options)
for i = 1, #options do
if value == options[i] then
return nil, validation_errors.NOT_ONE_OF:format(concat(options, ", "))
end
end
return true
end,
timestamp = function(value)
return value > 0 or nil
end,
uuid = function(value)
if #value ~= 36 then
return nil
end
return re_find(value, uuid_regex, "ioj") and true or nil
end,
contains = function(array, wanted)
for i = 1, #array do
if array[i] == wanted then
return true
end
end
return nil, validation_errors.CONTAINS:format(wanted)
end,
mutually_exclusive_subsets = function(value, subsets)
local subset_union = {} -- union of all subsets; key is an element, value is the
for i = 1, #subsets do -- the subset the element is part of
local subset = subsets[i]
for j = 1, #subset do
subset_union[subset[j]] = subset
end
end
local member_of = {}
for i = 1, #value do -- for each value, add the set it's part of
local val = value[i]
if subset_union[val] and not member_of[subset_union[val]] then -- to member_of, iff it hasn't already
member_of[subset_union[val]] = true
member_of[#member_of+1] = subset_union[val]
end
end
if #member_of <= 1 then
return true
else
return nil, validation_errors.MUTUALLY_EXCLUSIVE_SETS:format(quoted_list(member_of))
end
end,
custom_validator = function(value, fn)
return fn(value)
end
}
Schema.validators_order = {
"eq",
"ne",
"not_one_of",
"one_of",
-- type-dependent
"gt",
"timestamp",
"uuid",
"is_regex",
"between",
-- strings (1/2)
"len_eq",
"len_min",
"len_max",
-- strings (2/2)
"starts_with",
"not_match",
"match_none",
"match",
"match_all",
"match_any",
-- arrays
"contains",
-- other
"custom_validator",
"mutually_exclusive_subsets",
}
--- Returns true if a field is non-empty (with emptiness defined
-- for strings and aggregate values).
-- This function is defined as `is_nonempty` rather than the more intuitive
-- `is_empty` because the former has a less fuzzy definition:
-- being non-empty clearly excludes null and nil values.
-- @param value a value, which may be `ngx.null` or `nil`.
local function is_nonempty(value)
if value == nil
or value == null
or (type(value) == "table" and not next(value))
or (type(value) == "string" and value == "") then
return false
end
return true
end
--- Returns true if a table is a sequence
-- @param t a table to be checked
-- @return `true` if `t` is a sequence, otherwise returns false.
local function is_sequence(t)
if type(t) ~= "table" then
return false
end
local m, c = 0, 0
for k, _ in pairs(t) do
c = c + 1
if t[c] == nil then
return false
end
if type(k) ~= "number" or k < 0 or floor(k) ~= k then
return false
end
m = max(m, k)
end
return c == m
end
-- Get a field from a possibly-nested table using a string key
-- such as "x.y.z", such that `get_field(t, "x.y.z")` is the
-- same as `t.x.y.z`.
local function get_field(tbl, name)
if tbl == nil or tbl == null then
return nil
end
local dot = find(name, ".", 1, true)
if not dot then
return tbl[name]
end
local hd, tl = sub(name, 1, dot - 1), sub(name, dot + 1)
return get_field(tbl[hd], tl)
end
-- Set a field from a possibly-nested table using a string key
-- such as "x.y.z", such that `set_field(t, "x.y.z", v)` is the
-- same as `t.x.y.z = v`.
local function set_field(tbl, name, value)
local dot = find(name, ".", 1, true)
if not dot then
tbl[name] = value
return
end
local hd, tl = sub(name, 1, dot - 1), sub(name, dot + 1)
local subtbl = tbl[hd]
if subtbl == nil then
subtbl = {}
tbl[hd] = subtbl
end
set_field(subtbl, tl, value)
end
-- Get a field definition from a possibly-nested schema using a string key
-- such as "x.y.z", such that `get_field(t, "x.y.z")` is the
-- same as `t.x.y.z`.
local function get_schema_field(schema, name)
if schema == nil then
return nil
end
local dot = find(name, ".", 1, true)
if not dot then
return schema.fields[name]
end
local hd, tl = sub(name, 1, dot - 1), sub(name, dot + 1)
return get_schema_field(schema.fields[hd], tl)
end
local function mutually_required(entity, field_names)
local nonempty = {}
for i = 1, #field_names do
local name = field_names[i]
if is_nonempty(get_field(entity, name)) then
insert(nonempty, name)
end
end
if #nonempty == 0 or #nonempty == #field_names then
return true
end
return nil, quoted_list(field_names)
end
local function mutually_exclusive(entity, field_names)
local nonempty = {}
for i = 1, #field_names do
local name = field_names[i]
if is_nonempty(get_field(entity, name)) then
insert(nonempty, name)
end
end
if #nonempty == 0 or #nonempty == 1 then
return true
end
return nil, quoted_list(field_names)
end
--- Entity checkers are cross-field validation rules.
-- An entity checker is implemented as an entry in this table,
-- containing a mandatory field `fn`, the checker function,
-- and an optional field `field_sources`.
--
-- An entity checker is used in a schema by adding an entry to
-- the `entity_checks` array of a schema table. Entries
-- in `entity_checks` are tables with a single key, named
-- after the entity checker; its value is the "entity check
-- argument". For example:
--
-- entity_checks = {
-- { only_one_of = { "field_a", "field_b" } },
-- },
--
-- The `fn` function which implements an entity checker receives
-- three arguments: a projection of the entity containing only
-- the relevant fields to this checker, the entity check argument,
-- and the schema table. This ensures that the entity checker
-- does _not_ have access by default to the entire entity being
-- checked. This allows us to enable/disable entity checkers on
-- partial updates.
--
-- To specify which fields are relevant to this checker, one
-- uses the `field_sources`. It is an array of strings, which
-- are key names to the entity check argument (see the `conditional`
-- entity checker for an example of its use).
-- If `field_sources` is not present, it is assumed that the
-- entity check argument is an array of field names, and that
-- all of them need to be present for the entity checker to run.
-- (this is the case, for example, of `only_one_of` in the example
-- above: this checker forces both fields to be given, and the
-- implementation of the checker will demand that only one is
-- non-empty).
Schema.entity_checkers = {
at_least_one_of = {
run_with_missing_fields = true,
run_with_invalid_fields = true,
fn = function(entity, field_names)
for i = 1, #field_names do
local name = field_names[i]
if is_nonempty(get_field(entity, name)) then
return true
end
end
return nil, quoted_list(field_names)
end,
},
conditional_at_least_one_of = {
run_with_missing_fields = true,
run_with_invalid_fields = true,
field_sources = {
"if_field",
"then_at_least_one_of",
"else_then_at_least_one_of",
},
required_fields = { "if_field" },
fn = function(entity, arg, schema)
local if_value = get_field(entity, arg.if_field)
if if_value == nil then
return true
end
local arg_mt = {
__index = get_schema_field(schema, arg.if_field),
}
setmetatable(arg.if_match, arg_mt)
local ok, _ = Schema.validate_field(schema, arg.if_match, if_value)
if not ok then
if arg.else_match == nil then
return true
end
-- run 'else'
setmetatable(arg.else_match, arg_mt)
local ok, _ = Schema.validate_field(schema, arg.else_match, if_value)
if not ok then
return true
end
local names = arg.else_then_at_least_one_of
for i = 1, #names do
if is_nonempty(get_field(entity, names[i])) then
return true
end
end
local list = quoted_list(arg.else_then_at_least_one_of)
local else_then_err
if arg.else_then_err then
else_then_err = arg.else_then_err:format(list)
end
return nil, list, else_then_err
end
-- run 'if'
local names = arg.then_at_least_one_of
for i = 1, #names do
if is_nonempty(get_field(entity, names[i])) then
return true
end
end
local list = quoted_list(arg.then_at_least_one_of)
local then_err
if arg.then_err then
then_err = arg.then_err:format(list)
end
return nil, list, then_err
end,
},
only_one_of = {
run_with_missing_fields = false,
run_with_invalid_fields = true,
fn = function(entity, field_names)
local found = false
local ok = false
for i = 1, #field_names do
if is_nonempty(get_field(entity, field_names[i])) then
if not found then
found = true
ok = true
else
ok = false
end
end
end
if ok then
return true
end
return nil, quoted_list(field_names)
end,
},
distinct = {
run_with_missing_fields = false,
run_with_invalid_fields = true,
fn = function(entity, field_names)
local seen = {}
for i = 1, #field_names do
local value = get_field(entity, field_names[i])
if is_nonempty(value) then
if seen[value] then
return nil, quoted_list(field_names)
end
seen[value] = true
end
end
return true
end,
},
--- Conditional validation: if the first field passes the given validator,
-- then run the validator against the second field.
-- Example:
-- ```
-- conditional = { if_field = "policy",
-- if_match = { match = "^redis$" },
-- then_field = "redis_host",
-- then_match = { required = true } }
-- ```
conditional = {
run_with_missing_fields = false,
run_with_invalid_fields = true,
field_sources = { "if_field", "then_field" },
required_fields = { ["if_field"] = true },
fn = function(entity, arg, schema, errors)
local if_value = get_field(entity, arg.if_field)
local then_value = get_field(entity, arg.then_field)
if then_value == nil then
then_value = null
end
setmetatable(arg.if_match, {
__index = get_schema_field(schema, arg.if_field)
})
local ok, _ = Schema.validate_field(schema, arg.if_match, if_value)
if not ok then
return true
end
-- Handle `required`
if arg.then_match.required == true and then_value == null then
set_field(errors, arg.then_field, validation_errors.REQUIRED)
return nil, arg.if_field
end
setmetatable(arg.then_match, {
__index = get_schema_field(schema, arg.then_field)
})
local err
ok, err = Schema.validate_field(schema, arg.then_match, then_value)
if not ok then
set_field(errors, arg.then_field, err)
local then_err
if arg.then_err then
then_err = arg.then_err:format(arg.if_field)
end
return nil, arg.if_field, then_err
end
return true
end,
},
custom_entity_check = {
run_with_missing_fields = false,
run_with_invalid_fields = false,
field_sources = { "field_sources" },
required_fields = { ["field_sources"] = true },
fn = function(entity, arg)
return arg.fn(entity)
end,
},
mutually_required = {
run_with_missing_fields = true,
fn = mutually_required,
},
mutually_exclusive = {
run_with_missing_fields = true,
fn = mutually_exclusive,
},
mutually_exclusive_sets = {
run_with_missing_fields = true,
field_sources = { "set1", "set2" },
required_fields = { "set1", "set2" },
fn = function(entity, args)
local nonempty1 = {}
local nonempty2 = {}
for i = 1, #args.set1 do
local name = args.set1[i]
if is_nonempty(get_field(entity, name)) then
insert(nonempty1, name)
end
end
for i = 1, #args.set2 do
local name = args.set2[i]
if is_nonempty(get_field(entity, name)) then
insert(nonempty2, name)
end
end
if #nonempty1 > 0 and #nonempty2 > 0 then
return nil, format("(%s), (%s)", quoted_list(nonempty1),
quoted_list(nonempty2))
end
return true
end
},
}
local function memoize(fn)
local cache = setmetatable({}, { __mode = "k" })
return function(k)
if cache[k] then
return cache[k]
end
local v = fn(k)
cache[k] = v
return v
end
end
local function validate_elements(self, field, value)
field.elements.required = true
local errs = {}
local all_ok = true
for i = 1, #value do
local ok, err = self:validate_field(field.elements, value[i])
if not ok then
errs[i] = err
all_ok = false
end
end
if all_ok then
return true
else
return nil, errs
end
end
local get_field_schema = memoize(function(field)
return Schema.new(field)
end)
-- Forward declaration
local validate_fields
--- Validate the field according to the schema.
-- For aggregate values, validate each field recursively.
-- @param self The complete schema object.
-- @param field The schema definition for the field.
-- @param value The value to be checked (may be ngx.null).
-- @return true if the field validates correctly;
-- nil and an error message on failure.
function Schema:validate_field(field, value)
yield(true)
if value == null then
if field.ne == null then
return nil, field.err or validation_errors.NE:format("null")
end
if field.eq ~= nil and field.eq ~= null then
return nil, validation_errors.EQ:format(tostring(field.eq))
end
if field.required then
return nil, validation_errors.REQUIRED
end
return true
end
if field.eq == null then
return nil, field.err or validation_errors.EQ:format("null")
end
if field.abstract then
return nil, validation_errors.SUBSCHEMA_ABSTRACT_FIELD
end
if field.type == "array" then
if not is_sequence(value) then
return nil, validation_errors.ARRAY
end
local ok, err = validate_elements(self, field, value)
if not ok then
return nil, err
end
elseif field.type == "set" then
if not is_sequence(value) then
return nil, validation_errors.SET
end
field.elements.required = true
local ok, err = validate_elements(self, field, value)
if not ok then
return nil, err
end
elseif field.type == "map" then
if type(value) ~= "table" then
return nil, validation_errors.MAP
end
field.keys.required = true
field.values.required = true
for k, v in pairs(value) do
local ok, err
ok, err = self:validate_field(field.keys, k)
if not ok then
return nil, err
end
ok, err = self:validate_field(field.values, v)
if not ok then
return nil, err
end
end
elseif field.type == "record" then
if type(value) ~= "table" then
return nil, validation_errors.RECORD
end
local field_schema = get_field_schema(field)
-- TODO return nested table or string?
local copy = field_schema:process_auto_fields(value, "insert")
local ok, err = field_schema:validate(copy)
if not ok then
return nil, err
end
elseif field.type == "foreign" then
if field.schema and field.schema.validate_primary_key then
local ok, errs = field.schema:validate_primary_key(value, true)
if not ok then
if type(value) == "table" and field.schema.validate then
local foreign_ok, foreign_errs = field.schema:validate(value, false)
if not foreign_ok then
return nil, foreign_errs
end
end
return ok, errs
end
end
elseif field.type == "integer" then
if not (type(value) == "number"
and value == floor(value)
and value ~= 1/0
and value ~= -1/0) then
return nil, validation_errors.INTEGER
end
elseif field.type == "string" then
if type(value) ~= "string" then
return nil, validation_errors.STRING
end
-- empty strings are not accepted by default
if not field.len_min then
field.len_min = 1
end
if field.referenceable and is_reference(value) then
return true
end
elseif field.type == "function" then
if type(value) ~= "function" then
return nil, validation_errors.FUNCTION
end
elseif self.valid_types[field.type] then
if type(value) ~= field.type then
return nil, validation_errors[field.type:upper()]
end
-- if type is "any" (an internal marker), run validators only
elseif field.type ~= "any" then
return nil, validation_errors.SCHEMA_TYPE:format(field.type)
end
local validators = Schema.validators_order
for i = 1, #validators do
local k = validators[i]
if field[k] ~= nil then
local ok, err = self.validators[k](value, field[k], field)
if not ok then
if not err then
err = (validation_errors[k:upper()]
or validation_errors.VALIDATION):format(value)
end
return nil, field.err or err
end