tdlib-session-container/src/main/java/it/tdlight/tdlibsession/td/middle/client/AsyncTdMiddleEventBusClient...

220 lines
8.6 KiB
Java
Raw Normal View History

package it.tdlight.tdlibsession.td.middle.client;
2020-10-17 18:28:54 +02:00
import io.vertx.core.eventbus.DeliveryOptions;
2021-01-24 19:13:46 +01:00
import io.vertx.core.json.JsonObject;
2021-01-23 18:49:21 +01:00
import io.vertx.reactivex.core.Vertx;
2021-01-22 17:31:09 +01:00
import io.vertx.reactivex.core.eventbus.Message;
2021-01-23 22:33:52 +01:00
import io.vertx.reactivex.core.eventbus.MessageConsumer;
import it.tdlight.jni.TdApi;
import it.tdlight.jni.TdApi.Function;
import it.tdlight.tdlibsession.td.ResponseError;
2021-01-23 18:49:21 +01:00
import it.tdlight.tdlibsession.td.TdError;
import it.tdlight.tdlibsession.td.TdResult;
import it.tdlight.tdlibsession.td.TdResultMessage;
import it.tdlight.tdlibsession.td.middle.AsyncTdMiddle;
2021-01-23 22:33:52 +01:00
import it.tdlight.tdlibsession.td.middle.EndSessionMessage;
import it.tdlight.tdlibsession.td.middle.ExecuteObject;
2021-01-23 18:49:21 +01:00
import it.tdlight.tdlibsession.td.middle.StartSessionMessage;
import it.tdlight.tdlibsession.td.middle.TdClusterManager;
import it.tdlight.tdlibsession.td.middle.TdResultList;
2021-01-23 18:49:21 +01:00
import it.tdlight.utils.BinlogAsyncFile;
import it.tdlight.utils.BinlogUtils;
import it.tdlight.utils.MonoUtils;
2021-01-23 18:49:21 +01:00
import it.tdlight.utils.MonoUtils.SinkRWStream;
import java.nio.file.Path;
2021-01-24 03:15:45 +01:00
import java.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
2021-01-22 17:31:09 +01:00
import reactor.core.publisher.Sinks.Empty;
2021-01-22 12:25:04 +01:00
import reactor.core.publisher.Sinks.One;
2021-01-19 03:18:00 +01:00
import reactor.core.scheduler.Schedulers;
2021-01-23 18:49:21 +01:00
public class AsyncTdMiddleEventBusClient implements AsyncTdMiddle {
2021-01-23 18:49:21 +01:00
private Logger logger;
public static final byte[] EMPTY = new byte[0];
2021-01-22 17:31:09 +01:00
private final TdClusterManager cluster;
2020-10-17 18:28:54 +02:00
private final DeliveryOptions deliveryOptions;
private final DeliveryOptions deliveryOptionsWithTimeout;
2021-01-23 18:49:21 +01:00
private final One<BinlogAsyncFile> binlog = Sinks.one();
2021-01-24 03:15:45 +01:00
SinkRWStream<Message<TdResultList>> updates = MonoUtils.unicastBackpressureStream(10000);
2021-01-23 18:49:21 +01:00
// This will only result in a successful completion, never completes in other ways
private final Empty<Void> updatesStreamEnd = Sinks.one();
// This will only result in a crash, never completes in other ways
private final Empty<Void> crash = Sinks.one();
private int botId;
private String botAddress;
private String botAlias;
private boolean local;
public AsyncTdMiddleEventBusClient(TdClusterManager clusterManager) {
2021-01-23 18:49:21 +01:00
this.logger = LoggerFactory.getLogger(AsyncTdMiddleEventBusClient.class);
this.cluster = clusterManager;
2020-10-17 18:28:54 +02:00
this.deliveryOptions = cluster.newDeliveryOpts().setLocalOnly(local);
this.deliveryOptionsWithTimeout = cluster.newDeliveryOpts().setLocalOnly(local).setSendTimeout(30000);
}
2021-01-22 17:31:09 +01:00
public static Mono<AsyncTdMiddle> getAndDeployInstance(TdClusterManager clusterManager,
2021-01-23 18:49:21 +01:00
int botId,
2021-01-22 17:31:09 +01:00
String botAlias,
2021-01-23 18:49:21 +01:00
boolean local,
2021-01-24 19:13:46 +01:00
JsonObject implementationDetails,
2021-01-23 18:49:21 +01:00
Path binlogsArchiveDirectory) {
2021-01-22 17:31:09 +01:00
var instance = new AsyncTdMiddleEventBusClient(clusterManager);
2021-01-23 18:49:21 +01:00
return retrieveBinlog(clusterManager.getVertx(), binlogsArchiveDirectory, botId)
2021-01-23 22:33:52 +01:00
.flatMap(binlog -> binlog
.getLastModifiedTime()
.filter(modTime -> modTime == 0)
.doOnNext(v -> LoggerFactory
.getLogger(AsyncTdMiddleEventBusClient.class)
.error("Can't retrieve binlog of bot " + botId + " " + botAlias + ". Creating a new one..."))
.thenReturn(binlog)
)
.<AsyncTdMiddle>flatMap(binlog -> instance
2021-01-24 19:13:46 +01:00
.start(botId, botAlias, local, implementationDetails, binlog)
2021-01-23 18:49:21 +01:00
.thenReturn(instance)
2021-01-23 22:33:52 +01:00
)
.single();
}
2021-01-23 18:49:21 +01:00
/**
*
* @return optional result
*/
public static Mono<BinlogAsyncFile> retrieveBinlog(Vertx vertx, Path binlogsArchiveDirectory, int botId) {
return BinlogUtils.retrieveBinlog(vertx.fileSystem(), binlogsArchiveDirectory.resolve(botId + ".binlog"));
}
2021-01-23 18:49:21 +01:00
private Mono<Void> saveBinlog(byte[] data) {
return this.binlog.asMono().flatMap(binlog -> BinlogUtils.saveBinlog(binlog, data));
}
2021-01-24 19:13:46 +01:00
public Mono<Void> start(int botId,
String botAlias,
boolean local,
JsonObject implementationDetails,
BinlogAsyncFile binlog) {
2021-01-23 18:49:21 +01:00
this.botId = botId;
this.botAlias = botAlias;
this.botAddress = "bots.bot." + this.botId;
this.local = local;
this.logger = LoggerFactory.getLogger(this.botId + " " + botAlias);
return MonoUtils
.emitValue(this.binlog, binlog)
.then(binlog.getLastModifiedTime())
.zipWith(binlog.readFullyBytes())
.single()
.flatMap(tuple -> {
var binlogLastModifiedTime = tuple.getT1();
var binlogData = tuple.getT2();
2021-01-24 19:13:46 +01:00
var msg = new StartSessionMessage(this.botId,
this.botAlias,
binlogData,
binlogLastModifiedTime,
implementationDetails
);
2021-01-23 18:49:21 +01:00
return setupUpdatesListener()
2021-01-24 19:13:46 +01:00
.then(Mono.defer(() -> local ? Mono.empty()
: cluster.getEventBus().<byte[]>rxRequest("bots.start-bot", msg).as(MonoUtils::toMono)))
2021-01-23 18:49:21 +01:00
.then();
});
}
2021-01-23 18:49:21 +01:00
@SuppressWarnings("CallingSubscribeInNonBlockingScope")
private Mono<Void> setupUpdatesListener() {
2021-01-24 19:13:46 +01:00
MessageConsumer<TdResultList> updateConsumer = MessageConsumer.newInstance(cluster.getEventBus().<TdResultList>consumer(botAddress + ".updates").setMaxBufferedMessages(5000).getDelegate());
2021-01-23 18:49:21 +01:00
updateConsumer.endHandler(h -> {
logger.error("<<<<<<<<<<<<<<<<EndHandler?>>>>>>>>>>>>>");
});
// Here the updates will be piped from the server to the client
updateConsumer
.rxPipeTo(updates.writeAsStream()).as(MonoUtils::toMono)
.subscribeOn(Schedulers.single())
.subscribe();
// Return when the registration of all the consumers has been done across the cluster
return updateConsumer.rxCompletionHandler().as(MonoUtils::toMono);
}
2021-01-23 18:49:21 +01:00
@Override
public Flux<TdApi.Object> receive() {
// Here the updates will be received
2021-01-24 19:13:46 +01:00
return Mono
.fromRunnable(() -> logger.trace("Called receive() from parent"))
.doOnSuccess(s -> logger.trace("Sending ready-to-receive"))
.then(cluster.getEventBus().<byte[]>rxRequest(botAddress + ".ready-to-receive", EMPTY, deliveryOptionsWithTimeout).as(MonoUtils::toMono))
.doOnSuccess(s -> logger.trace("Sent ready-to-receive, received reply"))
.doOnSuccess(s -> logger.trace("About to read updates flux"))
2021-01-24 03:15:45 +01:00
.thenMany(updates.readAsFlux())
2021-01-23 22:33:52 +01:00
.cast(io.vertx.core.eventbus.Message.class)
2021-01-24 03:15:45 +01:00
.timeout(Duration.ofSeconds(20), Mono.fromCallable(() -> {
throw new IllegalStateException("Server did not respond to 4 pings after 20 seconds (5 seconds per ping)");
}))
2021-01-24 04:21:47 +01:00
.flatMap(updates -> {
var result = (TdResultList) updates.body();
if (result.succeeded()) {
return Flux.fromIterable(result.value());
} else {
return Mono.fromCallable(() -> TdResult.failed(result.error()).orElseThrow());
}
})
2021-01-23 22:33:52 +01:00
.flatMap(this::interceptUpdate)
2021-01-23 18:49:21 +01:00
.doOnError(crash::tryEmitError)
.doOnTerminate(updatesStreamEnd::tryEmitEmpty);
}
2021-01-24 19:13:46 +01:00
private Mono<TdApi.Object> interceptUpdate(TdApi.Object update) {
2021-01-23 22:33:52 +01:00
switch (update.getConstructor()) {
case TdApi.UpdateAuthorizationState.CONSTRUCTOR:
var updateAuthorizationState = (TdApi.UpdateAuthorizationState) update;
switch (updateAuthorizationState.authorizationState.getConstructor()) {
case TdApi.AuthorizationStateClosed.CONSTRUCTOR:
2021-01-24 19:13:46 +01:00
return Mono.fromRunnable(() -> logger.trace("Received AuthorizationStateClosed from tdlib"))
.then(cluster.getEventBus().<EndSessionMessage>rxRequest(this.botAddress + ".read-binlog", EMPTY).as(MonoUtils::toMono))
2021-01-23 22:33:52 +01:00
.doOnNext(l -> logger.info("Received binlog from server. Size: " + BinlogUtils.humanReadableByteCountBin(l.body().binlog().length)))
.flatMap(latestBinlog -> this.saveBinlog(latestBinlog.body().binlog()))
.doOnSuccess(s -> logger.info("Overwritten binlog from server"))
.thenReturn(update);
}
break;
}
return Mono.just(update);
}
@Override
public <T extends TdApi.Object> Mono<TdResult<T>> execute(Function request, boolean executeDirectly) {
var req = new ExecuteObject(executeDirectly, request);
2021-01-22 17:31:09 +01:00
return Mono
2021-01-23 18:49:21 +01:00
.firstWithSignal(
MonoUtils.castVoid(crash.asMono()),
2021-01-24 19:13:46 +01:00
Mono
.fromRunnable(() -> logger.trace("Executing request {}", request))
.then(cluster.getEventBus().<TdResultMessage>rxRequest(botAddress + ".execute", req, deliveryOptions).as(MonoUtils::toMono))
2021-01-22 17:31:09 +01:00
.onErrorMap(ex -> ResponseError.newResponseError(request, botAlias, ex))
2021-01-24 19:13:46 +01:00
.<TdResult<T>>flatMap(resp -> Mono
.fromCallable(() -> {
if (resp.body() == null) {
throw ResponseError.newResponseError(request, botAlias, new TdError(500, "Response is empty"));
} else {
return resp.body().toTdResult();
}
})
)
.doOnSuccess(s -> logger.trace("Executed request"))
2021-01-23 18:49:21 +01:00
)
2021-01-23 22:33:52 +01:00
.switchIfEmpty(Mono.defer(() -> Mono.fromCallable(() -> {
2021-01-23 18:49:21 +01:00
throw ResponseError.newResponseError(request, botAlias, new TdError(500, "Client is closed or response is empty"));
2021-01-23 22:33:52 +01:00
})));
}
}