summaryrefslogtreecommitdiff
path: root/server/src/rpc.lua
blob: 99136a0a98b26bf64d963a7d342634189b0ba0a7 (plain)
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
local json = require 'json'

local TIMEOUT = 1.0

local ID = 0
local BUF = {}

local function notify(self, method, params)
    local pack = {
        jsonrpc = '2.0',
        method = method,
        params = params,
    }
    local content = json.encode(pack)
    local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
    io.write(buf)
end

local function request(self, method, params, callback)
    ID = ID + 1
    local pack = {
        jsonrpc = '2.0',
        id = ID,
        method = method,
        params = params,
    }
    local content = json.encode(pack)
    local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
    BUF[ID] = {
        callback = callback,
        timeout = os.clock() + TIMEOUT,
    }
    io.write(buf)
end

local function response(self, id, data)
    data.jsonrpc = '2.0'
    data.id = id
    local content = json.encode(data)
    local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
    io.write(buf)
end

local function recieve(self, proto)
    local id = proto.id
    local data = BUF[id]
    if not data then
        log.warn('Recieve id not found: ', table.dump(proto))
        return
    end
    BUF[id] = nil
    if os.clock() > data.timeout then
        log.warn('Recieve timeout: ', table.dump(proto.error))
        return
    end
    if proto.error then
        log.warn('Recieve: ', table.dump(proto.error))
        return
    end
    data.callback(proto.result)
end

return {
    notify   = notify,
    request  = request,
    response = response,
    recieve  = recieve,
}