-
Notifications
You must be signed in to change notification settings - Fork 170
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[resty.concurrent] safe task executor
- Loading branch information
Showing
2 changed files
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |