From 8a9202e826169f688b2dbb271e3a2b587c347a73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=80=E8=90=8C=E5=B0=8F=E6=B1=90?= Date: Fri, 20 Sep 2019 14:39:11 +0800 Subject: =?UTF-8?q?=E5=AE=8C=E6=95=B4=E7=9A=84proto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server-beta/src/proto/proto.lua | 59 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 53 insertions(+), 6 deletions(-) (limited to 'server-beta/src') diff --git a/server-beta/src/proto/proto.lua b/server-beta/src/proto/proto.lua index d35d76ba..cc9988a8 100644 --- a/server-beta/src/proto/proto.lua +++ b/server-beta/src/proto/proto.lua @@ -5,12 +5,19 @@ local pub = require 'pub' local jsonrpc = require 'jsonrpc' local ErrorCodes = require 'define.ErrorCodes' +local reqCounter = util.counter() + local m = {} m.ability = {} +m.waiting = {} -local function isOptionalMethod(method) - return method:sub(1, 2) == '$/' +function m.getMethodName(proto) + if proto.method:sub(1, 2) == '$/' then + return proto.method:sub(3), true + else + return proto.method, false + end end function m.on(method, callback) @@ -37,11 +44,32 @@ function m.responseErr(id, code, message) io.stdout:write(buf) end -function m.doProto(proto) - local method = proto.method +function m.notify(name, params) + local buf = jsonrpc.encode { + method = name, + params = params, + } + io.stdout:write(buf) +end + +function m.request(name, params) + local id = reqCounter() + local buf = jsonrpc.encode { + id = id, + method = name, + params = params, + } + io.stdout:write(buf) + return task.wait(function (waker) + m.waiting[id] = waker + end) +end + +function m.doMethod(proto) + local method, optional = m.getMethodName(proto) local abil = m.ability[method] if not abil then - if not isOptionalMethod(method) then + if not optional then log.warn('Recieved unknown proto: ' .. method) end if proto.id then @@ -64,6 +92,21 @@ function m.doProto(proto) end) end +function m.doResponse(proto) + local id = proto.id + local waker = m.waiting[id] + if not waker then + log.warn('Response id not found: ' .. util.dump(proto)) + return + end + m.waiting[id] = nil + if proto.error then + log.warn(('Response error [%d]: %s'):format(proto.error.code, proto.error.message)) + return + end + waker(proto.result) +end + function m.listen() subprocess.filemode(io.stdin, 'b') subprocess.filemode(io.stdout, 'b') @@ -72,7 +115,11 @@ function m.listen() task.create(function () while true do local proto = pub.task('loadProto') - m.doProto(proto) + if proto.method then + m.doMethod(proto) + else + m.doResponse(proto) + end end end) end -- cgit v1.2.3