Skip to content

Commit

Permalink
[resty.concurrent] safe task executor
Browse files Browse the repository at this point in the history
  • Loading branch information
mikz committed Jun 22, 2018
1 parent db9f97e commit 4a5a815
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
37 changes: 37 additions & 0 deletions gateway/src/resty/concurrent/safe_task_executor.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
local setmetatable = setmetatable
local tab_remove = table.remove
local pcall = pcall

--- @class SafeTaskExecutor
local _M = { }
local instance = setmetatable({ }, { __index = _M })

local mt = { __index = instance }

--- @param task fun(...):any
--- @return SafeTaskExecutor
function _M.new(task)
return setmetatable({ task = task }, mt)
end

function _M.execute(task, ...)
return _M.new(task):execute(...)
end

--- @return boolean, any, any|string
function instance:execute(...)
local task = self and self.task

if not task then return nil, 'not initialized' end

local ret = { pcall(task, ...) }
local ok = tab_remove(ret, 1)

if ok then
return true, ret
else
return false, nil, ret[1]
end
end

return _M
24 changes: 24 additions & 0 deletions spec/resty/concurrent/safe_task_executor_spec.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
local SafeTaskExecutor = require('resty.concurrent.safe_task_executor')

describe('SafeTaskExecutor', function()
it('has module level execute', function()
local task = spy.new(function () end)

SafeTaskExecutor.execute(task)

assert.spy(task).was_called(1)
end)

it('returns success', function()
local task = SafeTaskExecutor.new(function () return 'some value', 'some other value' end)

assert.same({true, { 'some value', 'some other value' }}, { task:execute() })
end)

it('returns failure', function ()
local task = SafeTaskExecutor.new(function () return error('some error') end)

assert.same({false, nil, 'some error'}, { task:execute() })
end)

end)

0 comments on commit 4a5a815

Please sign in to comment.