1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
|
-- lib/supple/request.lua
--
-- Sandbox (for) Untrusted Procedure Partitioning (in) Lua Engine
--
-- Request/response serialisation/deserialisation including contextual object
-- management and organisation.
--
-- Copyright 2012 Daniel Silverstone <dsilvers@digital-scurf.org>
--
-- For licence terms, see COPYING
--
local capi = require 'supple.capi'
local objects = require 'supple.objects'
local tconcat = table.concat
local ipairs = ipairs
local select = select
local loadstring = loadstring
local setfenv = setfenv
local function serialise_error(errstr, traceback)
return tconcat {
"error=true,",
("message=%q,"):format(errstr),
("traceback=%q"):format(traceback)
}
end
local function _serialise_object(obj, ret)
ret[#ret+1] = "{"
local comma = ""
if obj.type then
ret[#ret+1] = ("type=%q"):format(obj.type)
comma = ","
end
ret[#ret+1] = ("%stag=%q"):format(comma, obj.tag)
if obj.methods then
ret[#ret+1] = ",methods={"
comma = ""
for _, meth in ipairs(obj.methods) do
ret[#ret+1] = ("%s%q"):format(comma, meth)
comma = ","
end
ret[#ret+1] = "}"
end
ret[#ret+1] = "}"
end
local function serialise_request(obj, method, ...)
assert(capi.rawtype(obj) == "string")
assert(capi.rawtype(method) == "string")
local args = { n = select("#", ...), ... }
local ret = {
("object=%q,"):format(obj),
("method=%q,"):format(method),
("args={n=%d"):format(args.n)
}
for i = 1, args.n do
local v = objects.give(args[i])
if capi.rawtype(v) == "string" then
ret[#ret+1] = (",%q"):format(v)
elseif capi.rawtype(v) == "table" then
ret[#ret+1] = ","
_serialise_object(v, ret)
else
ret[#ret+1] = "," .. tostring(v)
end
end
ret[#ret+1] = "}"
return tconcat(ret)
end
local function serialise_response(...)
local args = { n = select("#", ...), ... }
local ret = {
"error=false,",
("results={n=%d"):format(args.n)
}
for i = 1, args.n do
local v = objects.give(args[i])
if capi.rawtype(v) == "string" then
ret[#ret+1] = (",%q"):format(v)
elseif capi.rawtype(v) == "table" then
ret[#ret+1] = ","
_serialise_object(v, ret)
else
ret[#ret+1] = "," .. tostring(v)
end
end
ret[#ret+1] = "}"
return tconcat(ret)
end
local function deserialise_entity(entity)
local str = ("return {%s}"):format(entity)
local fn = assert(loadstring(str))
setfenv(fn, {})
local res = fn()
local walk = res.args or res.results
if walk then
assert(walk.n, "Elements missing 'n'")
for i = 1, walk.n do
walk[i] = objects.receive(walk[i])
end
end
return res
end
return {
error = serialise_error,
request = serialise_request,
response = serialise_response,
deserialise = deserialise_entity,
}
|