PsychOSPackages/ricad/service/ricad.lua

53 lines
1.3 KiB
Lua

local component = require "component"
local computer = require "computer"
local rpc = require "rpc"
local handles = {}
local timeout, pid = 30
local function prune()
for k,v in pairs(handles) do
if computer.uptime() > v.ts + timeout then
v.rq.close()
handles[k] = nil
end
end
end
function start()
-- function to keep the socket alive, will be run by long-running TCP clients
rpc.register("rica_keepalive", function(id)
assert(handles[id], "no such handle")
handles[id].ts = computer.uptime()
prune()
end)
-- create a socket object and return the ID to the client
rpc.register("rica_request", function(url, pd)
prune()
local ic = component.proxy(component.list("internet")())
local rq = ic.request(url, pd)
local rv = math.random(2^16)
handles[rv] = {rq=rq, ts=computer.uptime()}
return rv
end)
-- generate thin wrappers around the samey functions
for k,v in ipairs({"read","write","close","response","finishConnect"}) do
rpc.register("rica_"..tostring(v), function(id, ...)
prune()
assert(handles[id], "no such handle")
-- any activity should update the timestamp
handles[id].ts = computer.uptime()
return handles[id].rq[v](...)
end)
end
end
function stop()
for k,v in ipairs({"keepalive","request","connect","read","write","close","response"}) do
rpc.unregister(v)
end
end
return {start=start,stop=stop}