From 50cb3fb5801df2c22fb4cb9c76ad5cd3803b1853 Mon Sep 17 00:00:00 2001 From: Yordan Atanasov Date: Thu, 19 Sep 2024 09:23:28 +0300 Subject: [PATCH] refactor: Remove deprecated http rpc client api export and related code. Remove LoadBalancer. Use only one node for HTTP rpc requests. Remove http.js. Other small cleanups. --- src/main/java/com/limechain/Main.java | 11 --- .../java/com/limechain/config/HostConfig.java | 9 +-- .../com/limechain/constants/RpcConstants.java | 20 +---- .../blockannounce/BlockAnnounceService.java | 6 +- .../com/limechain/rpc/ChainRpcClient.java | 7 +- .../java/com/limechain/rpc/LoadBalancer.java | 26 ------- .../java/com/limechain/rpc/RpcClient.java | 20 +---- .../java/com/limechain/teavm/HttpRequest.java | 31 ++++++-- .../com/limechain/teavm/TeaVMScheduler.java | 20 ----- .../com/limechain/utils/json/JsonUtil.java | 2 +- src/main/webapp/js/fruzhin-lib.js | 2 - src/main/webapp/js/http.js | 78 ------------------- 12 files changed, 38 insertions(+), 194 deletions(-) delete mode 100644 src/main/java/com/limechain/rpc/LoadBalancer.java delete mode 100644 src/main/java/com/limechain/teavm/TeaVMScheduler.java delete mode 100644 src/main/webapp/js/http.js diff --git a/src/main/java/com/limechain/Main.java b/src/main/java/com/limechain/Main.java index 7944a85fd..e4785feec 100644 --- a/src/main/java/com/limechain/Main.java +++ b/src/main/java/com/limechain/Main.java @@ -2,24 +2,17 @@ import com.limechain.client.HostNode; import com.limechain.client.LightClient; -import com.limechain.rpc.RPCFunction; -import com.limechain.rpc.RpcClient; import com.limechain.rpc.server.RpcApp; import com.limechain.utils.DivLogger; -import org.teavm.jso.JSBody; -import org.teavm.jso.core.JSString; import java.util.logging.Level; public class Main { - private static final String RPC_VARIABLE_NAME = "rpc"; - private static final DivLogger log = new DivLogger(); public static void main(String[] args) { log.log("Starting LimeChain node..."); - exportAPI(RpcClient::sendRpcRequest, JSString.valueOf(RPC_VARIABLE_NAME)); RpcApp rpcApp = new RpcApp(); rpcApp.start(); @@ -31,8 +24,4 @@ public static void main(String[] args) { client.start(); log.log(Level.INFO, "\uD83D\uDE80Started light client!"); } - - @JSBody(params = {"f", "apiName"}, script = "window[apiName] = f;" + - "window.fruzhin.HTTP.changeRpcExported(true);") - private static native void exportAPI(RPCFunction f, JSString apiName); } \ No newline at end of file diff --git a/src/main/java/com/limechain/config/HostConfig.java b/src/main/java/com/limechain/config/HostConfig.java index d273cff16..62d3380c2 100644 --- a/src/main/java/com/limechain/config/HostConfig.java +++ b/src/main/java/com/limechain/config/HostConfig.java @@ -5,7 +5,6 @@ import com.limechain.utils.DivLogger; import lombok.Getter; -import java.util.List; import java.util.logging.Level; /** @@ -38,9 +37,6 @@ public HostConfig() { log.log(Level.INFO, "Loading rpcNodeAddress..."); switch (chain.getValue()) { - case "POLKADOT", "LOCAL": - rpcNodeAddress = RpcConstants.POLKADOT_WS_RPC; - break; case "KUSAMA": rpcNodeAddress = RpcConstants.KUSAMA_WS_RPC; break; @@ -68,12 +64,11 @@ public String getGenesisPath() { }; } - public List getHttpsRpcEndpoints() { + public String getHttpsRpcEndpoint() { return switch (chain) { - case POLKADOT -> RpcConstants.POLKADOT_HTTPS_RPC; case KUSAMA -> RpcConstants.KUSAMA_HTTPS_RPC; case WESTEND -> RpcConstants.WESTEND_HTTPS_RPC; - case LOCAL -> List.of(); + case POLKADOT, LOCAL -> RpcConstants.POLKADOT_HTTPS_RPC; }; } } diff --git a/src/main/java/com/limechain/constants/RpcConstants.java b/src/main/java/com/limechain/constants/RpcConstants.java index c4a066f7a..b4ddd776d 100644 --- a/src/main/java/com/limechain/constants/RpcConstants.java +++ b/src/main/java/com/limechain/constants/RpcConstants.java @@ -3,27 +3,13 @@ import lombok.AccessLevel; import lombok.NoArgsConstructor; -import java.util.List; - @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class RpcConstants { public static final String POLKADOT_WS_RPC = "wss://rpc.polkadot.io"; public static final String KUSAMA_WS_RPC = "wss://kusama-rpc.polkadot.io"; public static final String WESTEND_WS_RPC = "wss://westend-rpc.polkadot.io"; - public static final List POLKADOT_HTTPS_RPC = List.of( - "https://rpc.ibp.network/polkadot", - "https://polkadot-rpc.dwellir.com", - "https://rpc.polkadot.io" - ); - public static final List KUSAMA_HTTPS_RPC = List.of( - "https://rpc.ibp.network/kusama", - "https://kusama-rpc.dwellir.com", - "https://kusama-rpc.polkadot.io" - ); - public static final List WESTEND_HTTPS_RPC = List.of( - "https://rpc.ibp.network/westend", - "https://westend-rpc.dwellir.com", - "https://westend-rpc.polkadot.io" - ); + public static final String POLKADOT_HTTPS_RPC = "https://rpc.polkadot.io"; + public static final String KUSAMA_HTTPS_RPC = "https://kusama-rpc.polkadot.io"; + public static final String WESTEND_HTTPS_RPC = "https://westend-rpc.polkadot.io"; } \ No newline at end of file diff --git a/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceService.java b/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceService.java index bc85a0b0e..024018261 100644 --- a/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceService.java +++ b/src/main/java/com/limechain/network/protocol/blockannounce/BlockAnnounceService.java @@ -6,10 +6,10 @@ import com.limechain.rpc.dto.ChainGetHeaderResult; import com.limechain.rpc.server.AppBean; import com.limechain.sync.warpsync.WarpSyncState; -import com.limechain.teavm.TeaVMScheduler; import com.limechain.utils.RpcUtils; import com.limechain.utils.Stopwatch; import lombok.extern.java.Log; +import org.teavm.jso.browser.Window; import java.util.logging.Level; @@ -46,7 +46,7 @@ public void sendHandshake() { } private static void registerFallbackRpcScheduler(Stopwatch stopwatch) { - TeaVMScheduler.schedule(() -> { + Window.setInterval(() -> new Thread(() -> { if (stopwatch.getElapsedTime() > FALLBACK_THRESHOLD) { ChainGetHeaderResult rpcResult = ChainRpcClient.getHeader(null); BlockHeader fallbackHeader = RpcUtils.toBlockHeader(rpcResult); @@ -57,6 +57,6 @@ private static void registerFallbackRpcScheduler(Stopwatch stopwatch) { " parentHash:" + fallbackHeader.getParentHash() + " stateRoot:" + fallbackHeader.getStateRoot()); } - }, 6_000); + }).start(), 6_000); } } diff --git a/src/main/java/com/limechain/rpc/ChainRpcClient.java b/src/main/java/com/limechain/rpc/ChainRpcClient.java index 1e6fcf9e5..447efc9ef 100644 --- a/src/main/java/com/limechain/rpc/ChainRpcClient.java +++ b/src/main/java/com/limechain/rpc/ChainRpcClient.java @@ -18,11 +18,8 @@ public static Hash256 getLastFinalizedBlockHash() { } public static ChainGetHeaderResult getHeader(String blockHash) { - List params = blockHash == null - ? List.of() - : List.of(blockHash); - - RpcResponse response = sendRpcRequest(RpcMethod.CHAIN_GET_HEADER, params); + RpcResponse response = sendRpcRequest(RpcMethod.CHAIN_GET_HEADER, + blockHash == null ? List.of() : List.of(blockHash)); return getResult(response, ChainGetHeaderResult.class); } } diff --git a/src/main/java/com/limechain/rpc/LoadBalancer.java b/src/main/java/com/limechain/rpc/LoadBalancer.java deleted file mode 100644 index 52ab52e8f..000000000 --- a/src/main/java/com/limechain/rpc/LoadBalancer.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.limechain.rpc; - -import com.limechain.config.HostConfig; - -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * A simple load balancer that switches between provided endpoints. Each consecutive call takes the latter endpoint - * in the provided list. - */ -public class LoadBalancer { - - private final List endpoints; - private final AtomicInteger index; - - public LoadBalancer(HostConfig hostConfig) { - this.endpoints = hostConfig.getHttpsRpcEndpoints(); - this.index = new AtomicInteger(0); - } - - public String getNextEndpoint() { - int currentIndex = index.getAndUpdate(i -> (i + 1) % endpoints.size()); - return endpoints.get(currentIndex); - } -} diff --git a/src/main/java/com/limechain/rpc/RpcClient.java b/src/main/java/com/limechain/rpc/RpcClient.java index 67ad05844..aa38d2ef2 100644 --- a/src/main/java/com/limechain/rpc/RpcClient.java +++ b/src/main/java/com/limechain/rpc/RpcClient.java @@ -21,22 +21,10 @@ public sealed class RpcClient permits ChainRpcClient, GrandpaRpcClient { private static final String POST = "POST"; + private static final String HTTP_RPC_ENDPOINT = AppBean.getBean(HostConfig.class).getHttpsRpcEndpoint(); private static final AtomicInteger ID_COUNTER = new AtomicInteger(1); - private static final LoadBalancer LOAD_BALANCER = new LoadBalancer(AppBean.getBean(HostConfig.class)); protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(false); - /** - * Send an RPC request. Currently used only by the exported RPC client. - * - * @param method {@link String} representation of the RPC method name. For example "system_name". - * @param params An array of parameters for the sent RPC request. - * @return The {@link String} representation of the received RPC json result. - */ - public static String sendRpcRequest(String method, Object[] params) { - return HttpRequest.createHttpRequest(POST, LOAD_BALANCER.getNextEndpoint(), - createRpcRequestJson(method, List.of(params))); - } - /** * Send an RPC request. Used by the specific implementations of the RpcClient. * @@ -45,8 +33,8 @@ public static String sendRpcRequest(String method, Object[] params) { * @return The {@link RpcResponse} representation of the received RPC json result. */ protected static RpcResponse sendRpcRequest(RpcMethod method, List params) { - String jsonResult = HttpRequest.createHttpRequest(POST, LOAD_BALANCER.getNextEndpoint(), - createRpcRequestJson(method.getMethod(), params)); + String jsonResult = HttpRequest.sendHttpRequest(POST, HTTP_RPC_ENDPOINT, + createRpcRequestJson(method.getMethod(), params)); return OBJECT_MAPPER.mapToClass(jsonResult, RpcResponse.class); } @@ -67,7 +55,7 @@ private static String createRpcRequestJson(String method, List params) { protected static T getResult(RpcResponse response, Class klazz) { if (response.getError() != null) { throw new IllegalStateException("RPC request resulted in an error with code:" + response.getError().getCode() - + " and message:" + response.getError().getMessage()); + + " and message:" + response.getError().getMessage()); } return OBJECT_MAPPER.mapToClass(JsonUtil.stringify(response.getResult()), klazz); diff --git a/src/main/java/com/limechain/teavm/HttpRequest.java b/src/main/java/com/limechain/teavm/HttpRequest.java index 1f3ecdef2..3d64aeaf6 100644 --- a/src/main/java/com/limechain/teavm/HttpRequest.java +++ b/src/main/java/com/limechain/teavm/HttpRequest.java @@ -11,10 +11,10 @@ public class HttpRequest { @Async - public static native String asyncHttpRequest(String method, String url, String body); + public static native String sendHttpRequest(String method, String url, String body); - private static void asyncHttpRequest(String method, String url, String body, AsyncCallback callback) { - createAsyncHttpRequest(method, url, body, (error, response) -> { + private static void sendHttpRequest(String method, String url, String body, AsyncCallback callback) { + sendHttpRequestNative(method, url, body, (error, response) -> { if (error != null) { log.log(Level.WARNING, error.getMessage()); } else { @@ -23,11 +23,26 @@ private static void asyncHttpRequest(String method, String url, String body, Asy }); } - @JSBody(params = {"method", "url", "body", "callback"}, script = "return window.fruzhin.HTTP.asyncHttpRequest(method, url, body, callback);") - public static native void createAsyncHttpRequest(String method, String url, String body, TeaVMCallback callback); - - @JSBody(params = {"method", "url", "body"}, script = "return window.fruzhin.HTTP.httpRequestSync(method, url, body);") - public static native String createHttpRequest(String method, String url, String body); + @JSBody(params = {"method", "url", "body", "callback"}, script = "fetch(" + + "url, {" + + " method: method," + + " headers: {" + + " 'Content-Type': 'application/json'}," + + " body: method === 'POST' ? body : undefined" + + "})" + + ".then(response => {" + + " if (!response.ok) {" + + " throw new Error(`Request failed with status: ${response.status}`);" + + " }" + + " return response.text();" + + "})" + + ".then(result => {" + + " callback(null, result);" + + "})" + + ".catch(error => {" + + " callback(new Error(`Error during sending request: ${error.message}`), null);" + + "});") + public static native void sendHttpRequestNative(String method, String url, String body, TeaVMCallback callback); } diff --git a/src/main/java/com/limechain/teavm/TeaVMScheduler.java b/src/main/java/com/limechain/teavm/TeaVMScheduler.java deleted file mode 100644 index 0e727ece9..000000000 --- a/src/main/java/com/limechain/teavm/TeaVMScheduler.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.limechain.teavm; - -import org.teavm.jso.JSBody; -import org.teavm.jso.JSFunctor; -import org.teavm.jso.JSObject; - -public class TeaVMScheduler { - - public static void schedule(TeaVMRunnable task, int intervalMillis) { - scheduleNative(task, intervalMillis); - } - - @JSBody(params = {"callback", "interval"}, script = "setInterval(callback, interval);") - private static native void scheduleNative(TeaVMRunnable callback, int intervalMillis); - - @JSFunctor - public interface TeaVMRunnable extends JSObject { - void run(); - } -} diff --git a/src/main/java/com/limechain/utils/json/JsonUtil.java b/src/main/java/com/limechain/utils/json/JsonUtil.java index a7f2435c4..94e6783fd 100644 --- a/src/main/java/com/limechain/utils/json/JsonUtil.java +++ b/src/main/java/com/limechain/utils/json/JsonUtil.java @@ -16,6 +16,6 @@ public static String stringify(Object object) { } public static String readJsonFromFile(String filePath) { - return HttpRequest.asyncHttpRequest("GET", filePath, null); + return HttpRequest.sendHttpRequest("GET", filePath, null); } } diff --git a/src/main/webapp/js/fruzhin-lib.js b/src/main/webapp/js/fruzhin-lib.js index f84915d2d..9567a7954 100644 --- a/src/main/webapp/js/fruzhin-lib.js +++ b/src/main/webapp/js/fruzhin-lib.js @@ -12,7 +12,6 @@ import 'https://unpkg.com/it-pb-stream@4.0.2/dist/index.min.js'; import 'https://unpkg.com/@muradsenteca/ed25519@1.0.0/dist/index.min.js' import 'https://unpkg.com/@muradsenteca/blake2b@1.0.1/dist/index.min.js' -import * as HTTP from './http.js'; import * as Fruzhin from './fruzhin.js' var startLibp2p = async (bootnodes) => { @@ -45,6 +44,5 @@ var startLibp2p = async (bootnodes) => { window.fruzhin = { startLibp2p, - HTTP, ...Fruzhin, } diff --git a/src/main/webapp/js/http.js b/src/main/webapp/js/http.js deleted file mode 100644 index fc2974484..000000000 --- a/src/main/webapp/js/http.js +++ /dev/null @@ -1,78 +0,0 @@ -async function asyncHttpRequest(method = 'GET', url, body = null, callback) { - try { - const response = await fetch(url, { - method: method, - headers: { - 'Content-Type': 'application/json' - }, - body: method === 'POST' ? body : undefined - }); - - if (!response.ok) { - callback(new Error(`Request failed with status: ${response?.status}`), null); - return; - } - - const result = await response.text(); - callback(null, result); - - } catch (error) { - callback(new Error(`Error during sending request: ${error?.message}`), null); - } -} - -function httpRequestSync(method, url, body) { - var xhr = new XMLHttpRequest(); - xhr.open(method, url, false); // false for synchronous request - xhr.setRequestHeader('Content-Type', 'application/json'); - if (method === 'POST' && body) { - xhr.send(body); - } else { - xhr.send(); - } - if (xhr.status === 200) { - return xhr.responseText; - } else { - throw new Error('Request failed with status ' + xhr.status); - } -} - -var isRpcExported = false; - -function sendRpcRequest(method, params) { - return new Promise((resolve, reject) => { - if (window.fruzhin.HTTP.getRpcExported() === false) { - window.setTimeout(async () => { - try { - const result = await sendRpcRequest(method, params); - resolve(result); - } catch (error) { - reject(error); - } - }, 10); - } else { - try { - const result = rpc.sendRequest(method, params); - resolve(result); - } catch (error) { - reject(error); - } - } - }); -} - -function changeRpcExported(newVal){ - isRpcExported = newVal; -} - -function getRpcExported(){ - return isRpcExported; -} - -export { - sendRpcRequest, - asyncHttpRequest, - httpRequestSync, - changeRpcExported, - getRpcExported -} \ No newline at end of file