poppy-server/rpc.lua

54 lines
1.4 KiB
Lua

local rpc = {
PROTOCOL_VERSION = "001"
}
function rpc.parse(msg)
local fields = {}
for field in msg:gmatch("[^\31]+") do
fields[#fields + 1] = field
end
local prot_version = fields[1]:match("^poppyV(%d+)")
if not prot_version then error("invalid protocol version") end
if prot_version ~= rpc.PROTOCOL_VERSION then error("unsupported protocol version " .. prot_version) end
local client_id = fields[2]:match("^ID(%d+)")
if not client_id then error("invalid message, missing client id") end
return {
version = prot_version,
client_id = client_id,
request = {unpack(fields, 3, #fields)}
}
end
function rpc.parse_multiple(msg)
local requests = {}
for record in msg:gmatch("[^\30]+") do
table.insert(requests, rpc.parse(record))
end
return requests
end
function rpc.eval(command_table, rpc_request)
local rpc_function = command_table
local rpc_args = {}
for i, cmd in ipairs(rpc_request.request) do
if rpc_function[cmd] then
rpc_function = rpc_function[cmd]
else
rpc_args = {unpack(rpc_request.request, i, #rpc_request.request)}
break
end
end
if type(rpc_function) ~= "function" then
error("received unknown command: " .. table.concat(rpc_request.request, ", "))
rpc_function = nil
end
return rpc_function(unpack(rpc_args))
end
return rpc