Skip to content

Commit f5a1002

Browse files
committed
perf: cache the JSON schema validator
Creating a json schema validator is somewhat expensive, so we cache this step with a local LRU cache
1 parent 5dd3914 commit f5a1002

File tree

1 file changed

+32
-2
lines changed

1 file changed

+32
-2
lines changed

gateway/src/apicast/policy_config_validator.lua

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,35 @@
33
-- Validates a policy configuration against a policy config JSON schema.
44

55
local jsonschema = require('jsonschema')
6+
local lrucache = require("resty.lrucache")
67

7-
local _M = { }
8+
local cached_validator = lrucache.new(100)
9+
10+
local _M = {
11+
_VERSION=0.1
12+
}
13+
14+
local function create_validator(schema)
15+
local ok, res = pcall(jsonschema.generate_validator, schema)
16+
if ok then
17+
return res
18+
end
19+
20+
return nil, res
21+
end
22+
23+
local function get_validator(schema)
24+
local validator, err = cached_validator:get(schema)
25+
if not validator then
26+
validator, err = create_validator(schema)
27+
if not validator then
28+
return nil, err
29+
end
30+
cached_validator:set(schema, validator)
31+
end
32+
33+
return validator, nil
34+
end
835

936
--- Validate a policy configuration
1037
-- Checks if a policy configuration is valid according to the given schema.
@@ -13,7 +40,10 @@ local _M = { }
1340
-- @treturn boolean True if the policy configuration is valid. False otherwise.
1441
-- @treturn string Error message only when the policy config is invalid.
1542
function _M.validate_config(config, config_schema)
16-
local validator = jsonschema.generate_validator(config_schema or {})
43+
local validator, err = get_validator(config_schema or {})
44+
if not validator then
45+
return false, err
46+
end
1747
return validator(config or {})
1848
end
1949

0 commit comments

Comments
 (0)