From 4a037387e9f161d0ab154cda5ad39c32c04338e6 Mon Sep 17 00:00:00 2001 From: Mikunj Date: Mon, 18 Feb 2019 11:37:06 +1100 Subject: [PATCH 1/2] Refactor rpc calls to its own function. --- js/modules/loki_message_api.js | 88 ++++++++++++++++------------------ 1 file changed, 42 insertions(+), 46 deletions(-) diff --git a/js/modules/loki_message_api.js b/js/modules/loki_message_api.js index b68a65d97..4ca1ab6ed 100644 --- a/js/modules/loki_message_api.js +++ b/js/modules/loki_message_api.js @@ -57,6 +57,28 @@ const fetch = async (url, options = {}) => { } }; +// Wrapper for a JSON RPC request +const rpc = (address, port, method, params, options = {}) => { + const headers = options.headers || {}; + const url = `${address}${port}${endpointBase}`; + const body = { + method, + params, + }; + + const fetchOptions = { + method: 'POST', + ...options, + body: JSON.stringify(body), + headers: { + 'X-Loki-EphemKey': 'not implemented yet', + ...headers, + }, + }; + + return fetch(url, fetchOptions); +}; + // Will be raised (to 3?) when we get more nodes const MINIMUM_SUCCESSFUL_REQUESTS = 2; @@ -69,22 +91,13 @@ class LokiMessageAPI { const data64 = dcodeIO.ByteBuffer.wrap(data).toString('base64'); const timestamp = Math.floor(Date.now() / 1000); const p2pDetails = lokiP2pAPI.getContactP2pDetails(pubKey); - const body = { - method: 'store', - params: { - data: data64, - }, - }; if (p2pDetails && (isPing || p2pDetails.isOnline)) { try { const port = p2pDetails.port ? `:${p2pDetails.port}` : ''; - const url = `${p2pDetails.address}${port}${endpointBase}`; - const fetchOptions = { - method: 'POST', - body: JSON.stringify(body), - }; - await fetch(url, fetchOptions); + await rpc(p2pDetails.address, port, 'store', { + data: data64, + }); lokiP2pAPI.setContactOnline(pubKey); return; } catch (e) { @@ -117,16 +130,6 @@ class LokiMessageAPI { // Something went horribly wrong throw err; } - const storageParams = { - pubKey, - ttl: ttl.toString(), - nonce, - timestamp: timestamp.toString(), - }; - body.params = { - ...body.params, - ...storageParams, - }; const completedNodes = []; const failedNodes = []; @@ -141,17 +144,16 @@ class LokiMessageAPI { }; const doRequest = async nodeUrl => { - const url = `${nodeUrl}${this.messageServerPort}${endpointBase}`; - const fetchOptions = { - method: 'POST', - body: JSON.stringify(body), - headers: { - 'X-Loki-EphemKey': 'not implemented yet', - }, + const params = { + pubKey, + ttl: ttl.toString(), + nonce, + timestamp: timestamp.toString(), + data: data64, }; try { - await fetch(url, fetchOptions); + await rpc(nodeUrl, this.messageServerPort, 'store', params); nodeComplete(nodeUrl); successfulRequests += 1; @@ -233,24 +235,18 @@ class LokiMessageAPI { }; const doRequest = async (nodeUrl, nodeData) => { - const url = `${nodeUrl}${this.messageServerPort}${endpointBase}`; - const body = { - method: 'retrieve', - params: { - pubKey: ourKey, - lastHash: nodeData.lastHash, - }, - }; - const headers = { - 'X-Loki-EphemKey': 'not implemented yet', - }; - const fetchOptions = { - method: 'POST', - body: JSON.stringify(body), - headers, + const params = { + pubKey: ourKey, + lastHash: nodeData.lastHash, }; + try { - const result = await fetch(url, fetchOptions); + const result = await rpc( + nodeUrl, + this.messageServerPort, + 'retrieve', + params + ); nodeComplete(nodeUrl); From 429bdd64602e4a5627a9c31248614d8517fd8db0 Mon Sep 17 00:00:00 2001 From: Mikunj Date: Fri, 22 Feb 2019 11:30:02 +1100 Subject: [PATCH 2/2] Refactor local_loki_server --- libloki/modules/local_loki_server.js | 81 ++++++++++++++++------------ 1 file changed, 48 insertions(+), 33 deletions(-) diff --git a/libloki/modules/local_loki_server.js b/libloki/modules/local_loki_server.js index 951db7dab..4d18a25c3 100644 --- a/libloki/modules/local_loki_server.js +++ b/libloki/modules/local_loki_server.js @@ -1,6 +1,14 @@ const http = require('http'); const EventEmitter = require('events'); +const STATUS = { + OK: 200, + BAD_REQUEST: 400, + NOT_FOUND: 404, + METHOD_NOT_ALLOWED: 405, + INTERNAL_SERVER_ERROR: 500, +}; + class LocalLokiServer extends EventEmitter { /** * Creates an instance of LocalLokiServer. @@ -11,47 +19,54 @@ class LocalLokiServer extends EventEmitter { this.server = http.createServer((req, res) => { let body = []; + const sendResponse = (statusCode, message = null) => { + const headers = message && { + 'Content-Type': 'text/plain', + }; + res.writeHead(statusCode, headers); + res.end(message); + }; + + if (req.method !== 'POST') { + sendResponse(STATUS.METHOD_NOT_ALLOWED); + return; + } + // Check endpoints - if (req.method === 'POST') { - req - .on('error', () => { - // Internal server error - res.statusCode = 500; - res.end(); - }) - .on('data', chunk => { - body.push(chunk); - }) - .on('end', () => { - try { - body = Buffer.concat(body).toString(); - } catch (e) { - // Error occurred while converting to string - res.statusCode = 500; - res.end(); - } + req + .on('error', () => { + // Internal server error + sendResponse(STATUS.INTERNAL_SERVER_ERROR); + }) + .on('data', chunk => { + body.push(chunk); + }) + .on('end', () => { + try { + body = Buffer.concat(body).toString(); + } catch (e) { + // Internal server error: failed to convert body to string + sendResponse(STATUS.INTERNAL_SERVER_ERROR); + } - // Check endpoints here - if (req.url === '/v1/storage_rpc') { + // Check endpoints here + if (req.url === '/v1/storage_rpc') { + try { const bodyObject = JSON.parse(body); if (bodyObject.method !== 'store') { - res.writeHead(404, { 'Content-Type': 'text/plain' }); - res.end('Invalid endpoint!'); + sendResponse(STATUS.NOT_FOUND, 'Invalid endpoint!'); return; } this.emit('message', bodyObject.params.data); - res.statusCode = 200; - res.end(); - } else { - res.writeHead(404, { 'Content-Type': 'text/plain' }); - res.end('Invalid endpoint!'); + sendResponse(STATUS.OK); + } catch (e) { + // Bad Request: Failed to decode json + sendResponse(STATUS.BAD_REQUEST, 'Failed to decode JSON'); } - }); - } else { - // Method Not Allowed - res.statusCode = 405; - res.end(); - } + } else { + sendResponse(STATUS.NOT_FOUND, 'Invalid endpoint!'); + } + }); }); }