Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 0 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,6 @@ The features implemented by this SDK can be found in [SDK feature matrix](https:

Library available in Maven: https://search.maven.org/artifact/io.github.centrifugal/centrifuge-java

This library depends on `streamsupport-minifuture`. In case your project has a dependency to `streamsupport-cfuture` and you have a class name conflicts, you can exclude minifuture safely. Example for Gradle:

```
implementation('io.github.centrifugal:centrifuge-java:{version}') {
exclude group: 'net.sourceforge.streamsupport', module: 'streamsupport-minifuture'
}
```

## Javadoc online

http://www.javadoc.io/doc/io.github.centrifugal/centrifuge-java
Expand Down
1 change: 0 additions & 1 deletion centrifuge/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ configurations {
dependencies {
api 'com.squareup.okhttp3:okhttp:4.12.0'
implementation 'com.google.protobuf:protobuf-javalite:3.25.5'
implementation 'net.sourceforge.streamsupport:streamsupport-minifuture:1.7.4'

testImplementation 'junit:junit:4.13.2'
// In-process WebSocket server for channel compaction tests (the feature is
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package io.github.centrifugal.centrifuge;

/**
* The outcome of one call: completed once, with a result or with an error. A single
* listener is notified on the thread that completes the future, or at once if the
* future is already done.
*/
final class CallFuture<T> {

interface Consumer<T> {
void accept(T value);
}

interface Function<T, R> {
R apply(T value);
}

interface Listener<T> {
void onDone(T result, Throwable error);
}

private boolean done;
private T result;
private Throwable error;
private Listener<T> listener;

boolean complete(T result) {
return this.settle(result, null);
}

boolean completeExceptionally(Throwable error) {
if (error == null) {
throw new NullPointerException();
}
return this.settle(null, error);
}

synchronized boolean isDone() {
return this.done;
}

void whenComplete(Listener<T> listener) {
synchronized (this) {
if (this.listener != null) {
throw new IllegalStateException("listener already set");
}
if (!this.done) {
this.listener = listener;
return;
}
}
listener.onDone(this.result, this.error);
}

private boolean settle(T result, Throwable error) {
Listener<T> l;
synchronized (this) {
if (this.done) {
return false;
}
this.done = true;
this.result = result;
this.error = error;
l = this.listener;
this.listener = null;
}
if (l != null) {
l.onDone(result, error);
}
return true;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import io.github.centrifugal.centrifuge.internal.backoff.Backoff;
import io.github.centrifugal.centrifuge.internal.protocol.Protocol;

import java8.util.concurrent.CompletableFuture;
import okhttp3.Credentials;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
Expand All @@ -49,7 +48,7 @@ public class Client {
private String token;
private com.google.protobuf.ByteString data;
private final EventListener listener;
private final Map<Integer, CompletableFuture<Protocol.Reply>> futures = new ConcurrentHashMap<>();
private final Map<Integer, CallFuture<Protocol.Reply>> futures = new ConcurrentHashMap<>();
private final Map<Integer, Protocol.Command> connectCommands = new ConcurrentHashMap<>();
private final Map<Integer, Protocol.Command> connectAsyncCommands = new ConcurrentHashMap<>();

Expand Down Expand Up @@ -380,7 +379,7 @@ public boolean close(long awaitMilliseconds) throws InterruptedException {
this.executor.submit(() -> {
// Tear down the connection synchronously on the executor thread
// so any future-cleanup tasks scheduled by processDisconnect
// (e.g. orTimeout/exceptionally re-submits) get queued before
// (e.g. re-submits from call error handlers) get queued before
// we mark the executor shutdown.
WebSocket last = Client.this.ws;
Client.this.processDisconnect(DISCONNECTED_DISCONNECT_CALLED, "client closed", false);
Expand Down Expand Up @@ -497,7 +496,7 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) {

private void failPendingCalls() {
// From a copy: a failure handler may register a new call.
for (CompletableFuture<Protocol.Reply> f : new ArrayList<>(this.futures.values())) {
for (CallFuture<Protocol.Reply> f : new ArrayList<>(this.futures.values())) {
f.completeExceptionally(new IOException());
}
}
Expand Down Expand Up @@ -852,8 +851,8 @@ private static long nowMs() {
* handler got the timeout as a second callback, and it failed a call on
* its own thread although the reply was already waiting.
*/
<T> void settle(CompletableFuture<T> f, java8.util.function.Consumer<T> onResult,
java8.util.function.Function<Throwable, Void> onError) {
<T> void settle(CallFuture<T> f, CallFuture.Consumer<T> onResult,
CallFuture.Function<Throwable, Void> onError) {
final long due = nowMs() + this.opts.getTimeout();
ScheduledFuture<?> timer;
try {
Expand All @@ -871,8 +870,7 @@ <T> void settle(CompletableFuture<T> f, java8.util.function.Consumer<T> onResult
if (error == null) {
onResult.accept(result);
} else {
onError.apply(error instanceof java8.util.concurrent.CompletionException && error.getCause() != null
? error.getCause() : error);
onError.apply(error);
}
} catch (Throwable t) {
// E.g. an app callback that threw: reported, never called again.
Expand All @@ -881,7 +879,7 @@ <T> void settle(CompletableFuture<T> f, java8.util.function.Consumer<T> onResult
});
}

private <T> void expire(CompletableFuture<T> f, long due) {
private <T> void expire(CallFuture<T> f, long due) {
if (f.isDone()) {
return;
}
Expand Down Expand Up @@ -983,7 +981,7 @@ private void sendSubscribeSynchronized(Subscription sub, Protocol.SubscribeReque
.setSubscribe(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.futures.put(cmd.getId(), f);
this.settle(f, reply -> {
if (Client.this.getState() != ClientState.CONNECTED) {
Expand Down Expand Up @@ -1043,7 +1041,7 @@ private void sendUnsubscribeSynchronized(String channel) {
.build();

final WebSocket unsubscribeWs = this.ws;
CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.futures.put(cmd.getId(), f);
this.settle(f, reply -> {
this.futures.remove(cmd.getId());
Expand Down Expand Up @@ -1315,7 +1313,7 @@ private void handleConnectReply(Protocol.Reply reply) {
Protocol.Command cmd = entry.getValue();
boolean sent = this.ws.send(ByteString.of(this.serializeCommand(cmd)));
if (!sent) {
CompletableFuture<Protocol.Reply> f = this.futures.get(cmd.getId());
CallFuture<Protocol.Reply> f = this.futures.get(cmd.getId());
if (f != null) {
f.completeExceptionally(new IOException());
}
Expand All @@ -1326,7 +1324,7 @@ private void handleConnectReply(Protocol.Reply reply) {

for (Map.Entry<Integer, Protocol.Command> entry : this.connectAsyncCommands.entrySet()) {
Protocol.Command cmd = entry.getValue();
CompletableFuture<Protocol.Reply> f = this.futures.get(cmd.getId());
CallFuture<Protocol.Reply> f = this.futures.get(cmd.getId());
boolean sent = this.ws.send(ByteString.of(this.serializeCommand(cmd)));
if (!sent) {
if (f != null) {
Expand Down Expand Up @@ -1455,7 +1453,7 @@ private void sendConnect() {
.build();

final WebSocket connectWs = this.ws;
CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.futures.put(cmd.getId(), f);
this.settle(f, reply -> {
this.futures.remove(cmd.getId());
Expand All @@ -1465,8 +1463,7 @@ private void sendConnect() {
this.handleDispatchError(e);
}
}, e -> {
// A timeout completes the future on the CompletableFuture delay
// scheduler thread - hop to the executor like other command failures.
// Handle the failure in a separate executor task.
this.executor.submit(() -> {
Client.this.futures.remove(cmd.getId());
// Failed because the connection was already torn down (disconnect
Expand All @@ -1490,7 +1487,7 @@ private void failUnauthorized() {

private void processReply(Protocol.Reply reply) throws Exception {
if (reply.getId() > 0) {
CompletableFuture<Protocol.Reply> cf = this.futures.get(reply.getId());
CallFuture<Protocol.Reply> cf = this.futures.get(reply.getId());
if (cf != null) cf.complete(reply);
} else {
if (reply.hasPush()) {
Expand Down Expand Up @@ -1702,7 +1699,7 @@ private void sendSynchronized(byte[] data, CompletionCallback cb) {
.setSend(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.futures.put(cmd.getId(), f);
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
Expand All @@ -1727,7 +1724,7 @@ private void sendSynchronized(byte[] data, CompletionCallback cb) {
}
}

private void enqueueCommandFuture(Protocol.Command cmd, CompletableFuture<Protocol.Reply> f) {
private void enqueueCommandFuture(Protocol.Command cmd, CallFuture<Protocol.Reply> f) {
this.futures.put(cmd.getId(), f);
if (this.getState() != ClientState.CONNECTED) {
this.connectCommands.put(cmd.getId(), cmd);
Expand Down Expand Up @@ -1775,7 +1772,7 @@ private void rpcSynchronized(String method, byte[] data, ResultCallback<RPCResul
.setRpc(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
if (reply.getError().getCode() != 0) {
Expand Down Expand Up @@ -1820,7 +1817,7 @@ private void publishSynchronized(String channel, byte[] data, ResultCallback<Pub
.setPublish(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
if (reply.getError().getCode() != 0) {
Expand Down Expand Up @@ -1866,7 +1863,7 @@ private void historySynchronized(String channel, HistoryOptions opts, ResultCall
.setHistory(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
if (reply.getError().getCode() != 0) {
Expand Down Expand Up @@ -1914,7 +1911,7 @@ private void presenceSynchronized(String channel, ResultCallback<PresenceResult>
.setPresence(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
if (reply.getError().getCode() != 0) {
Expand Down Expand Up @@ -1955,7 +1952,7 @@ private void presenceStatsSynchronized(String channel, ResultCallback<PresenceSt
.setPresenceStats(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
if (reply.getError().getCode() != 0) {
Expand Down Expand Up @@ -1988,7 +1985,7 @@ private void refreshSynchronized(String token, ResultCallback<Protocol.RefreshRe
.setRefresh(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
if (reply.getError().getCode() != 0) {
Expand Down Expand Up @@ -2019,7 +2016,7 @@ void subRefreshSynchronized(String channel, String token, ResultCallback<Protoco
.setSubRefresh(req)
.build();

CompletableFuture<Protocol.Reply> f = new CompletableFuture<>();
CallFuture<Protocol.Reply> f = new CallFuture<>();
this.settle(f, reply -> {
this.cleanCommandFuture(cmd);
if (reply.getError().getCode() != 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@

import io.github.centrifugal.centrifuge.internal.backoff.Backoff;
import io.github.centrifugal.centrifuge.internal.protocol.Protocol;
import java8.util.concurrent.CompletableFuture;

public class Subscription {

Expand All @@ -20,7 +19,7 @@ public class Subscription {
private String epoch;
final private SubscriptionEventListener listener;
private volatile SubscriptionState state = SubscriptionState.UNSUBSCRIBED;
final private Map<String, CompletableFuture<Throwable>> futures = new ConcurrentHashMap<>();
final private Map<String, CallFuture<Throwable>> futures = new ConcurrentHashMap<>();
private final Backoff backoff;
private ScheduledFuture<?> refreshTask;
private ScheduledFuture<?> resubscribeTask;
Expand Down Expand Up @@ -289,8 +288,8 @@ void moveToSubscribed(Protocol.SubscribeResult result) throws Exception {
this.client.handlePub(this.channel, publication);
}

for(Map.Entry<String, CompletableFuture<Throwable>> entry: this.futures.entrySet()) {
CompletableFuture<Throwable> f = entry.getValue();
for(Map.Entry<String, CallFuture<Throwable>> entry: this.futures.entrySet()) {
CallFuture<Throwable> f = entry.getValue();
f.complete(null);
}
this.futures.clear();
Expand Down Expand Up @@ -536,8 +535,8 @@ private void _unsubscribe(boolean sendUnsubscribe, int code, String reason) {
if (sendUnsubscribe) {
this.client.sendUnsubscribe(this.getChannel());
}
for(Map.Entry<String, CompletableFuture<Throwable>> entry: this.futures.entrySet()) {
CompletableFuture<Throwable> f = entry.getValue();
for(Map.Entry<String, CallFuture<Throwable>> entry: this.futures.entrySet()) {
CallFuture<Throwable> f = entry.getValue();
f.complete(new SubscriptionStateError(this.getState()));
}
this.futures.clear();
Expand Down Expand Up @@ -585,7 +584,7 @@ public void publish(byte[] data, ResultCallback<PublishResult> cb) {
}

private void publishSynchronized(byte[] data, ResultCallback<PublishResult> cb) {
CompletableFuture<Throwable> f = new CompletableFuture<>();
CallFuture<Throwable> f = new CallFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
this.client.settle(f, err -> {
Expand All @@ -610,7 +609,7 @@ public void history(HistoryOptions opts, ResultCallback<HistoryResult> cb) {
}

private void historySynchronized(HistoryOptions opts, ResultCallback<HistoryResult> cb) {
CompletableFuture<Throwable> f = new CompletableFuture<>();
CallFuture<Throwable> f = new CallFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
this.client.settle(f, err -> {
Expand All @@ -635,7 +634,7 @@ public void presence(ResultCallback<PresenceResult> cb) {
}

private void presenceSynchronized(ResultCallback<PresenceResult> cb) {
CompletableFuture<Throwable> f = new CompletableFuture<>();
CallFuture<Throwable> f = new CallFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
this.client.settle(f, err -> {
Expand All @@ -660,7 +659,7 @@ public void presenceStats(ResultCallback<PresenceStatsResult> cb) {
}

private void presenceStatsSynchronized(ResultCallback<PresenceStatsResult> cb) {
CompletableFuture<Throwable> f = new CompletableFuture<>();
CallFuture<Throwable> f = new CallFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
this.client.settle(f, err -> {
Expand Down
Loading
Loading