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
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,27 @@ To use with Android don't forget to set INTERNET permission to `AndroidManifest.
<uses-permission android:name="android.permission.INTERNET" />
```

## Threads and event listeners

Each `Client` runs its work on one thread of its own: connection and subscription logic, timers, and the calls of
your `EventListener` and `SubscriptionEventListener` methods and of result callbacks. So listeners and callbacks are
never called concurrently, and they are called in the order things happened.

- **Client methods are asynchronous.** `connect()`, `disconnect()`, `subscribe()`, `unsubscribe()`, `publish()` and
the other calls queue their work on that thread and return at once. A call made from a listener takes effect after
the listener returns.
- **Don't block in a listener or callback.** While it runs, the client handles nothing else: no replies, no pings, no
timers. Waiting inside a listener for the result of a call (e.g. on a future completed by a callback) can't
succeed before the call's timeout, and `close(awaitMilliseconds)` called from a listener can't wait for the client
thread it runs on: it returns `false` after the wait. Move blocking work to your own thread.
- **Exceptions.** An exception thrown by a listener or callback is reported through `EventListener.onError`
(`UnclassifiedError`) and doesn't stop the client's own work. An exception thrown while the client handles data
from the server — e.g. by an `onConnected`, `onSubscribed` or `onPublication` listener — also disconnects the client
with code 2 ("bad protocol"), as centrifuge-js does; call `connect()` to start again. A token or state getter that
throws is treated as if it called back with that error.
- **Call `close()` when the client is no longer needed.** `disconnect()` keeps the client's thread for a later
`connect()`.

## Usage in background

When a mobile application goes to the background there are OS-specific limitations for established persistent connections - which can be silently closed shortly. Thus in most cases you need to disconnect from a server when app moves to the background and connect again when app goes to the foreground.
Expand Down
573 changes: 496 additions & 77 deletions centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ public class Subscription {
private int resubscribeAttempts = 0;
private String token;
private com.google.protobuf.ByteString data;
private FilterNode tagsFilter;
// Set from the app's thread, read on the client thread when subscribing.
private volatile FilterNode tagsFilter;
private boolean deltaNegotiated;
private byte[] prevData;
// Numeric channel ID assigned by the server when channel compaction is
Expand All @@ -38,6 +39,13 @@ public class Subscription {
// callbacks capture the epoch at issue time and bail if it has moved on,
// so a stale token from an earlier attempt cannot land on a later one.
private long subscribeEpoch = 0;
// Bumped each time the subscription becomes unsubscribed. A subscribe command
// carries the value it was sent with, so its reply is dropped when an
// unsubscribe (and possibly a new subscribe) happened meanwhile: that reply
// belongs to a subscribe the server was told to end.
private long unsubscribeCount = 0;
// Removed from the client's registry: it can't subscribe again.
private volatile boolean removed = false;

Subscription(final Client client, final String channel, final SubscriptionEventListener listener, final SubscriptionOptions options) {
this.client = client;
Expand All @@ -63,6 +71,14 @@ public class Subscription {
this(client, channel, listener, new SubscriptionOptions());
}

void markRemoved() {
this.removed = true;
}

long getUnsubscribeCount() {
return unsubscribeCount;
}

void setState(SubscriptionState state) {
this.state = state;
}
Expand Down Expand Up @@ -100,6 +116,11 @@ void resubscribeIfNecessary() {
if (this.getState() != SubscriptionState.SUBSCRIBING) {
return;
}
if (this.resubscribeTask != null && !this.resubscribeTask.isDone()) {
// A subscribe error is retried after its backoff, also across a reconnect
// (as centrifuge-js): the retry subscribes once it fires.
return;
}
this.sendSubscribe();
}

Expand All @@ -109,7 +130,7 @@ void sendRefresh() {
}
this.client.getExecutor().submit(() -> {
final long epoch = ++Subscription.this.subscribeEpoch;
Subscription.this.opts.getTokenGetter().getSubscriptionToken(new SubscriptionTokenEvent(Subscription.this.getChannel()), (err, token) -> Subscription.this.client.getExecutor().submit(() -> {
Client.fetchSubscriptionToken(Subscription.this.opts.getTokenGetter(), new SubscriptionTokenEvent(Subscription.this.getChannel()), (err, token) -> Subscription.this.client.getExecutor().submit(() -> {
if (Subscription.this.subscribeEpoch != epoch) {
return;
}
Expand Down Expand Up @@ -180,7 +201,8 @@ void sendRefresh() {

void moveToSubscribing(int code, String reason) {
if (this.getState() == SubscriptionState.SUBSCRIBING) {
this.clearSubscribingState();
// Still subscribing (e.g. across a reconnect): a pending resubscribe keeps
// its backoff instead of retrying at once on the next connect.
return;
}
if (this.getState() == SubscriptionState.SUBSCRIBED) {
Expand Down Expand Up @@ -217,6 +239,13 @@ void handlePublication(Protocol.Publication pub) throws Exception {
event.setTags(pub.getTagsMap());
if (pub.getOffset() > 0) {
this.setOffset(pub.getOffset());
// A subscribe reply without an epoch (a channel with no stream yet): the epoch
// comes with the first publication. Taken with the offset it belongs to, and
// only while none is known; a different one means the stream was reset, which
// the server reports on recovery (as centrifuge-js).
if ((this.epoch == null || this.epoch.isEmpty()) && !pub.getEpoch().isEmpty()) {
this.setEpoch(pub.getEpoch());
}
}
this.listener.onPublication(this, event);
}
Expand All @@ -229,7 +258,10 @@ void moveToSubscribed(Protocol.SubscribeResult result) throws Exception {
if (result.getRecoverable()) {
this.recover = true;
}
this.setEpoch(result.getEpoch());
if (!result.getEpoch().isEmpty()) {
// A reply without an epoch doesn't drop the one already known.
this.setEpoch(result.getEpoch());
}
this.deltaNegotiated = result.getDelta();
// Channel compaction: register the numeric channel ID assigned by the
// server (0 when not negotiated — also clears a stale ID from a previous
Expand Down Expand Up @@ -277,6 +309,15 @@ void subscribeError(ReplyError err) {
this.scheduleResubscribe();
return;
}
if (err.getCode() == 109 && this.opts.getTokenGetter() == null) {
// The token expired and there is no token getter to get another one: like a
// connection, unauthorized, instead of subscribing again without a token (the
// server answers 103 and the app sees "permission denied"). As centrifuge-js.
this.listener.onError(this, new SubscriptionErrorEvent(new ConfigurationError(
new Exception("subscription token expired but no tokenGetter set in SubscriptionOptions"))));
this._unsubscribe(false, Client.UNSUBSCRIBED_UNAUTHORIZED, "unauthorized");
return;
}
this.listener.onError(this, new SubscriptionErrorEvent(new SubscriptionSubscribeError(err)));
if (err.getCode() == 109) { // Token expired.
this.token = "";
Expand All @@ -302,14 +343,32 @@ public void setTagsFilter(FilterNode tagsFilter) {
this.tagsFilter = tagsFilter;
}

/**
* Subscribe to the channel.
*
* @throws IllegalStateException if the subscription was removed from the client: the
* client no longer tracks it, so the server would keep a
* subscription whose publications are dropped.
*/
public void subscribe() {
if (this.removed) {
throw new IllegalStateException("subscription to the channel " + this.channel + " was removed from the client");
}
this.client.getExecutor().submit(() -> {
if (Subscription.this.removed) {
return;
}
if (Subscription.this.getState() == SubscriptionState.SUBSCRIBED || Subscription.this.getState() == SubscriptionState.SUBSCRIBING) {
return;
}
Subscription.this.setState(SubscriptionState.SUBSCRIBING);
Subscription.this.listener.onSubscribing(Subscription.this, new SubscribingEvent(Client.SUBSCRIBING_SUBSCRIBE_CALLED, "subscribe called"));
Subscription.this.sendSubscribe();
try {
Subscription.this.listener.onSubscribing(Subscription.this, new SubscribingEvent(Client.SUBSCRIBING_SUBSCRIBE_CALLED, "subscribe called"));
} finally {
// A handler that throws doesn't stop the subscribe; one that called
// unsubscribe() queued it after this step.
Subscription.this.sendSubscribe();
}
});
}

Expand Down Expand Up @@ -357,6 +416,12 @@ Protocol.SubscribeRequest createSubscribeRequest() {
}

void sendSubscribe() {
if (this.client.getState() != ClientState.CONNECTED) {
// Subscribed once the client connects (the connect reply resubscribes every
// subscribing subscription), as centrifuge-js: no token or state requested
// while disconnected, and no second request for the same subscribe on connect.
return;
}
// State getter: ask the app for its current state position. Only called
// when we don't have a saved position (first subscribe or after a position
// reset due to unrecoverable position error 112). On normal reconnects with
Expand All @@ -365,7 +430,7 @@ void sendSubscribe() {
if (this.opts.getStateGetter() != null && !this.getRecover()) {
final long epoch = ++this.subscribeEpoch;
SubscriptionGetStateEvent getStateEvent = new SubscriptionGetStateEvent(this.channel);
this.opts.getStateGetter().getSubscriptionState(getStateEvent, (err, position) -> Subscription.this.client.getExecutor().submit(() -> {
Client.fetchSubscriptionState(this.opts.getStateGetter(), getStateEvent, (err, position) -> Subscription.this.client.getExecutor().submit(() -> {
if (Subscription.this.subscribeEpoch != epoch) {
return;
}
Expand All @@ -392,7 +457,7 @@ private void continueSubscribe() {
if (this.token.equals("") && this.opts.getTokenGetter() != null) {
final long epoch = ++this.subscribeEpoch;
SubscriptionTokenEvent subscriptionTokenEvent = new SubscriptionTokenEvent(this.channel);
this.opts.getTokenGetter().getSubscriptionToken(subscriptionTokenEvent, (err, token) -> Subscription.this.client.getExecutor().submit(() -> {
Client.fetchSubscriptionToken(this.opts.getTokenGetter(), subscriptionTokenEvent, (err, token) -> Subscription.this.client.getExecutor().submit(() -> {
if (Subscription.this.subscribeEpoch != epoch) {
return;
}
Expand Down Expand Up @@ -431,6 +496,11 @@ private void clearSubscribedState() {
this.refreshTask.cancel(true);
this.refreshTask = null;
}
// Ends a refresh in flight (its token request or its sub_refresh command): a
// resubscribe that reuses the token doesn't start a new attempt, so the stale
// continuation would otherwise refresh the new subscribed period too and start a
// second refresh chain.
this.subscribeEpoch++;
}

private void clearSubscribingState() {
Expand All @@ -454,6 +524,7 @@ private void _unsubscribe(boolean sendUnsubscribe, int code, String reason) {
this.clearSubscribingState();
}
this.setState(SubscriptionState.UNSUBSCRIBED);
this.unsubscribeCount++;
// Channel compaction ID is no longer valid once unsubscribed.
this.setPushId(0);
if (sendUnsubscribe) {
Expand All @@ -471,6 +542,11 @@ private void scheduleResubscribe() {
if (this.getState() != SubscriptionState.SUBSCRIBING) {
return;
}
if (this.resubscribeTask != null) {
// One pending retry at most: an overwritten task fired too, subscribing again
// or fetching a token while disconnected.
this.resubscribeTask.cancel(false);
}
this.resubscribeTask = this.client.getScheduler().schedule(
Subscription.this::startResubscribing,
Subscription.this.backoff.duration(this.resubscribeAttempts, this.opts.getMinResubscribeDelay(), this.opts.getMaxResubscribeDelay()),
Expand All @@ -480,7 +556,14 @@ private void scheduleResubscribe() {
}

void startResubscribing() {
this.client.getExecutor().submit(this::sendSubscribe);
this.client.getExecutor().submit(() -> {
// The retry timer may have fired just before the app's unsubscribe() (or a
// subscribe reply) ran: it then belongs to an attempt that ended.
if (Subscription.this.getState() != SubscriptionState.SUBSCRIBING) {
return;
}
Subscription.this.sendSubscribe();
});
}

boolean getRecover() {
Expand All @@ -499,14 +582,14 @@ private void publishSynchronized(byte[] data, ResultCallback<PublishResult> cb)
CompletableFuture<Throwable> f = new CompletableFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
f.thenAccept(err -> {
this.client.settle(f, err -> {
if (err != null) {
cb.onDone(err, null);
return;
}
this.futures.remove(uuid);
this.client.publish(this.getChannel(), data, cb);
}).orTimeout(this.client.getOpts().getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> {
}, e -> {
Subscription.this.futures.remove(uuid);
cb.onDone(e, null);
return null;
Expand All @@ -524,14 +607,14 @@ private void historySynchronized(HistoryOptions opts, ResultCallback<HistoryResu
CompletableFuture<Throwable> f = new CompletableFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
f.thenAccept(err -> {
this.client.settle(f, err -> {
if (err != null) {
cb.onDone(err, null);
return;
}
this.futures.remove(uuid);
this.client.history(this.getChannel(), opts, cb);
}).orTimeout(this.client.getOpts().getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> {
}, e -> {
Subscription.this.futures.remove(uuid);
cb.onDone(e, null);
return null;
Expand All @@ -549,14 +632,14 @@ private void presenceSynchronized(ResultCallback<PresenceResult> cb) {
CompletableFuture<Throwable> f = new CompletableFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
f.thenAccept(err -> {
this.client.settle(f, err -> {
if (err != null) {
cb.onDone(err, null);
return;
}
this.futures.remove(uuid);
this.client.presence(this.getChannel(), cb);
}).orTimeout(this.client.getOpts().getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> {
}, e -> {
Subscription.this.futures.remove(uuid);
cb.onDone(e, null);
return null;
Expand All @@ -574,14 +657,14 @@ private void presenceStatsSynchronized(ResultCallback<PresenceStatsResult> cb) {
CompletableFuture<Throwable> f = new CompletableFuture<>();
String uuid = UUID.randomUUID().toString();
this.futures.put(uuid, f);
f.thenAccept(err -> {
this.client.settle(f, err -> {
if (err != null) {
cb.onDone(err, null);
return;
}
this.futures.remove(uuid);
this.client.presenceStats(this.getChannel(), cb);
}).orTimeout(this.client.getOpts().getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> {
}, e -> {
Subscription.this.futures.remove(uuid);
cb.onDone(e, null);
return null;
Expand Down Expand Up @@ -625,7 +708,11 @@ private void setPushId(long id) {
// just resubscribes (the sentinel is not sent). The real epoch/offset are
// adopted from the subscribe reply. Runs on the client executor thread.
void invalidateState() {
this.token = "";
if (this.opts.getTokenGetter() != null) {
// Only a token the getter can replace: a static token is kept, and the
// server rejects it if it's no longer valid.
this.token = "";
}
this.offset = 0;
this.epoch = "_";
this.prevData = null;
Expand Down
Loading
Loading