Merge pull request #304 from nmav/ocserv-crypt
[project/luci.git] / libs / luci-lib-rpcc / luasrc / rpcc.lua
1 -- Copyright 2009 Steven Barth <steven@midlink.org>
2 -- Licensed to the public under the Apache License 2.0.
3
4 local util = require "luci.util"
5 local json = require "luci.json"
6 local ltn12 = require "luci.ltn12"
7 local nixio = require "nixio", require "nixio.util"
8
9 local tostring, assert, setmetatable = tostring, assert, setmetatable
10 local error = error
11
12 module "luci.rpcc"
13
14 RQLIMIT = 32 * nixio.const.buffersize
15
16 Client = util.class()
17
18 function Client.__init__(self, fd, v1)
19         self.fd = fd
20         self.uniqueid = tostring(self):match("0x([a-f0-9]+)")
21         self.msgid = 1
22         self.v1 = v1
23 end
24
25 function Client.request(self, method, params, notification)
26         local oldchunk = self.decoder and self.decoder.chunk
27         self.decoder = json.ActiveDecoder(self.fd:blocksource(nil, RQLIMIT))
28         self.decoder.chunk = oldchunk
29         
30         local reqid = self.msgid .. self.uniqueid
31         local reqdata = json.Encoder({
32                 id = (not notification) and (self.msgid .. self.uniqueid) or nil,
33                 jsonrpc = (not self.v1) and "2.0" or nil,
34                 method = method,
35                 params = params
36         })
37         ltn12.pump.all(reqdata:source(), self.fd:sink())
38         if not notification then
39                 self.msgid = self.msgid + 1
40                 local response = self.decoder:get()
41                 assert(response.id == reqid, "Invalid response id")
42                 if response.error then
43                         error(response.error.message or response.error)
44                 end
45                 return response.result
46         end
47 end
48
49 function Client.proxy(self, prefix)
50         prefix = prefix or ""
51         return setmetatable({}, {
52                 __call = function(proxy, ...)
53                         return self:request(prefix, {...})
54                 end,
55                 __index = function(proxy, name)
56                         return self:proxy(prefix .. name .. ".")
57                 end
58         })
59 end