diff --git a/lib/server.js b/lib/server.js index 30a97ab0..e42673ef 100644 --- a/lib/server.js +++ b/lib/server.js @@ -247,37 +247,15 @@ class Server { } async rpc(client, packet) { - const { id, method, args } = packet; + const { id, method } = packet; const [unitName, methodName] = method.split('/'); const [unit, ver = '*'] = unitName.split('.'); const proc = this.application.getMethod(unit, ver, methodName); if (!proc) return void client.error(404, { id }); - const context = client.createContext(); if (!client.session && proc.access !== 'public') { return void client.error(403, { id }); } - try { - await proc.enter(); - } catch { - return void client.error(503, { id }); - } - let result = null; - try { - result = await proc.invoke(context, args); - } catch (error) { - let code = error.code === 'ETIMEOUT' ? 408 : 500; - if (typeof error.code === 'number') code = error.code; - error.httpCode = code <= 599 ? code : 500; - return void client.error(code, { id, error }); - } finally { - proc.leave(); - } - if (metautil.isError(result)) { - const { code, httpCode = 200 } = result; - return void client.error(code, { id, error: result, httpCode }); - } - client.send({ type: 'callback', id, result }); - this.console.log(`${client.ip}\t${method}`); + this.handleRequest(client, packet, proc); } async stream(client, packet) { @@ -337,7 +315,13 @@ class Server { } async hook(client, proc, packet, verb, headers) { - const { id, method, args } = packet; + const { method, args, id } = packet; + const par = Object.assign(args, { method, headers, verb }); + this.handleRequest(client, { method, id, args: par }, proc); + } + + async handleRequest(client, packet, proc) { + const { id, method, args, type } = packet; if (!proc) return void client.error(404, { id }); const context = client.createContext(); try { @@ -347,10 +331,12 @@ class Server { } let result = null; try { - const par = { verb, method, args, headers }; - result = await proc.invoke(context, par); + result = await proc.invoke(context, args); } catch (error) { - client.error(500, { id, error }); + let code = error.code === 'ETIMEOUT' ? 408 : 500; + if (typeof error.code === 'number') code = error.code; + error.httpCode = code <= 599 ? code : 500; + return void client.error(code, { id, error }); } finally { proc.leave(); } @@ -358,7 +344,8 @@ class Server { const { code, httpCode = 200 } = result; return void client.error(code, { id, error: result, httpCode }); } - client.send(result); + if (type === 'call') client.send({ type: 'callback', id, result }); + else client.send(result); this.console.log(`${client.ip}\t${method}`); }