-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathluarpc.lua
More file actions
575 lines (479 loc) · 18.1 KB
/
Copy pathluarpc.lua
File metadata and controls
575 lines (479 loc) · 18.1 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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
local table = require('table')
local socket = require('socket')
------------------------------------------------------ ERRORS ---------------------------------------------------------
errors = {
I01 = 'The provided interface file is either missing or syntatically invalid',
I02 = 'The provided interface does not have a "name" attribute',
I03 = 'The provided interface "name" attribute whose value is not of type "string"',
I04 = 'The provided interface does not have a "methods" attribute',
I05 = 'The provided interface "methods" attribute whose value is not of type "table"',
I06 = 'The provided interface "methods" attribute whose value must define at least one method',
I07 = 'The provided interface has a method without a "resulttype" attribute',
I08 = 'The provided interface has a "resulttype" attribute value that is not of type "string"',
I09 = 'The provided interface has a "resulttype" attribute value that is neither \'void\', \'char\', \'string\' nor \'double\'',
I10 = 'The provided interface has an "args" attribute whose value does not define a "direction" attribute',
I11 = 'The provided interface has a "direction" attribute whose value is not of type "string"',
I12 = 'The provided interface has a "direction" attribute whose value is neither \'in\', \'out\' nor \'inout\'',
I13 = 'The provided interface has an "args" attribute whose value does not define a "type" attribute',
I14 = 'The provided interface has a "type" attribute whose value is not of type "string"',
I15 = 'The provided interface has a "type" attribute whose value is neither \'char\', \'string\' nor \'double\'',
S01 = 'The provided definition does not implement all methods in the inferface',
S02 = 'The provided definition implements a method that is not of type "function"',
S03 = 'The provided definition implements a method that does not return the amount of values accordingly to the interface',
S04 = 'The provided definition implements a method that does not return the types accordingly to the interface',
P01 = 'The provided parameters do not match what is specified in the interface'
}
----------------------------------------------------- HELPERS ---------------------------------------------------------
local runtimeVerbosity = os.getenv('LUARPC_VERBOSITY')
local function log(type)
return function(message)
if runtimeVerbosity == 'true' then
print(type .. ': ' .. message)
end
end
end
local logInfo = log('INFO')
local logWarn = log('WARN')
local logErro = log('ERRO')
local function isType(t)
return function(value)
if t == 'char' then
return type(value) == 'string' and string.len(value) == 1
end
if t == 'double' then
return type(value) == 'number'
end
return type(value) == t
end
end
local isTable = isType('table')
local isString = isType('string')
local isFunction = isType('function')
local function hasValue(array)
return function(value)
for _, v in pairs(array) do
if v == value then return true end
end
return false
end
end
local function getTableKeys(t)
local keys = {}
for k, _ in pairs(t) do table.insert(keys, k) end
return keys
end
local function concatArrays(array1, array2)
for _, v in pairs(array2) do table.insert(array1, v) end
return array1
end
local function stringStartsWith(s, start)
return string.sub(s, 1, string.len(start)) == start
end
local function stringReplace(string, substring, newstring)
return string:gsub('(' .. substring .. ')', newstring)
end
--------------------------------------------------- MARSHALING --------------------------------------------------------
local Marshaling = {}
Marshaling._separator = '\n'
function Marshaling:_encode(string)
local encodedSeparator = '\\:-)\\'
return stringReplace(string, self._separator, encodedSeparator)
end
function Marshaling:_decode(string)
local encodedSeparator = '\\%:%-%)\\'
return stringReplace(string, encodedSeparator, self._separator)
end
function Marshaling:_marshalSegment(segment)
if isString(segment) then
return self:_encode(segment)
end
return segment
end
function Marshaling:_unmarshalSegment(segment, type)
if type == 'double' then
return tonumber(segment)
elseif type == 'string' or type == 'char' then
return self:_decode(segment)
end
return segment
end
function Marshaling:marshalRequest(method, args)
local stub = method
for _, arg in pairs(args) do
stub = stub .. self._separator .. self:_marshalSegment(arg)
end
return stub .. '\n'
end
function Marshaling:unmarshalRequest(stub, spec)
local meta = nil
local methodName = nil
local args = {}
count = 0
for segment in string.gmatch(stub, '[^' .. self._separator .. ']+') do
if count == 0 then
methodName = segment
local method = spec.methods[methodName]
if method == nil then
return false, 'couldn\'t find matching function'
else
meta = method._meta
end
else
local value = self:_unmarshalSegment(segment, meta.inTypes[count])
if value == nil then return false, 'couldn\'t unmarshal client request' end
table.insert(args, value)
end
count = count + 1
end
if count < #meta.inTypes then
return false, 'couldn\'t unmarshal client request'
end
return true, methodName, args
end
function Marshaling:marshalResponse(args)
local stub = ''
for i, arg in pairs(args) do
if i == 1 then
stub = stub .. arg
else
stub = stub .. self._separator .. self:_marshalSegment(arg)
end
end
return stub .. '\n'
end
function Marshaling:marshalErrorResponse(cause)
return '__ERRORPC: ' .. self:_encode(cause) .. '\n'
end
function Marshaling:unmarshalResponse(stub, meta)
if stringStartsWith(stub, '__ERRORPC: ') then
return false, string.sub(stub, 12)
end
local args = {}
count = 1
for segment in string.gmatch(stub, '[^' .. self._separator .. ']+') do
local value = self:_unmarshalSegment(segment, meta.outTypes[count])
if value == nil then return false, 'couldn\'t unmarshal server response' end
table.insert(args, value)
count = count + 1
end
if count - 1 < #meta.outTypes then
return false, 'couldn\'t unmarshal server response'
end
return true, args
end
---------------------------------------------------- INTERFACE --------------------------------------------------------
local prospectMemoizer
function interface(value)
prospectMemoizer = value
end
local InterfaceHandler = {}
function InterfaceHandler:_getArgTypesByDirection(args, direction)
local argTypes = {}
for _, arg in pairs(args) do
if arg.direction == direction or arg.direction == 'inout' then
table.insert(argTypes, arg.type)
end
end
return argTypes
end
function InterfaceHandler:_addMetadata(prospect, id)
prospect._id = prospect.name .. '[' .. id .. ']'
for _, method in pairs(prospect.methods) do
local inTypes = self:_getArgTypesByDirection(method.args, 'in')
local outArgTypes = self:_getArgTypesByDirection(method.args, 'out')
local outTypes = method.resulttype == 'void' and outArgTypes or concatArrays({method.resulttype}, outArgTypes)
method._meta = { inTypes = inTypes, outTypes = outTypes }
end
return prospect
end
function InterfaceHandler:_normalize(prospect)
for _, method in pairs(prospect.methods) do
if method.args == nil then method.args = {} end
end
return prospect
end
InterfaceHandler._isvalidargtype = hasValue({'char', 'string', 'double'})
InterfaceHandler._isvalidargdirection = hasValue({'in', 'out', 'inout'})
function InterfaceHandler:_validateMethodArg(arg)
assert(arg.direction, errors.I10)
assert(isString(arg.direction), errors.I11)
assert(self._isvalidargdirection(arg.direction), errors.I12)
assert(arg.type, errors.I13)
assert(isString(arg.type), errors.I14)
assert(self._isvalidargtype(arg.type), errors.I15)
end
function InterfaceHandler:_validateMethodArgs(method)
if method.args then
for _, arg in pairs(method.args) do
self:_validateMethodArg(arg)
end
end
end
InterfaceHandler._isvalidresulttype = hasValue({'void', 'char', 'string', 'double'})
function InterfaceHandler:_validateMethodResultType(method)
assert(method.resulttype, errors.I07)
assert(isString(method.resulttype), errors.I08)
assert(self._isvalidresulttype(method.resulttype), errors.I09)
end
function InterfaceHandler:_validateMethod(method)
self:_validateMethodResultType(method)
self:_validateMethodArgs(method)
end
function InterfaceHandler:_validateMethods(prospect)
assert(prospect.methods, errors.I04)
assert(isTable(prospect.methods), errors.I05)
local methodCount = 0
for _, method in pairs(prospect.methods) do
methodCount = methodCount + 1
self:_validateMethod(method)
end
assert(methodCount > 0, errors.I06)
end
function InterfaceHandler:_validateName(prospect)
assert(prospect.name, errors.I02)
assert(isString(prospect.name), errors.I03)
end
function InterfaceHandler:_validate(prospect)
self:_validateName(prospect)
self:_validateMethods(prospect)
return prospect
end
function InterfaceHandler:_parse(file)
prospectMemoizer = nil
dofile(file)
assert(isTable(prospectMemoizer), errors.I01)
return prospectMemoizer
end
function InterfaceHandler:consume(file)
return self:_addMetadata(self:_normalize(self:_validate(self:_parse(file))), file)
end
----------------------------------------------------- SERVANT ---------------------------------------------------------
local ServantBuilderSandbox = {}
ServantBuilderSandbox._inputDefaults = { double = 1, string = 'abc', char = 'c' }
function ServantBuilderSandbox:_validateOutput(returnValues, meta)
for i, otype in pairs(meta.outTypes) do
local validate = isType(otype)
if not validate(returnValues[i]) then
return false
end
end
return true
end
function ServantBuilderSandbox:_createInput(meta)
local input = {}
for _, m in pairs(meta.inTypes) do
table.insert(input, self._inputDefaults[m])
end
return input
end
function ServantBuilderSandbox:run(method, meta)
local input = self:_createInput(meta)
local success, returnVals = pcall(function() return {method(table.unpack(input))} end)
if success then
assert(#returnVals == #meta.outTypes, errors.S03)
assert(self:_validateOutput(returnVals, meta), errors.S04)
else
logWarn('One of the provided definitions might be prone to throw an error')
end
return true
end
local ServantBuilder = {}
ServantBuilder._sandbox = ServantBuilderSandbox
function ServantBuilder:validate(def, spec)
local smethodnames = getTableKeys(spec.methods)
for i = 1, #smethodnames do
local smethodname = smethodnames[i]
local dmethod = def[smethodname]
assert(dmethod ~= nil, errors.S01)
assert(isFunction(dmethod), errors.S02)
self._sandbox:run(dmethod, spec.methods[smethodname]._meta)
end
return true
end
function ServantBuilder:bind(def, id, spec, port)
local s = assert(socket.bind('*', port or '0'))
local ip, port = s:getsockname()
logInfo('Definition for "' .. id .. '" bound to "' .. ip .. ':' .. port .. '"')
return { id = id .. '@' .. port, name = spec.name, ip = ip, port = port, def = def, socket = s, spec = spec }
end
local ServantPool = {}
ServantPool._builder = ServantBuilder
ServantPool._instanceCatalog = {}
ServantPool.instances = {}
function ServantPool:_createNextVersion(id)
local version = self._instanceCatalog[id]
version = version == nil and 1 or version + 1
self._instanceCatalog[id] = version
return id .. '#' .. version
end
function ServantPool:add(def, spec, port)
self._builder:validate(def, spec)
local instance = self._builder:bind(def, self:_createNextVersion(spec._id), spec, port)
table.insert(self.instances, instance)
return instance
end
------------------------------------------------------ PROXY ----------------------------------------------------------
local ProxyFactory = {}
ProxyFactory._defaultInputTypes = { double = 1, char = 'c', string = 'string' }
function ProxyFactory:_cleanArgs(meta, args)
if isTable(args[1]) then
table.remove(args, 1)
end
for i, itype in pairs(meta.inTypes) do
if args[i] == nil then
args[i] = self._defaultInputTypes[itype]
else
local validate = isType(itype)
assert(validate(args[i]), errors.P01)
end
end
return args
end
function ProxyFactory:_createProxyMethodWrapper(name, methodMeta, s, marshaler)
return function(...)
local cleansedArgs = self:_cleanArgs(methodMeta, {...})
local reqStub = marshaler:marshalRequest(name, cleansedArgs)
bla, err = s:send(reqStub)
logInfo('Sent request')
local resStub = ''
for i = 1, #methodMeta.outTypes do
rv, err = s:receive()
if err ~= nil then
logErro('Connection with server failed (' .. err .. ')')
return err
end
resStub = resStub .. rv .. '\n'
if stringStartsWith(rv, '__ERRORPC: ') then
break
end
end
logInfo('Received response')
local success, rvs = marshaler:unmarshalResponse(resStub, methodMeta)
if not success then
return rvs
end
return nil, table.unpack(rvs)
end
end
function ProxyFactory:createProxy(ip, port, spec)
local proxy = {}
local s = assert(socket.tcp())
s:connect(ip, port)
s:settimeout(5)
for name, method in pairs(spec.methods) do
proxy[name] = self:_createProxyMethodWrapper(name, method._meta, s, Marshaling)
end
logInfo('Created proxy to ' .. ip .. ':' .. port .. ' targeting "' .. spec._id .. '"')
return proxy
end
----------------------------------------------------- AWAITER ---------------------------------------------------------
local Awaiter = {}
function Awaiter:_run(fn, args)
return pcall(function()
return {fn(table.unpack(args))}
end)
end
function Awaiter:_act(instance, s, marshaler)
local methodName, err = s:receive()
logInfo('Received method name')
if err ~= nil then
logWarn('Interrupted connection with client (' .. err .. ')')
return false, err
end
local instanceMethod = instance.spec.methods[methodName]
if instanceMethod == nil then
local err = 'Couldn\'t find a matching method for "' .. methodName .. '"'
logWarn(err)
return false, err
end
local reqStub = methodName
for i = 1, #instanceMethod._meta.inTypes do
local param, err = s:receive()
if err ~= nil then
logWarn('Interrupted connection with client (' .. err .. ')')
return false, err
end
logInfo('Received method parameter')
reqStub = reqStub .. '\n' .. param
end
logInfo('Received request')
local success, method, args = marshaler:unmarshalRequest(reqStub, instance.spec)
if not success then
logErro(method)
local errStub = marshaler:marshalErrorResponse(method)
s:send(errStub)
logInfo('Sent response')
return true, method
end
local fn = instance.def[method]
local runSuccess, rvs = self:_run(fn, args)
if runSuccess then
local resStub = marshaler:marshalResponse(rvs)
s:send(resStub)
logInfo('Sent response')
return true, nil
end
local resStub = marshaler:marshalErrorResponse(rvs)
s:send(resStub) -- TODO: verificar se tem que tratar erro
logInfo('Sent response')
return true, rvs
end
function Awaiter:_getSockets(instances)
local sockets = {}
local instanceMap = {}
for _, instance in pairs(instances) do
instance.socket:settimeout(1)
table.insert(sockets, instance.socket)
instanceMap[instance.socket] = instance
end
return sockets, instanceMap
end
function Awaiter:waitIncoming(instances, marshaler)
local sockets, instanceSocketMap = self:_getSockets(instances)
local instanceMap = {}
local listeners = {}
while true do
-- checks if there is a new connection
local recvt, sendt, err = socket.select(sockets, nil, 1)
for _, s in ipairs(recvt) do
local listener = s:accept()
table.insert(listeners, listener)
local instance = instanceSocketMap[s]
instanceMap[listener] = instance
end
-- acts on open connections
local recvtl, _, err = socket.select(listeners, nil, 1)
for _, listener in ipairs(recvtl) do
ok, cause = self:_act(instanceMap[listener], listener, marshaler)
if not ok and cause == 'closed' then
listener:close()
instanceMap[listener] = nil
end
end
end
end
-----------------------------------------------------------------------------------------------------------------------
----------------------------------------------------- EXPOSED ---------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------------
return {
createProxy = function(ip, port, file)
local spec = InterfaceHandler:consume(file)
return ProxyFactory:createProxy(ip, port, spec)
end,
createServant = function(def, file)
local spec = InterfaceHandler:consume(file)
return ServantPool:add(def, spec)
end,
waitIncoming = function()
Awaiter:waitIncoming(ServantPool.instances, Marshaling)
end,
_createServant = function(def, file, port)
local spec = InterfaceHandler:consume(file)
return ServantPool:add(def, spec, port)
end,
_interfaceHandler = InterfaceHandler,
_servantPool = ServantPool,
_proxyFactory = ProxyFactory,
_marshaling = Marshaling,
_awaiter = Awaiter
}