Skip to content

Commit

Permalink
[sandbox] sandbox cache
Browse files Browse the repository at this point in the history
Loading policy multiple times returns the same instance.
  • Loading branch information
mikz committed Jun 18, 2018
1 parent c588b33 commit f64fadb
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 5 deletions.
8 changes: 7 additions & 1 deletion gateway/src/apicast/policy_loader.lua
Original file line number Diff line number Diff line change
Expand Up @@ -131,11 +131,17 @@ function _M:load_path(name, version, paths)
return nil, nil, failures
end

local package_cache = setmetatable({}, {
__index = function(t, k) local n = { }; t[k] = n; return n end
})

function _M:call(name, version, dir)
local v = version or 'builtin'
local load_path, policy_config_schema, invalid_paths = self:load_path(name, v, dir)

local loader = sandbox.new(load_path and { load_path } or invalid_paths)
local cache = package_cache[table.concat({name, v, dir}, '-')]
local loader = sandbox.new(load_path and { load_path } or invalid_paths,
cache)

ngx.log(ngx.DEBUG, 'loading policy: ', name, ' version: ', v)

Expand Down
6 changes: 3 additions & 3 deletions gateway/src/resty/sandbox.lua
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ local function gen_require(package)
-- to determine whether modname is already loaded.
-- NOTE: this is different from the spec: use the top level package.loaded,
-- otherwise it would try to sandbox load already loaded shared code
local mod = root_loaded[modname]
local mod = root_loaded[modname] or package.loaded[modname]

-- If it is, then require returns the value stored at package.loaded[modname].
if mod then return mod end
Expand Down Expand Up @@ -211,10 +211,10 @@ local mt = {

local empty_t = {}

function _M.new(load_paths)
function _M.new(load_paths, cache)
-- need to create global variable package that mimics the native one
local package = {
loaded = {},
loaded = cache or {},
preload = preload,
searchers = {}, -- http://www.lua.org/manual/5.2/manual.html#pdf-package.searchers
searchpath = searchpath,
Expand Down
2 changes: 1 addition & 1 deletion spec/policy_loader_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ describe('APIcast Policy Loader', function()
assert.are_not.same(test, test2)

assert.are.same(test.dependency, test2.dependency)
assert.are_not.equal(test.dependency, test2.dependency)
assert.are.equal(test.dependency, test2.dependency)
end)

it('loads two versions of the same policy', function()
Expand Down

0 comments on commit f64fadb

Please sign in to comment.