This repository was archived by the owner on Nov 20, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage.lua
More file actions
73 lines (66 loc) · 2.37 KB
/
message.lua
File metadata and controls
73 lines (66 loc) · 2.37 KB
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
-- Submodule for sending messages to remote processes.
module('concurrent._distributed._message', package.seeall)
require 'mime'
-- The existing version of this function for message sending is renamed.
_send = concurrent._message.send
-- Sends a message to local or remote processes. If the process is local the
-- old renamed version of this function is used, otherwise the message is send
-- through the network. The message is serialized and the magic cookie is also
-- attached before sent. Returns true for success and false otherwise.
function send(dest, mesg)
if type(dest) ~= 'table' then
return _send(concurrent.whereis(dest), mesg)
end
local pid, node = unpack(dest)
local socket = concurrent._distributed._network.connect(node)
if not socket then
return false
end
local data
if concurrent.getcookie() then
data = concurrent.getcookie() .. ' ' .. tostring(pid) .. ' ' ..
serialize(mesg) .. '\r\n'
else
data = tostring(pid) .. ' ' .. serialize(mesg) .. '\r\n'
end
local total = #data
repeat
local n, errmsg, _ = socket:send(data, total - #data + 1)
if not n and errmsg == 'closed' then
concurrent._distributed._network.disconnect(node)
return false
end
total = total - n
until total == 0
if concurrent.getoption('debug') then
print('-> ' .. string.sub(data, 1, #data - 2))
end
return true
end
-- Serializes an object that can be any of: nil, boolean, number, string, table,
-- function. Returns the serialized object.
function serialize(obj)
local t = type(obj)
if t == 'nil' or t == 'boolean' or t == 'number' then
return tostring(obj)
elseif t == 'string' then
return string.format("%q", obj)
elseif t == 'function' then
return 'loadstring((mime.unb64([[' .. (mime.b64(string.dump(obj))) ..
']])))'
elseif t == 'table' then
local t = '{'
for k, v in pairs(obj) do
if type(k) == 'number' or type(k) == 'boolean' then
t = t .. ' [' .. tostring(k) .. '] = ' .. serialize(v) .. ','
else
t = t .. ' ["' .. tostring(k) .. '"] = ' .. serialize(v) .. ','
end
end
t = t .. ' }'
return t
else
error('cannot serialize a ' .. t)
end
end
concurrent.send = send