Skip to content

Commit

Permalink
更好的 API 架構
Browse files Browse the repository at this point in the history
  • Loading branch information
eric2788 committed May 11, 2022
1 parent 7389262 commit 5087069
Show file tree
Hide file tree
Showing 11 changed files with 48 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
import javax.annotation.Nullable;
import javax.inject.Named;
import java.io.IOException;
import java.net.ConnectException;
import java.net.http.HttpTimeoutException;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
Expand All @@ -32,11 +30,12 @@ public final class OkHttpRequester implements RPCRequester {
private @Nullable String serviceName;

@Override
public void initialize(RPCInfo client) {
public CompletableFuture<Void> initialize(RPCInfo client) {
this.serviceName = client.serviceName();
this.hosts = client.fallbackHosts();
// insert main host as first
this.hosts.add(0, new RPCInfo.FallbackHost(client.host(), client.useTLS(), client.authToken()));
return CompletableFuture.completedFuture(null);
}

public Object invokeRequest(RPCPayload payload, RPCInfo.FallbackHost host) throws Exception {
Expand Down Expand Up @@ -69,7 +68,7 @@ public Object invokeRequest(RPCPayload payload, RPCInfo.FallbackHost host) throw


@Override
public CompletableFuture<Object> offerRequest(RPCPayload payload) throws Exception {
public CompletableFuture<Object> offerRequest(RPCPayload payload) {
CompletableFuture<Object> future = new CompletableFuture<>();

for (RPCInfo.FallbackHost host : this.hosts) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import okhttp3.*;
import okhttp3.internal.ws.RealWebSocket;
import okio.ByteString;
import org.bukkit.Bukkit;
import org.eldependenci.rpc.context.*;
import org.eldependenci.rpc.protocol.RPCRequester;

Expand All @@ -20,7 +19,6 @@
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
Expand Down Expand Up @@ -55,21 +53,13 @@ public OkWebSocketRequester(LoggingService loggingService) {
private RPCInfo info;

@Override
public void initialize(RPCInfo client) {
public CompletableFuture<Void> initialize(RPCInfo client) {
this.info = client;
this.serviceName = client.serviceName();
this.hosts = client.fallbackHosts();
hosts.add(new RPCInfo.FallbackHost(client.host(), client.useTLS(), client.authToken()));
/*
launchWebSockets(iterator, client.locate()).whenComplete((v, ex) -> {
if (ex != null) {
logger.warn(ex, "Error while launching service {0}: {1}", client.locate(), ex.getMessage());
}
});
*/

httpClient.connectionPool().evictAll();
return launchWebSockets(hosts.iterator(), client.locate());
}


Expand Down Expand Up @@ -162,7 +152,7 @@ public void onMessage(WebSocket webSocket, ByteString bytes) {
}

@Override
public CompletableFuture<Object> offerRequest(RPCPayload payload) throws Exception {
public CompletableFuture<Object> offerRequest(RPCPayload payload) {
var previousFuture = webSocket == null ? launchWebSockets(hosts.iterator(), info.locate()).thenApply(v -> null) : CompletableFuture.completedFuture(null);
return previousFuture.thenCompose(v -> {
var future = new CompletableFuture<Object>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
package org.eldependenci.rpc.remote;

import org.eldependenci.rpc.config.RPCConfig;
import org.eldependenci.rpc.context.RPCInfo;
import org.eldependenci.rpc.context.RPCPayload;
import org.eldependenci.rpc.protocol.RPCRequester;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;

public class RemoteInvocationHandler implements InvocationHandler {

private final RPCRequester requester;

private final Class<?> service;
private final RequesterManager requesterManager;

private final String serviceName;
Expand All @@ -23,7 +21,7 @@ public RemoteInvocationHandler(
RequesterManager requesterManager
) {
this.requesterManager = requesterManager;
this.requester = requesterManager.getRequester(service);
this.service = service;
var rpcInfo = requesterManager.findInfo(service);
this.serviceName = rpcInfo.map(RPCInfo::serviceName).orElse(service.getSimpleName());
this.token = rpcInfo.map(RPCInfo::authToken).orElse("");
Expand All @@ -36,8 +34,9 @@ public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl
} else {
args = args != null ? args : new String[0];
var id = System.nanoTime();
var payload = new RPCPayload(id, method.getName(), serviceName, args, token);
var future = this.requester.offerRequest(payload);
var payload = new RPCPayload(id, method.getName(), serviceName, args, token);

var future = requesterManager.getRequester(service).thenCompose(requester -> requester.offerRequest(payload));
return requesterManager.handleFuture(future, method.getGenericReturnType());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,6 @@ public final class RemoteManager {
@Inject
private RequesterManager requestManager;

@Inject
private RPCConfig config;

public <T> T getRemoteService(Class<T> service) {
return (T) Optional.ofNullable(proxyMap.get(service)).orElseGet(() -> createService(service));
}
Expand All @@ -39,7 +36,6 @@ private <T> T createService(Class<T> service) {

public <T> T createServiceDynamically(Class<T> service, RPCInfo info) {
var serviceName = Optional.ofNullable(info.serviceName()).orElse(service.getSimpleName());
var requester = requestManager.getRequesterDynamically(info);
return (T) Proxy.newProxyInstance(
service.getClassLoader(),
new Class[]{service},
Expand All @@ -50,7 +46,7 @@ public <T> T createServiceDynamically(Class<T> service, RPCInfo info) {
args = args != null ? args : new String[0];
var id = System.nanoTime();
var payload = new RPCPayload(id, method.getName(), serviceName, args, info.authToken());
var future = requester.offerRequest(payload);
var future = requestManager.getRequesterDynamically(info).thenCompose(requester -> requester.offerRequest(payload));
return this.requestManager.handleFuture(future, method.getGenericReturnType());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,17 +60,16 @@ public Optional<RPCInfo> findInfo(Class<?> service) {
.findAny();
}

public RPCRequester getRequesterDynamically(RPCInfo info) {
public CompletableFuture<RPCRequester> getRequesterDynamically(RPCInfo info) {
var requester = this.requesterMap.get(info.protocol());
if (requester == null) {
throw new IllegalArgumentException("Protocol " + info.protocol() + " is not supported");
}
var ins = injector.getInstance(requester);
ins.initialize(info);
return ins;
return ins.initialize(info).thenApply(v -> ins);
}

public RPCRequester getRequester(Class<?> service) {
public CompletableFuture<RPCRequester> getRequester(Class<?> service) {

var info = findInfo(service).orElseThrow(() -> new IllegalStateException("Can't find remote config for " + service.getName() + ", have you defined it on remotes.yml?"));

Expand All @@ -80,12 +79,17 @@ public RPCRequester getRequester(Class<?> service) {
if (instances == null) {
throw new IllegalArgumentException("Protocol " + protocol + " is not supported");
}
return Optional.ofNullable(instances.get(service)).orElseGet(() -> {
var requester = this.requesterMap.get(protocol);
var ins = injector.getInstance(requester);
ins.initialize(info);
instances.put(service, ins);
return ins;

var ins = instances.get(service);
if (ins != null){
return CompletableFuture.completedFuture(ins);
}

var requester = this.requesterMap.get(protocol);
var newIns = injector.getInstance(requester);
return newIns.initialize(info).thenApply(v -> {
instances.put(service, newIns);
return newIns;
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@
@Target(ElementType.TYPE)
public @interface BaseURL {

/**
* URL
* @return URL
*/
String value();

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,27 @@ public class RPCException extends Exception {

private final long id;
private final Exception real;

/**
* 建構子
* @param id 追蹤 ID
* @param e 真正的錯誤
*/
public RPCException(long id, Exception e) {
this.real = e;
this.id = id;
}

/**
*
* 返回 真正的錯誤
* @return 真正的錯誤
*/
public Exception getReal() {
return real;
}

/**
*
* 返回 追蹤 ID
* @return 追蹤 ID
*/
public long getId() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
public class RPCUnauthorizedException extends RPCException {

/**
*
* 認證 token 授權錯誤
* @param id 追蹤 ID
* @param e 原本錯誤
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,17 @@ public interface RPCRequester {

/**
* 初始化 請求接口 (基於 Remote 服務)
*
* @param client RPC 資訊
* @return 異步初始化
*/
void initialize(RPCInfo client);
CompletableFuture<Void> initialize(RPCInfo client);

/**
* 執行 RPC 請求
* @param payload RPC 請求內容協定
* @return RPC 回應
* @throws Exception 請求錯誤
*/
CompletableFuture<Object> offerRequest(RPCPayload payload) throws Exception;
CompletableFuture<Object> offerRequest(RPCPayload payload);

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ public interface ServiceHandler {

/**
* 異步處理 payload
* <p />
* 此方式將包含使用 {@link #toFuture(RPCPayload)}, {@link #invokes(RPCPayload)} 和 {@link #finalizeType(Object, Type)},
* <p>
* 此方式將包含使用 {@link #toFuture(RPCPayload, boolean)}, {@link #invokes(RPCPayload)} 和 {@link #finalizeType(Object, Type)},
* 且自帶 BukkitPromise 轉換功能
* @param rpcPayload 請求資料
* @param debug 是否啟用除錯, 若是,則會填入 {@link RPCError#errors() } 參數
Expand Down
3 changes: 2 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,7 @@
</links>
<show>public</show>
<isOffline>false</isOffline>
<failOnWarnings>false</failOnWarnings>
<linksource>true</linksource>
<encoding>UTF-8</encoding>
<windowtitle>ELDependenci-Addon</windowtitle>
Expand All @@ -150,7 +151,7 @@
<version>true</version>
<linksource>true</linksource>
<notimestamp>true</notimestamp>
<bottom><![CDATA[<b>© ELDependenci - 2020</b>]]></bottom>
<bottom><![CDATA[<b>© ELDependenci-RPC - 2022</b>]]></bottom>
<reportOutputDirectory>${project.build.directory}</reportOutputDirectory>
<outputDirectory>../javadocs</outputDirectory>
<detectJavaApiLink>true</detectJavaApiLink>
Expand Down

0 comments on commit 5087069

Please sign in to comment.