Skip to content

Commit

Permalink
chore(callback): split get_callback_list to two functions to avoid un…
Browse files Browse the repository at this point in the history
…necessary table creation (#51)
  • Loading branch information
bungle authored May 21, 2024
1 parent de85a12 commit ab580f7
Showing 1 changed file with 21 additions and 24 deletions.
45 changes: 21 additions & 24 deletions lualib/resty/events/callback.lua
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,34 @@ local _M = {
local _MT = { __index = _M, }

function _M.new()
local self = {
return setmetatable({
_callbacks = {},
_funcs = {},
_counter = 0,
}

return setmetatable(self, _MT)
}, _MT)
end

local function get_callback_list(self, source, event)
local _callbacks = self._callbacks

if not _callbacks[source] then
_callbacks[source] = {}
end
return self._callbacks[source] and self._callbacks[source][event]
end

if not _callbacks[source][event] then
_callbacks[source][event] = {}
local function prepare_callback_list(self, source, event)
local callbacks = self._callbacks
if not callbacks[source] then
callbacks[source] = {
[event] = {}
}
elseif not callbacks[source][event] then
callbacks[source][event] = {}
end

return _callbacks[source][event]
return callbacks[source][event]
end

-- subscribe('*', '*', func)
-- subscribe('s', '*', func)
-- subscribe('s', 'e', func)
function _M:subscribe(source, event, callback)
local list = get_callback_list(self, source, event)
local list = prepare_callback_list(self, source, event)

local count = self._counter + 1
self._counter = count
Expand All @@ -65,20 +65,18 @@ function _M:unsubscribe(id)
end

local function do_handlerlist(funcs, list, source, event, data, wid)
local ok, err

--log(DEBUG, "source=", source, "event=", event)
if not list then
return
end

for id, _ in pairs(list) do
for id in pairs(list) do
local handler = funcs[id]

if type(handler) ~= "function" then
list[id] = nil
goto continue
end

ok, err = xpcall(handler, traceback, data, event, source, wid)

local ok, err = xpcall(handler, traceback, data, event, source, wid)
if not ok then
local str, e

Expand Down Expand Up @@ -109,13 +107,12 @@ function _M:do_event(d)
local wid = d.wid

log(DEBUG, "worker-events: handling event; source=", source,
", event=", event, ", wid=", wid)
", event=", event, ", wid=", wid)

local funcs = self._funcs
local list

-- global callback
list = get_callback_list(self, "*", "*")
local list = get_callback_list(self, "*", "*")
do_handlerlist(funcs, list, source, event, data, wid)

-- source callback
Expand Down

0 comments on commit ab580f7

Please sign in to comment.