summaryrefslogtreecommitdiff
path: root/script-beta/jsonrpc.lua
blob: 4dda6fb0588dd32aca65c969969d43484440814a (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
local json  = require 'json'
local pcall = pcall
local tonumber = tonumber
local log = require 'brave.log'

_ENV = nil

---@class jsonrpc
local m = {}
m.type = 'jsonrpc'

function m.encode(pack)
    pack.jsonrpc = '2.0'
    local content = json.encode(pack)
    local buf = ('Content-Length: %d\r\n\r\n%s'):format(#content, content)
    return buf
end

local function readProtoHead(reader, errHandle)
    local head = {}
    while true do
        local line = reader 'L'
        if line == '\r\n' then
            break
        else
            local k, v = line:match '^([^:]+)%s*%:%s*(.+)\r\n$'
            if k then
                if k == 'Content-Length' then
                    v = tonumber(v)
                end
                head[k] = v
            else
                errHandle('Proto header error:', head)
                break
            end
        end
    end
    return head
end

function m.decode(reader, errHandle)
    local head = readProtoHead(reader, errHandle)
    local len = head['Content-Length']
    if not len then
        errHandle('Proto header error:', head)
        return nil
    end
    local content = reader(len)
    if not content then
        return nil
    end
    local suc, res = pcall(json.decode, content)
    if not suc then
        errHandle('Proto parse error: ' .. res)
        return nil
    end
    return res
end

return m