2021-04-07 19:48:10 +02:00
|
|
|
package it.tdlight.common.internal;
|
2021-02-13 17:41:54 +01:00
|
|
|
|
2021-04-07 19:48:10 +02:00
|
|
|
import it.tdlight.common.ClientEventsHandler;
|
|
|
|
import it.tdlight.common.ExceptionHandler;
|
|
|
|
import it.tdlight.common.ReactiveItem;
|
|
|
|
import it.tdlight.common.ReactiveTelegramClient;
|
2021-02-13 17:41:54 +01:00
|
|
|
import it.tdlight.jni.TdApi;
|
|
|
|
import it.tdlight.jni.TdApi.Error;
|
|
|
|
import it.tdlight.jni.TdApi.Function;
|
2021-10-02 15:02:48 +02:00
|
|
|
import java.time.Duration;
|
2021-02-13 17:41:54 +01:00
|
|
|
import java.util.Objects;
|
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
import java.util.concurrent.ConcurrentLinkedQueue;
|
2021-03-31 04:33:39 +02:00
|
|
|
import java.util.concurrent.CountDownLatch;
|
2021-10-02 15:02:48 +02:00
|
|
|
import java.util.concurrent.Executors;
|
|
|
|
import java.util.concurrent.ScheduledExecutorService;
|
|
|
|
import java.util.concurrent.ScheduledFuture;
|
|
|
|
import java.util.concurrent.TimeUnit;
|
2021-02-25 11:19:14 +01:00
|
|
|
import java.util.concurrent.atomic.AtomicBoolean;
|
2021-02-13 17:41:54 +01:00
|
|
|
import java.util.concurrent.atomic.AtomicLong;
|
|
|
|
import org.reactivestreams.Publisher;
|
|
|
|
import org.reactivestreams.Subscriber;
|
|
|
|
import org.reactivestreams.Subscription;
|
|
|
|
import org.slf4j.Logger;
|
|
|
|
import org.slf4j.LoggerFactory;
|
|
|
|
|
2021-09-27 19:27:13 +02:00
|
|
|
public final class InternalReactiveClient implements ClientEventsHandler, ReactiveTelegramClient {
|
2021-02-13 17:41:54 +01:00
|
|
|
|
2021-03-31 04:33:39 +02:00
|
|
|
private static final Logger logger = LoggerFactory.getLogger(InternalReactiveClient.class);
|
2021-10-02 15:02:48 +02:00
|
|
|
private final ConcurrentHashMap<Long, Handler> handlers = new ConcurrentHashMap<>();
|
|
|
|
private final ScheduledExecutorService timers = Executors.newSingleThreadScheduledExecutor();
|
2021-02-13 17:41:54 +01:00
|
|
|
private final ConcurrentLinkedQueue<ReactiveItem> backpressureQueue = new ConcurrentLinkedQueue<>();
|
|
|
|
private final ExceptionHandler defaultExceptionHandler;
|
|
|
|
private final Handler updateHandler;
|
|
|
|
|
|
|
|
private volatile Integer clientId = null;
|
|
|
|
private final InternalClientManager clientManager;
|
|
|
|
|
|
|
|
private final AtomicBoolean isClosed = new AtomicBoolean();
|
|
|
|
private final AtomicBoolean updatesAlreadySubscribed = new AtomicBoolean(false);
|
|
|
|
private final AtomicLong requested = new AtomicLong(0);
|
|
|
|
private volatile Subscriber<? super ReactiveItem> subscriber;
|
|
|
|
|
|
|
|
public InternalReactiveClient(InternalClientManager clientManager) {
|
|
|
|
this.clientManager = clientManager;
|
|
|
|
this.updateHandler = new Handler(
|
|
|
|
updateItem -> {
|
2021-05-05 13:10:28 +02:00
|
|
|
ReactiveItem item = ReactiveItem.ofUpdate(updateItem);
|
2021-02-13 17:41:54 +01:00
|
|
|
if (subscriber != null && requested.getAndUpdate(n -> n == 0 ? 0 : (n - 1)) > 0) {
|
|
|
|
subscriber.onNext(item);
|
|
|
|
} else {
|
|
|
|
backpressureQueue.add(item);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
updateEx -> {
|
2021-05-05 13:10:28 +02:00
|
|
|
ReactiveItem item = ReactiveItem.ofUpdateException(updateEx);
|
2021-02-13 17:41:54 +01:00
|
|
|
if (subscriber != null && requested.getAndUpdate(n -> n == 0 ? 0 : (n - 1)) > 0) {
|
|
|
|
subscriber.onNext(item);
|
|
|
|
} else {
|
|
|
|
backpressureQueue.add(item);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
this.defaultExceptionHandler = ex -> backpressureQueue.add(ReactiveItem.ofHandleException(ex));
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public int getClientId() {
|
|
|
|
return Objects.requireNonNull(clientId, "Can't obtain the client id before initialization");
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2021-09-27 19:27:13 +02:00
|
|
|
public void handleEvents(boolean isClosed, long[] eventIds, TdApi.Object[] events) {
|
2021-02-13 17:41:54 +01:00
|
|
|
for (int i = 0; i < eventIds.length; i++) {
|
|
|
|
handleEvent(eventIds[i], events[i]);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isClosed) {
|
|
|
|
if (this.isClosed.compareAndSet(false, true)) {
|
|
|
|
handleClose();
|
|
|
|
}
|
|
|
|
}
|
2021-04-18 23:27:23 +02:00
|
|
|
}
|
2021-02-13 17:41:54 +01:00
|
|
|
|
|
|
|
private void handleClose() {
|
2021-10-02 15:02:48 +02:00
|
|
|
handlers.forEach((eventId, handler) -> handleResponse(eventId, new Error(500, "Instance closed"), handler));
|
2021-02-13 17:41:54 +01:00
|
|
|
handlers.clear();
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles only a response (not an update!)
|
|
|
|
*/
|
2021-09-27 19:27:13 +02:00
|
|
|
private void handleResponse(long eventId, TdApi.Object event, Handler handler) {
|
2021-02-13 17:41:54 +01:00
|
|
|
if (handler != null) {
|
|
|
|
try {
|
2021-03-31 04:33:39 +02:00
|
|
|
if (eventId == 0) {
|
|
|
|
logger.trace("Client {} received an event: {}", clientId, event);
|
|
|
|
} else {
|
|
|
|
logger.trace("Client {} received a response for query id {}: {}", clientId, eventId, event);
|
|
|
|
}
|
2021-02-13 17:41:54 +01:00
|
|
|
handler.getResultHandler().onResult(event);
|
|
|
|
} catch (Throwable cause) {
|
|
|
|
handleException(handler.getExceptionHandler(), cause);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
logger.error("Unknown event id \"{}\", the event has been dropped! {}", eventId, event);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handles a response or an update
|
|
|
|
*/
|
2021-09-27 19:27:13 +02:00
|
|
|
private void handleEvent(long eventId, TdApi.Object event) {
|
2021-02-13 17:41:54 +01:00
|
|
|
Handler handler = eventId == 0 ? updateHandler : handlers.remove(eventId);
|
|
|
|
handleResponse(eventId, event, handler);
|
|
|
|
}
|
|
|
|
|
|
|
|
private void handleException(ExceptionHandler exceptionHandler, Throwable cause) {
|
|
|
|
if (exceptionHandler == null) {
|
|
|
|
exceptionHandler = defaultExceptionHandler;
|
|
|
|
}
|
|
|
|
if (exceptionHandler != null) {
|
|
|
|
try {
|
|
|
|
exceptionHandler.onException(cause);
|
|
|
|
} catch (Throwable ignored) {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void subscribe(Subscriber<? super ReactiveItem> subscriber) {
|
|
|
|
AtomicBoolean alreadyCompleted = new AtomicBoolean();
|
|
|
|
if (updatesAlreadySubscribed.compareAndSet(false, true)) {
|
2021-05-05 13:10:28 +02:00
|
|
|
Subscription subscription = new Subscription() {
|
2021-02-13 17:41:54 +01:00
|
|
|
|
|
|
|
@Override
|
|
|
|
public void request(long n) {
|
2021-03-31 04:33:39 +02:00
|
|
|
ReactiveItem item;
|
|
|
|
while (n > 0 && (item = backpressureQueue.poll()) != null) {
|
|
|
|
subscriber.onNext(item);
|
|
|
|
n--;
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
|
|
|
if (n > 0) {
|
|
|
|
requested.addAndGet(n);
|
|
|
|
}
|
|
|
|
if (isClosed.get()) {
|
|
|
|
if (alreadyCompleted.compareAndSet(false, true)) {
|
|
|
|
subscriber.onComplete();
|
2021-02-25 23:36:49 +01:00
|
|
|
logger.info("Client closed {}", clientId);
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-25 11:19:14 +01:00
|
|
|
@SuppressWarnings("ReactiveStreamsSubscriberImplementation")
|
2021-02-13 17:41:54 +01:00
|
|
|
@Override
|
|
|
|
public void cancel() {
|
|
|
|
if (!isClosed.get()) {
|
2021-10-02 15:02:48 +02:00
|
|
|
send(new TdApi.Close(), Duration.ofDays(1)).subscribe(new Subscriber<TdApi.Object>() {
|
2021-02-13 17:41:54 +01:00
|
|
|
@Override
|
|
|
|
public void onSubscribe(Subscription subscription) {
|
|
|
|
subscription.request(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2021-09-27 19:27:13 +02:00
|
|
|
public void onNext(TdApi.Object o) {
|
2021-02-13 17:41:54 +01:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void onError(Throwable throwable) {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void onComplete() {
|
|
|
|
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
this.subscriber = subscriber;
|
|
|
|
|
|
|
|
subscriber.onSubscribe(subscription);
|
|
|
|
} else {
|
|
|
|
throw new IllegalStateException("Already subscribed");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-25 11:19:14 +01:00
|
|
|
@SuppressWarnings("ReactiveStreamsSubscriberImplementation")
|
|
|
|
public void createAndRegisterClient() {
|
2021-02-13 17:41:54 +01:00
|
|
|
if (clientId != null) throw new UnsupportedOperationException("Can't initialize the same client twice!");
|
2021-03-31 04:33:39 +02:00
|
|
|
logger.debug("Creating new client");
|
2021-02-13 17:41:54 +01:00
|
|
|
clientId = NativeClientAccess.create();
|
2021-03-31 04:33:39 +02:00
|
|
|
logger.debug("Registering new client {}", clientId);
|
2021-02-13 17:41:54 +01:00
|
|
|
clientManager.registerClient(clientId, this);
|
2021-03-31 04:33:39 +02:00
|
|
|
|
|
|
|
CountDownLatch registeredClient = new CountDownLatch(1);
|
2021-02-13 17:41:54 +01:00
|
|
|
|
|
|
|
// Send a dummy request because @levlam is too lazy to fix race conditions in a better way
|
2021-10-02 15:02:48 +02:00
|
|
|
this.send(new TdApi.GetAuthorizationState(), Duration.ofDays(1)).subscribe(new Subscriber<TdApi.Object>() {
|
2021-02-13 17:41:54 +01:00
|
|
|
@Override
|
|
|
|
public void onSubscribe(Subscription subscription) {
|
|
|
|
subscription.request(1);
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2021-09-27 19:27:13 +02:00
|
|
|
public void onNext(TdApi.Object item) {
|
2021-03-31 04:33:39 +02:00
|
|
|
registeredClient.countDown();
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void onError(Throwable throwable) {
|
2021-03-31 04:33:39 +02:00
|
|
|
registeredClient.countDown();
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void onComplete() {
|
2021-03-31 04:33:39 +02:00
|
|
|
registeredClient.countDown();
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
|
|
|
});
|
2021-03-31 04:33:39 +02:00
|
|
|
|
|
|
|
try {
|
|
|
|
registeredClient.await();
|
|
|
|
} catch (InterruptedException e) {
|
|
|
|
throw new IllegalStateException(e);
|
|
|
|
}
|
|
|
|
logger.debug("Registered new client {}", clientId);
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2021-10-02 15:02:48 +02:00
|
|
|
public Publisher<TdApi.Object> send(Function query, Duration responseTimeout) {
|
2021-02-13 17:41:54 +01:00
|
|
|
return subscriber -> {
|
2021-05-05 13:10:28 +02:00
|
|
|
Subscription subscription = new Subscription() {
|
2021-03-31 04:33:39 +02:00
|
|
|
|
|
|
|
private final AtomicBoolean alreadyRequested = new AtomicBoolean(false);
|
2021-04-18 23:27:23 +02:00
|
|
|
private volatile boolean cancelled = false;
|
2021-03-31 04:33:39 +02:00
|
|
|
|
|
|
|
@Override
|
|
|
|
public void request(long n) {
|
2021-04-18 23:27:23 +02:00
|
|
|
if (n > 0 && alreadyRequested.compareAndSet(false, true)) {
|
2021-03-31 04:33:39 +02:00
|
|
|
if (isClosedAndMaybeThrow(query)) {
|
|
|
|
logger.trace("Client {} is already closed, sending \"Ok\" to: {}", clientId, query);
|
|
|
|
subscriber.onNext(new TdApi.Ok());
|
|
|
|
subscriber.onComplete();
|
|
|
|
} else if (clientId == null) {
|
|
|
|
logger.trace("Can't send a request to TDLib before calling \"createAndRegisterClient\" function!");
|
|
|
|
subscriber.onError(
|
|
|
|
new IllegalStateException("Can't send a request to TDLib before calling \"createAndRegisterClient\" function!")
|
|
|
|
);
|
|
|
|
} else {
|
|
|
|
long queryId = clientManager.getNextQueryId();
|
2021-10-02 15:02:48 +02:00
|
|
|
|
|
|
|
// Handle timeout
|
|
|
|
ScheduledFuture<?> timeoutFuture = timers.schedule(() -> {
|
|
|
|
if (handlers.remove(queryId) != null) {
|
|
|
|
if (!cancelled) {
|
|
|
|
subscriber.onNext(new Error(408, "Request Timeout"));
|
|
|
|
}
|
|
|
|
if (!cancelled) {
|
|
|
|
subscriber.onComplete();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}, responseTimeout.toMillis(), TimeUnit.MILLISECONDS);
|
|
|
|
|
2021-03-31 04:33:39 +02:00
|
|
|
handlers.put(queryId, new Handler(result -> {
|
2021-10-02 15:02:48 +02:00
|
|
|
boolean timeoutCancelled = timeoutFuture.cancel(false);
|
|
|
|
if (!cancelled && timeoutCancelled) {
|
2021-04-18 23:27:23 +02:00
|
|
|
subscriber.onNext(result);
|
|
|
|
}
|
2021-10-02 15:02:48 +02:00
|
|
|
if (!cancelled && timeoutCancelled) {
|
2021-04-18 23:27:23 +02:00
|
|
|
subscriber.onComplete();
|
|
|
|
}
|
|
|
|
}, t -> {
|
2021-10-02 15:02:48 +02:00
|
|
|
boolean timeoutCancelled = timeoutFuture.cancel(false);
|
|
|
|
if (!cancelled && timeoutCancelled) {
|
2021-04-18 23:27:23 +02:00
|
|
|
subscriber.onError(t);
|
|
|
|
}
|
|
|
|
}));
|
2021-03-31 04:33:39 +02:00
|
|
|
logger.trace("Client {} is requesting with query id {}: {}", clientId, queryId, query);
|
|
|
|
NativeClientAccess.send(clientId, queryId, query);
|
|
|
|
logger.trace("Client {} requested with query id {}: {}", clientId, queryId, query);
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
2021-03-31 04:33:39 +02:00
|
|
|
} else {
|
|
|
|
logger.debug("Client {} tried to request again the same request, ignored: {}", clientId, query);
|
2021-02-13 17:41:54 +01:00
|
|
|
}
|
2021-03-31 04:33:39 +02:00
|
|
|
}
|
2021-02-13 17:41:54 +01:00
|
|
|
|
2021-03-31 04:33:39 +02:00
|
|
|
@Override
|
|
|
|
public void cancel() {
|
2021-04-18 23:27:23 +02:00
|
|
|
cancelled = true;
|
2021-03-31 04:33:39 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
subscriber.onSubscribe(subscription);
|
2021-02-13 17:41:54 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
2021-09-27 19:27:13 +02:00
|
|
|
public TdApi.Object execute(Function query) {
|
2021-02-13 17:41:54 +01:00
|
|
|
if (isClosedAndMaybeThrow(query)) {
|
|
|
|
return new TdApi.Ok();
|
|
|
|
}
|
|
|
|
return NativeClientAccess.execute(query);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
*
|
|
|
|
* @param function function used to check if the check will be enforced or not. Can be null
|
|
|
|
* @return true if closed
|
|
|
|
*/
|
|
|
|
private boolean isClosedAndMaybeThrow(Function function) {
|
|
|
|
boolean closed = isClosed.get();
|
|
|
|
if (closed) {
|
|
|
|
if (function != null && function.getConstructor() == TdApi.Close.CONSTRUCTOR) {
|
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
throw new IllegalStateException("The client is closed!");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|