diff --git a/relib.lua b/relib.lua index ca9f0d4..16eb9b9 100644 --- a/relib.lua +++ b/relib.lua @@ -14,7 +14,7 @@ return function (hostname, transmit, onRReceive, time) -- The maximum amount of timers (used to cap memory usage) local tuningMaxTimers = 0x200 - local tuningClearAntiduplicate = 120 + local tuningClearAntiduplicate = 60 local tuningAttempts = 8 local tuningAttemptTime = 4 @@ -31,7 +31,7 @@ return function (hostname, transmit, onRReceive, time) local function addTimer(trig, expi) if #timers < tuningMaxTimers then - local t = {trig, expi} + local t = {trig, time() + expi} table.insert(timers, t) return t end @@ -56,23 +56,25 @@ return function (hostname, transmit, onRReceive, time) end local onReceive = function (nfrom, nto, data) - if data:len() < 6 then return end + if data:len() < 7 then return end local port = data:byte(2) + (data:byte(1) * 256) local tp = data:byte(7) local globalId = data:sub(1, 5) if tp == 0x00 then - onRReceive(nfrom, nto, port, data, true) + onRReceive(nfrom, nto, port, data:sub(8), true) return end if nto ~= node.hostname then return end - if (tp == 0x01) and weAcked[nto .. globalId] then + if (tp == 0x01) then -- Only send one acknowledgement per packet, - -- so timers aren't generated by external packets - -- Not a perfect system but, eh. + -- but only receive the packet once. + -- (This is why timers are counted - to prevent the weAcked pool from getting too big.) + if not weAcked[nto .. globalId] then + onRReceive(nfrom, nto, port, data:sub(8), false) + end weAcked[nto .. globalId] = addTimer(function () weAcked[nto .. globalId] = nil end, tuningClearAntiduplicate) - onRReceive(nfrom, nto, port, data, false) node.output(nto, nfrom, data:sub(1, 6) .. "\x02") end if (tp == 0x02) and needsAck[nfrom .. globalId] then @@ -87,12 +89,19 @@ return function (hostname, transmit, onRReceive, time) node = culib(hostname, transmit, onReceive, time) local relib = {} + relib.setHostname = function (h) + node.hostname = h + end + relib.getHostname = function () + return node.hostname + end relib.refresh = function () node.refresh() local i = 1 local t = time() while i <= #timers do - if timers[i].expiry < t then + if timers[i][2] <= t then + timers[i][1]() table.remove(timers, i) else i = i + 1 @@ -100,7 +109,10 @@ return function (hostname, transmit, onRReceive, time) end end relib.input = node.input + -- can be reduced to output(nto, port, data) safely relib.output = function (nto, port, data, unreliable, onSucceed, onFailure) + onSucceed = onSucceed or (function () end) + onFailure = onFailure or (function () end) local gid = genGlobalId(port) if unreliable then node.output(node.hostname, nto, gid .. "\x00\x00" .. data)