From 9f9d4f3c9cbd5e22b65614c202a91fa4a7c78b4b Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:33:53 +0300 Subject: [PATCH 01/11] Write the unsubscribe command before the unsubscribed event and drop replies of ended subscribe attempts unsubscribe() queued its command through a second executor task, so a subscribe() called right after it (or from its unsubscribed handler) reached the server first: the server answered 105 (already subscribed), the subscription ended unsubscribed, and the late unsubscribe removed the server subscription as well. The unsubscribe command is now written at once, before the event, as centrifuge-js does. A subscribe reply is now applied only to the subscribe attempt that sent it: after subscribe/unsubscribe/subscribe the first reply belongs to a subscription the server was told to end and is ignored. --- .../github/centrifugal/centrifuge/Client.java | 28 +++- .../centrifugal/centrifuge/Subscription.java | 10 ++ .../centrifuge/UnsubscribeOrderTest.java | 137 ++++++++++++++++++ 3 files changed, 168 insertions(+), 7 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeOrderTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index 02b9b6d..e60e234 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -621,7 +621,8 @@ private void scheduleReconnect() { this.reconnectAttempts++; } - private void sendSubscribeSynchronized(String channel, Protocol.SubscribeRequest req) { + private void sendSubscribeSynchronized(Subscription sub, Protocol.SubscribeRequest req) { + final long unsubscribeCount = sub.getUnsubscribeCount(); Protocol.Command cmd = Protocol.Command.newBuilder() .setId(this.getNextId()) .setSubscribe(req) @@ -634,7 +635,7 @@ private void sendSubscribeSynchronized(String channel, Protocol.SubscribeRequest return; } try { - this.handleSubscribeReply(channel, reply); + this.handleSubscribeReply(sub, unsubscribeCount, reply); } catch (Exception e) { // Should never happen. e.printStackTrace(); @@ -659,11 +660,19 @@ void sendSubscribe(Subscription sub, Protocol.SubscribeRequest req) { // client will be connected. return; } - this.sendSubscribeSynchronized(sub.getChannel(), req); + this.sendSubscribeSynchronized(sub, req); } + /** + * Writes the unsubscribe command at once. Called on the executor before the + * unsubscribed event is emitted, so a subscribe() made after unsubscribe() — or + * from its handler — always reaches the server after the unsubscribe. Deferring + * the write to another executor task let an already queued subscribe() go first: + * the server answered 105 (already subscribed) and the late unsubscribe then + * removed the new subscription (as centrifuge-js writes first). + */ void sendUnsubscribe(String channel) { - this.executor.submit(() -> Client.this.sendUnsubscribeSynchronized(channel)); + this.sendUnsubscribeSynchronized(channel); } private void sendUnsubscribeSynchronized(String channel) { @@ -804,9 +813,14 @@ public void removeSubscription(Subscription sub) { } } - private void handleSubscribeReply(String channel, Protocol.Reply reply) throws Exception { - Subscription sub = this.getSub(channel); - if (sub != null) { + private void handleSubscribeReply(Subscription sub, long unsubscribeCount, Protocol.Reply reply) throws Exception { + if (this.getSub(sub.getChannel()) != sub || sub.getUnsubscribeCount() != unsubscribeCount) { + // The subscription was unsubscribed (and maybe subscribed again) or removed + // since this subscribe was sent: the reply belongs to a subscribe the server + // was told to end, not to the attempt in progress now. + return; + } + { if (sub.getState() != SubscriptionState.SUBSCRIBING) { // The subscription left SUBSCRIBING while the subscribe command was // still in flight — e.g. unsubscribe() called right after subscribe(), diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index 258e095..e9b5458 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -38,6 +38,11 @@ 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; Subscription(final Client client, final String channel, final SubscriptionEventListener listener, final SubscriptionOptions options) { this.client = client; @@ -63,6 +68,10 @@ public class Subscription { this(client, channel, listener, new SubscriptionOptions()); } + long getUnsubscribeCount() { + return unsubscribeCount; + } + void setState(SubscriptionState state) { this.state = state; } @@ -454,6 +463,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) { diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeOrderTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeOrderTest.java new file mode 100644 index 0000000..19d5f56 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/UnsubscribeOrderTest.java @@ -0,0 +1,137 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * unsubscribe() writes its command before anything queued after it, and a subscribe + * reply is only applied to the subscribe attempt that sent it. + */ +public class UnsubscribeOrderTest { + + private FakeCentrifugoServer server; + private Client client; + + @Before + public void setUp() throws IOException { + server = new FakeCentrifugoServer(); + server.start(); + } + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + server.stop(); + } + + private List subscriptionCommands(String channel) { + List out = new ArrayList<>(); + for (Protocol.Command cmd : server.received()) { + if (cmd.hasSubscribe() && cmd.getSubscribe().getChannel().equals(channel)) { + out.add("subscribe"); + } else if (cmd.hasUnsubscribe() && cmd.getUnsubscribe().getChannel().equals(channel)) { + out.add("unsubscribe"); + } + } + return out; + } + + private Client connectedClient() throws InterruptedException { + CountDownLatch connected = new CountDownLatch(1); + client = new Client(server.url(), new Options(), new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + }); + client.connect(); + assertTrue("connected", connected.await(5, TimeUnit.SECONDS)); + return client; + } + + /** + * unsubscribe() then subscribe() from the app: the server must get the unsubscribe + * before the new subscribe. Sent the other way round, the server answers the + * subscribe with 105 (already subscribed) and the late unsubscribe then ends the + * new subscription. + */ + @Test + public void testUnsubscribeThenSubscribeReachesServerInOrder() throws Exception { + connectedClient(); + LinkedBlockingQueue subscribed = new LinkedBlockingQueue<>(); + Subscription sub = client.newSubscription("order", new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + subscribed.add(e); + } + }); + sub.subscribe(); + assertNotNull("first subscribe", subscribed.poll(5, TimeUnit.SECONDS)); + + sub.unsubscribe(); + sub.subscribe(); + + assertNotNull("subscribed again", subscribed.poll(5, TimeUnit.SECONDS)); + assertEquals(java.util.Arrays.asList("subscribe", "unsubscribe", "subscribe"), subscriptionCommands("order")); + assertEquals(SubscriptionState.SUBSCRIBED, sub.getState()); + } + + /** + * subscribe(), unsubscribe(), subscribe() while the first subscribe reply is held: + * that reply belongs to a subscribe the server was told to end, so it must not + * complete the second attempt — only the second reply does. + */ + @Test + public void testReplyOfEndedSubscribeAttemptIsIgnored() throws Exception { + AtomicInteger attempts = new AtomicInteger(); + server.onSubscribe = (channel, req) -> Protocol.SubscribeResult.newBuilder() + .setData(com.google.protobuf.ByteString.copyFromUtf8(String.valueOf(attempts.incrementAndGet()))) + .build(); + CountDownLatch bothSent = new CountDownLatch(2); + server.deferCommand = cmd -> { + if (cmd.hasSubscribe()) { + bothSent.countDown(); + return true; + } + return false; + }; + connectedClient(); + LinkedBlockingQueue subscribed = new LinkedBlockingQueue<>(); + Subscription sub = client.newSubscription("toggle", new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + subscribed.add(e); + } + }); + + sub.subscribe(); + sub.unsubscribe(); + sub.subscribe(); + assertTrue("both subscribes sent", bothSent.await(5, TimeUnit.SECONDS)); + server.releaseDeferredCommands(); + + SubscribedEvent event = subscribed.poll(5, TimeUnit.SECONDS); + assertNotNull("subscribed", event); + assertEquals("completed by the second attempt's reply", "2", new String(event.getData(), StandardCharsets.UTF_8)); + assertNull("subscribed once", subscribed.poll(300, TimeUnit.MILLISECONDS)); + assertEquals(java.util.Arrays.asList("subscribe", "unsubscribe", "subscribe"), subscriptionCommands("toggle")); + } +} From d9c2c28ea4a8b56416a67df13f6c3a58dd7e86e1 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:37:28 +0300 Subject: [PATCH 02/11] Tear the transport down in the teardown and bound the handshake by the client timeout The teardown only sent a close frame and left the reconnect to the socket's onClosed/onFailure callback. OkHttp delivers that callback once the peer answers the close frame, or after 60s when it never does: after "no ping", a subscribe or connect timeout on a dead or half-open link, the client stayed connecting for a minute before its next attempt. The teardown now closes the socket (or cancels it while its handshake is still pending), ignores its later callbacks, and schedules the reconnect itself, before any event is emitted. The WebSocket handshake had no SDK timeout: a server accepting TCP but never answering the upgrade was bounded only by OkHttp's read timeout (10s by default, none in an app-supplied OkHttpClient), and disconnect() left the handshake socket open until then. The attempt now fails after the client timeout with a "connect timeout" error and reconnects (as centrifuge-js), with a grace period when the timer runs late after a process suspension. A replaced socket that completes its handshake late is closed. --- .../github/centrifugal/centrifuge/Client.java | 120 ++++++++++-- .../centrifuge/TransportTeardownTest.java | 179 ++++++++++++++++++ 2 files changed, 281 insertions(+), 18 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index e60e234..e47382c 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -34,6 +34,10 @@ public class Client { private WebSocket ws; + // Whether the current ws completed its handshake (executor-owned). + private boolean wsOpen; + // Fails the current ws if it doesn't open within the timeout (executor-owned). + private ScheduledFuture openTimeoutTask; private OkHttpClient httpClient; // Whether httpClient was built from scratch (no user-supplied base client), // meaning its Dispatcher and ConnectionPool are ours to dispose. Recorded @@ -83,6 +87,11 @@ ScheduledExecutorService getScheduler() { } private static final int NORMAL_CLOSURE_STATUS = 1000; + // A timer running at least this late means the process didn't run meanwhile (e.g. + // it was suspended): data that arrived meanwhile gets LATE_TIMER_GRACE_MS to be + // handled first, as centrifuge-js lateCallTimer / lateCallGrace. + static final long LATE_TIMER_MS = 1000; + static final long LATE_TIMER_GRACE_MS = 1000; private static final int MESSAGE_SIZE_LIMIT_EXCEEDED_STATUS = 1009; static final int DISCONNECTED_DISCONNECT_CALLED = 0; @@ -211,10 +220,12 @@ public boolean close(long awaitMilliseconds) throws InterruptedException { // so any future-cleanup tasks scheduled by processDisconnect // (e.g. orTimeout/exceptionally re-submits) get queued before // we mark the executor shutdown. + WebSocket last = Client.this.ws; Client.this.processDisconnect(DISCONNECTED_DISCONNECT_CALLED, "client closed", false); Client.this.setState(ClientState.CLOSED); - if (Client.this.ws != null) { - Client.this.ws.cancel(); + if (last != null) { + // The teardown sent a close frame; don't wait for the peer. + last.cancel(); } // Release dispatcher threads + pooled connections on transports // we built from scratch. When the user supplied a base client, @@ -287,6 +298,12 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { this.setState(ClientState.DISCONNECTED); } + // Drop the transport before any event: a handler may connect again. Its + // callbacks are ignored from now on, and the reconnect below doesn't wait for + // its close callback, which OkHttp delivers only once the peer answers the + // close frame — up to 60s later on a dead or half-open link. + this.closeTransport(); + // Channel compaction IDs are scoped to a server session — drop the routing // registry; each resubscribe re-registers a fresh ID. The per-subscription // pushId field is left as-is: moveToSubscribed re-registers it on the next @@ -332,7 +349,43 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { } } - this.ws.close(NORMAL_CLOSURE_STATUS, null); + if (shouldReconnect) { + // A handler may have called disconnect() meanwhile: scheduleReconnect checks. + this.scheduleReconnect(); + } + } + + /** + * Closes the current transport and forgets it. An open socket gets a normal close + * frame; a socket still in its handshake is cancelled, so its handshake doesn't + * outlive the attempt. + */ + private void closeTransport() { + if (this.openTimeoutTask != null) { + this.openTimeoutTask.cancel(false); + this.openTimeoutTask = null; + } + WebSocket transport = this.ws; + boolean open = this.wsOpen; + this.ws = null; + this.wsOpen = false; + if (transport == null) { + return; + } + if (open) { + transport.close(NORMAL_CLOSURE_STATUS, null); + } else { + transport.cancel(); + } + } + + /** + * Fails the current attempt: an error event, then a teardown that reconnects with + * backoff (as centrifuge-js failTransport). + */ + private void failTransport(Throwable error) { + this.processDisconnect(CONNECTING_TRANSPORT_CLOSED, "transport closed", true); + this.listener.onError(this, new ErrorEvent(error)); } private void _connect() { @@ -349,9 +402,7 @@ private void _connect() { .addHeader("Sec-WebSocket-Protocol", "centrifuge-protobuf") .build(); - if (this.ws != null) { - this.ws.cancel(); - } + this.closeTransport(); // If we previously built our own OkHttpClient from scratch, release its // dispatcher threads and pooled connections before building a new one. @@ -417,8 +468,16 @@ public void onOpen(WebSocket webSocket, Response response) { // ws is guaranteed to be assigned. Matches centrifuge-js, // which ignores callbacks from a non-actual transport. if (Client.this.ws != webSocket) { + // A replaced socket that completed its handshake late: + // nothing else will close it. + webSocket.close(NORMAL_CLOSURE_STATUS, null); return; } + Client.this.wsOpen = true; + if (Client.this.openTimeoutTask != null) { + Client.this.openTimeoutTask.cancel(false); + Client.this.openTimeoutTask = null; + } try { Client.this.handleConnectionOpen(); } catch (Throwable e) { @@ -514,9 +573,6 @@ public void onClosed(WebSocket webSocket, int code, String reason) { if (Client.this.getState() != ClientState.DISCONNECTED) { Client.this.processDisconnect(disconnectCode, disconnectReason, reconnect); } - if (Client.this.getState() == ClientState.CONNECTING) { - Client.this.scheduleReconnect(); - } }); } catch (RejectedExecutionException ignored) { } @@ -533,11 +589,6 @@ public void onFailure(WebSocket webSocket, Throwable t, Response response) { Integer responseCode = (response != null) ? response.code() : null; listener.onError(Client.this, new ErrorEvent(t, responseCode)); Client.this.processDisconnect(CONNECTING_TRANSPORT_CLOSED, "transport closed", true); - if (Client.this.getState() == ClientState.CONNECTING) { - // We need to schedule reconnect from here, since onClosed won't be called - // after onFailure. - Client.this.scheduleReconnect(); - } }); } catch (RejectedExecutionException ignored) { } @@ -551,6 +602,36 @@ public void onFailure(WebSocket webSocket, Throwable t, Response response) { previousHttpClient.dispatcher().executorService().shutdown(); previousHttpClient.connectionPool().evictAll(); } + + // Bound the handshake by the client timeout, as the connect reply is: OkHttp's + // own limits (10s connect and read by default, or none in an app-supplied + // OkHttpClient) are not the SDK's. A timer that runs late (the process was + // suspended) first lets an open callback already queued run. + final WebSocket openingWs = this.ws; + final long openDue = System.nanoTime() / 1_000_000 + this.opts.getTimeout(); + this.openTimeoutTask = this.scheduler.schedule(() -> this.submitOrDrop(() -> { + if (Client.this.ws != openingWs || Client.this.wsOpen) { + return; + } + long late = System.nanoTime() / 1_000_000 - openDue; + if (late >= LATE_TIMER_MS) { + Client.this.openTimeoutTask = Client.this.scheduler.schedule(() -> Client.this.submitOrDrop(() -> { + if (Client.this.ws == openingWs && !Client.this.wsOpen) { + Client.this.failTransport(new java.util.concurrent.TimeoutException("connect timeout")); + } + }), LATE_TIMER_GRACE_MS, TimeUnit.MILLISECONDS); + return; + } + Client.this.failTransport(new java.util.concurrent.TimeoutException("connect timeout")); + }), this.opts.getTimeout(), TimeUnit.MILLISECONDS); + } + + /** Submits to the executor, dropping the task once the client is closed. */ + private void submitOrDrop(Runnable task) { + try { + this.executor.submit(task); + } catch (RejectedExecutionException ignored) { + } } private void handleConnectionOpen() { @@ -580,7 +661,7 @@ private void handleConnectionOpen() { return; } Client.this.listener.onError(Client.this, new ErrorEvent(new TokenError(err))); - this.ws.close(NORMAL_CLOSURE_STATUS, ""); + Client.this.processDisconnect(CONNECTING_TRANSPORT_CLOSED, "transport closed", true); return; } if (token == null) { @@ -613,6 +694,9 @@ private void scheduleReconnect() { if (this.getState() != ClientState.CONNECTING) { return; } + if (this.reconnectTask != null) { + this.reconnectTask.cancel(false); + } this.reconnectTask = this.scheduler.schedule( Client.this::startReconnecting, Client.this.backoff.duration(this.reconnectAttempts, this.opts.getMinReconnectDelay(), this.opts.getMaxReconnectDelay()), @@ -862,9 +946,9 @@ private void handleConnectReply(Protocol.Reply reply) { this.handleConnectionError(new ReplyError(reply.getError().getCode(), reply.getError().getMessage(), reply.getError().getTemporary())); if (reply.getError().getCode() == 109) { // Token expired. this.refreshRequired = true; - this.ws.close(NORMAL_CLOSURE_STATUS, ""); + this.processDisconnect(CONNECTING_TRANSPORT_CLOSED, "transport closed", true); } else if (reply.getError().getTemporary()) { - this.ws.close(NORMAL_CLOSURE_STATUS, ""); + this.processDisconnect(CONNECTING_TRANSPORT_CLOSED, "transport closed", true); } else { this.processDisconnect(reply.getError().getCode(), reply.getError().getMessage(), false); } @@ -1092,7 +1176,7 @@ private void sendConnect() { return; } Client.this.handleConnectionError(e); - Client.this.ws.close(NORMAL_CLOSURE_STATUS, ""); + Client.this.processDisconnect(CONNECTING_TRANSPORT_CLOSED, "transport closed", true); }); return null; }); diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java new file mode 100644 index 0000000..d4093c2 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java @@ -0,0 +1,179 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.io.InputStream; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * The client tears its transport down itself and doesn't wait for the socket's close + * callback, and a WebSocket handshake is bounded by the client timeout. + */ +public class TransportTeardownTest { + + private Client client; + private FakeCentrifugoServer server; + private ServerSocket silent; + private final List accepted = new CopyOnWriteArrayList<>(); + + @After + public void tearDown() throws Exception { + if (client != null) { + client.close(1000); + } + if (server != null) { + server.stop(); + } + if (silent != null) { + silent.close(); + } + for (Socket s : accepted) { + s.close(); + } + } + + private int connectCommands() { + int n = 0; + for (Protocol.Command cmd : server.received()) { + if (cmd.hasConnect()) { + n++; + } + } + return n; + } + + /** + * A dead link: the server stops sending pings and never answers the client's close + * frame. After "no ping" the client must reconnect within its backoff, not after + * OkHttp gives up waiting for the peer's close frame (60s). + */ + @Test + public void testReconnectAfterNoPingDoesNotWaitForPeerClose() throws Exception { + server = new FakeCentrifugoServer(); + server.connectResult = Protocol.ConnectResult.newBuilder() + .setClient("fake-client").setVersion("0.0.0").setPing(1).build(); + server.start(); + Options opts = new Options(); + opts.setMaxServerPingDelay(300); + opts.setMinReconnectDelay(100); + opts.setMaxReconnectDelay(200); + LinkedBlockingQueue noPing = new LinkedBlockingQueue<>(); + client = new Client(server.url(), opts, new EventListener() { + @Override + public void onConnecting(Client c, ConnectingEvent e) { + if (e.getCode() == Client.CONNECTING_NO_PING) { + noPing.add(System.nanoTime()); + } + } + }); + client.connect(); + assertNotNull("no ping detected", noPing.poll(5, TimeUnit.SECONDS)); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (connectCommands() < 2 && System.nanoTime() < deadline) { + Thread.sleep(20); + } + assertTrue("reconnected within 5s of no ping, connect commands: " + connectCommands(), connectCommands() >= 2); + } + + private int startSilentServer() throws IOException { + silent = new ServerSocket(0); + Thread acceptor = new Thread(() -> { + try { + while (true) { + accepted.add(silent.accept()); + } + } catch (IOException ignored) { + } + }); + acceptor.setDaemon(true); + acceptor.start(); + return silent.getLocalPort(); + } + + /** + * A server that accepts TCP but never answers the upgrade: the attempt fails after the + * client timeout with an error, and the client tries again. Before, only OkHttp's read + * timeout (10s) ended it, whatever the client timeout. + */ + @Test + public void testHungHandshakeFailsAfterClientTimeout() throws Exception { + int port = startSilentServer(); + Options opts = new Options(); + opts.setTimeout(500); + opts.setMinReconnectDelay(100); + opts.setMaxReconnectDelay(200); + LinkedBlockingQueue errors = new LinkedBlockingQueue<>(); + client = new Client("ws://127.0.0.1:" + port + "/connection/websocket", opts, new EventListener() { + @Override + public void onError(Client c, ErrorEvent e) { + errors.add(e.getError()); + } + }); + long start = System.nanoTime(); + client.connect(); + Throwable error = errors.poll(3, TimeUnit.SECONDS); + assertNotNull("an error within 3s", error); + assertTrue("connect timeout, got " + error, error instanceof TimeoutException); + assertTrue("after the client timeout", System.nanoTime() - start >= TimeUnit.MILLISECONDS.toNanos(450)); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); + while (accepted.size() < 2 && System.nanoTime() < deadline) { + Thread.sleep(20); + } + assertTrue("a new attempt, sockets accepted: " + accepted.size(), accepted.size() >= 2); + assertEquals(ClientState.CONNECTING, client.getState()); + } + + /** disconnect() during a hung handshake closes its socket at once. */ + @Test + public void testDisconnectAbortsHungHandshake() throws Exception { + int port = startSilentServer(); + Options opts = new Options(); + opts.setTimeout(5000); + CountDownLatch disconnected = new CountDownLatch(1); + client = new Client("ws://127.0.0.1:" + port + "/connection/websocket", opts, new EventListener() { + @Override + public void onDisconnected(Client c, DisconnectedEvent e) { + disconnected.countDown(); + } + }); + client.connect(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); + while (accepted.isEmpty() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertEquals("handshake started", 1, accepted.size()); + client.disconnect(); + assertTrue(disconnected.await(3, TimeUnit.SECONDS)); + Socket s = accepted.get(0); + s.setSoTimeout(1500); + InputStream in = s.getInputStream(); + long closedAfter = -1; + long start = System.nanoTime(); + try { + byte[] buf = new byte[4096]; + while (in.read(buf) >= 0) { + // The request bytes of the handshake; read until the client closes. + } + closedAfter = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + } catch (java.net.SocketTimeoutException e) { + // Still open after 1.5s. + } catch (IOException e) { + closedAfter = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + } + assertTrue("the client closed the handshake socket within 1.5s of disconnect()", closedAfter >= 0); + } +} From 2229a54706345aca3018b394e1048bea0a193e81 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:39:55 +0300 Subject: [PATCH 03/11] Apply pushes only to a subscription in the state they are for - Publications, join and leave are delivered only while the subscription is subscribed. A publication already on its way when the app called unsubscribe(), or one sent before a resubscribe, was delivered to the unsubscribed or subscribing subscription and moved its stored position past it, so a later subscribe could skip or repeat it. - An unsubscribe push is applied only to a subscribed subscription. It also ends previous subscriptions: a resubscribe code (2500) arriving after the app's unsubscribe() subscribed the channel again. - While a server-side subscription holds a channel and the client-side subscription object of that channel isn't subscribed, pushes go to the server-side one; they were taken by the unsubscribed object and lost . - An unsubscribe error reply now reconnects, as an unsubscribe timeout does: the server may still hold the subscription. All as centrifuge-js does. --- .../github/centrifugal/centrifuge/Client.java | 43 ++++- .../centrifugal/centrifuge/PushStateTest.java | 158 ++++++++++++++++++ 2 files changed, 198 insertions(+), 3 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/PushStateTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index e47382c..0a72ed7 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -772,11 +772,17 @@ private void sendUnsubscribeSynchronized(String channel) { .setUnsubscribe(req) .build(); + final WebSocket unsubscribeWs = this.ws; CompletableFuture f = new CompletableFuture<>(); this.futures.put(cmd.getId(), f); f.thenAccept(reply -> { - // No need to handle reply for now. this.futures.remove(cmd.getId()); + if (reply.getError().getCode() != 0 && this.ws == unsubscribeWs && this.getState() == ClientState.CONNECTED) { + // The server may still hold the subscription: its publications would + // reach an unsubscribed subscription, and a new subscribe would get 105. + // A new connection starts from a clean server state (as centrifuge-js). + this.processDisconnect(CONNECTING_UNSUBSCRIBE_ERROR, "unsubscribe error", true); + } }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { this.executor.submit(() -> { if (Client.this.getState() != ClientState.CONNECTED) { @@ -822,11 +828,21 @@ void updateSubscriptionPushId(Subscription sub, long oldId, long newId) { // Resolve a client-side subscription for a push: by numeric channel ID when // channel compaction is in use (the push then has no channel name), by channel // name otherwise. + /** + * The client-side subscription a push is for. While a server-side subscription holds + * the channel and the client-side one isn't subscribed, the push belongs to the + * server-side one: the server allows one subscription per channel (as + * centrifuge-js _getSubForPush). + */ private Subscription getSubForPush(String channel, long id) { if (id > 0) { return this.subsById.get(id); } - return this.subs.get(channel); + Subscription sub = this.subs.get(channel); + if (sub != null && sub.getState() != SubscriptionState.SUBSCRIBED && this.serverSubs.containsKey(channel)) { + return null; + } + return sub; } private ServerSubscription getServerSub(String channel) { @@ -1209,6 +1225,12 @@ void handlePub(String channel, Protocol.Publication pub, long id) throws Excepti ClientInfo info = ClientInfo.fromProtocolClientInfo(pub.getInfo()); Subscription sub = this.getSubForPush(channel, id); if (sub != null) { + if (sub.getState() != SubscriptionState.SUBSCRIBED) { + // E.g. a publication already on its way when the app called + // unsubscribe(), or one sent before a resubscribe: the app doesn't + // expect it, and the stored position must not move past it. + return; + } sub.handlePublication(pub); } else if (id > 0) { // Compacted push with unknown ID (e.g. already unsubscribed) — drop. @@ -1245,8 +1267,17 @@ private void handleSubscribe(String channel, Protocol.Subscribe sub) { } private void handleUnsubscribe(String channel, Protocol.Unsubscribe unsubscribe) { - Subscription sub = this.getSub(channel); + Subscription sub = this.getSubForPush(channel, 0); if (sub != null) { + if (sub.getState() != SubscriptionState.SUBSCRIBED) { + // It ends a previous subscription: one the app unsubscribed, or one that + // raced unsubscribe() and subscribe() of the app. The server unsubscribes + // a subscription in progress only after replying to its subscribe, and + // sends the push also when the subscription is already gone. A resubscribe + // code must not subscribe again, nor invalidate the state of a subscribe + // in progress (as centrifuge-js). + return; + } if (unsubscribe.getCode() < 2500) { sub.moveToUnsubscribed(false, unsubscribe.getCode(), unsubscribe.getReason()); } else { @@ -1271,6 +1302,9 @@ private void handleJoin(String channel, Protocol.Join join, long id) { ClientInfo info = ClientInfo.fromProtocolClientInfo(join.getInfo()); Subscription sub = this.getSubForPush(channel, id); if (sub != null) { + if (sub.getState() != SubscriptionState.SUBSCRIBED) { + return; + } JoinEvent event = new JoinEvent(); event.setInfo(info); sub.getListener().onJoin(sub, event); @@ -1291,6 +1325,9 @@ private void handleLeave(String channel, Protocol.Leave leave, long id) { Subscription sub = this.getSubForPush(channel, id); if (sub != null) { + if (sub.getState() != SubscriptionState.SUBSCRIBED) { + return; + } event.setInfo(info); sub.getListener().onLeave(sub, event); } else if (id > 0) { diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/PushStateTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/PushStateTest.java new file mode 100644 index 0000000..1de09e7 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/PushStateTest.java @@ -0,0 +1,158 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Pushes are applied only to a subscription in the state they are for. + */ +public class PushStateTest { + + private FakeCentrifugoServer server; + private Client client; + private final LinkedBlockingQueue clientEvents = new LinkedBlockingQueue<>(); + private final LinkedBlockingQueue subEvents = new LinkedBlockingQueue<>(); + + @Before + public void setUp() throws IOException { + server = new FakeCentrifugoServer(); + } + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + server.stop(); + } + + private void connect() throws Exception { + server.start(); + CountDownLatch connected = new CountDownLatch(1); + client = new Client(server.url(), new Options(), new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + + @Override + public void onConnecting(Client c, ConnectingEvent e) { + clientEvents.add("connecting:" + e.getCode()); + } + + @Override + public void onPublication(Client c, ServerPublicationEvent e) { + clientEvents.add("server_publication:" + e.getChannel()); + } + }); + client.connect(); + assertTrue("connected", connected.await(5, TimeUnit.SECONDS)); + // Only the events after the first connect count. + clientEvents.clear(); + } + + private Subscription newSub(String channel) throws Exception { + return client.newSubscription(channel, new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + subEvents.add("subscribed"); + } + + @Override + public void onSubscribing(Subscription s, SubscribingEvent e) { + subEvents.add("subscribing:" + e.getCode()); + } + + @Override + public void onUnsubscribed(Subscription s, UnsubscribedEvent e) { + subEvents.add("unsubscribed:" + e.getCode()); + } + + @Override + public void onPublication(Subscription s, PublicationEvent e) { + subEvents.add("publication:" + new String(e.getData(), StandardCharsets.UTF_8)); + } + }); + } + + private Subscription subscribedThenUnsubscribed(String channel) throws Exception { + Subscription sub = newSub(channel); + sub.subscribe(); + assertEquals("subscribing:0", subEvents.poll(5, TimeUnit.SECONDS)); + assertEquals("subscribed", subEvents.poll(5, TimeUnit.SECONDS)); + sub.unsubscribe(); + assertEquals("unsubscribed:0", subEvents.poll(5, TimeUnit.SECONDS)); + return sub; + } + + /** A publication already on its way when the app unsubscribed is not delivered. */ + @Test + public void testPublicationAfterUnsubscribeIsNotDelivered() throws Exception { + connect(); + Subscription sub = subscribedThenUnsubscribed("news"); + server.publishChannel("news", "late".getBytes(StandardCharsets.UTF_8)); + assertNull("nothing after unsubscribed", subEvents.poll(500, TimeUnit.MILLISECONDS)); + assertEquals(SubscriptionState.UNSUBSCRIBED, sub.getState()); + } + + /** + * An unsubscribe push with a resubscribe code for a subscription the app unsubscribed + * ends that previous subscription: it must not subscribe again. + */ + @Test + public void testResubscribePushAfterUnsubscribeIsIgnored() throws Exception { + connect(); + Subscription sub = subscribedThenUnsubscribed("news"); + server.unsubscribePush("news", 2500, "insufficient state"); + assertNull("no resubscribe", subEvents.poll(500, TimeUnit.MILLISECONDS)); + assertEquals(SubscriptionState.UNSUBSCRIBED, sub.getState()); + } + + /** + * A server-side subscription's publication goes to the client listener even when the app + * keeps an unsubscribed client-side subscription object for the same channel. + */ + @Test + public void testServerSidePublicationIsNotTakenByUnsubscribedClientSideObject() throws Exception { + server.connectResult = Protocol.ConnectResult.newBuilder() + .setClient("fake-client").setVersion("0.0.0").setPing(25) + .putSubs("shared", Protocol.SubscribeResult.newBuilder().build()) + .build(); + connect(); + newSub("shared"); + server.publishChannel("shared", "srv".getBytes(StandardCharsets.UTF_8)); + String event = clientEvents.poll(2, TimeUnit.SECONDS); + assertEquals("server_publication:shared", event); + assertNull("nothing on the client-side object", subEvents.poll(300, TimeUnit.MILLISECONDS)); + } + + /** + * An unsubscribe error reply: the server may still hold the subscription, so the client + * reconnects to start from a clean server state (as on an unsubscribe timeout). + */ + @Test + public void testUnsubscribeErrorReplyReconnects() throws Exception { + server.onCommand = cmd -> cmd.hasUnsubscribe() + ? Protocol.Reply.newBuilder().setId(cmd.getId()) + .setError(Protocol.Error.newBuilder().setCode(100).setMessage("internal").build()).build() + : null; + connect(); + subscribedThenUnsubscribed("news"); + String event = clientEvents.poll(3, TimeUnit.SECONDS); + assertNotNull("reconnect after the unsubscribe error", event); + assertEquals("connecting:" + Client.CONNECTING_UNSUBSCRIBE_ERROR, event); + } +} From 1e797872b93946e0a7ed9ab8a7ce63744750e9a5 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:43:56 +0300 Subject: [PATCH 04/11] Keep tokens that no token getter can replace - State invalidation (3014, 2502) cleared the connection and subscription tokens even without a token getter: a client with a static token, or an anonymous one, stopped on a local configuration error, and a subscription with a static token resubscribed without it, was denied (103) and ended unsubscribed. Now only a token a getter can replace is cleared; the client and subscriptions reconnect with what they have. - After a token expired error (109) without a getter, setToken() + connect() kept failing on a local configuration error: setToken() now clears the "new token required" flag when there is no getter. - A subscription token expired error (109) without a getter resubscribed without the token: now a configuration error and unsubscribed as unauthorized, like a connection. All as centrifuge-js does. StateInvalidationTest expected the static subscription token to be dropped on 3014/2502; it now expects it kept. --- .../github/centrifugal/centrifuge/Client.java | 18 +- .../centrifugal/centrifuge/Subscription.java | 15 +- .../centrifuge/StateInvalidationTest.java | 16 +- .../centrifuge/StaticTokenTest.java | 170 ++++++++++++++++++ 4 files changed, 209 insertions(+), 10 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/StaticTokenTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index 0a72ed7..348b58a 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -200,6 +200,14 @@ public void disconnect() { public void setToken(String token) { this.executor.submit(() -> { Client.this.token = token; + if (Client.this.opts.getTokenGetter() == null) { + // The token expired (109) and the app set a new one: without a token + // getter there is no other way to get it, so the next attempt uses it + // instead of failing on a configuration error. With a getter, the next + // attempt still fetches a new token: the one set meanwhile may be the + // expired one (as centrifuge-js). + Client.this.refreshRequired = false; + } }); } @@ -259,8 +267,14 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { // push, both funnel here): drop the connection token so the next connect // fetches a fresh one via the token getter, and invalidate every // subscription's cached state before reconnecting. - this.token = ""; - this.refreshRequired = true; + // Without a token getter there is no new token to get: keep the token the + // client has (or none) and reconnect with it. The server rejects it if it's + // no longer valid, instead of the client stopping on a local configuration + // error (as centrifuge-js). + if (this.opts.getTokenGetter() != null) { + this.token = ""; + this.refreshRequired = true; + } for (Subscription sub : this.subs.values()) { sub.invalidateState(); } diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index e9b5458..1876ff8 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -286,6 +286,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 = ""; @@ -635,7 +644,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; diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/StateInvalidationTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/StateInvalidationTest.java index c7d2f20..49d2502 100644 --- a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/StateInvalidationTest.java +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/StateInvalidationTest.java @@ -54,7 +54,7 @@ private Protocol.ConnectRequest lastConnect() { } @Test - public void testUnsubscribe2502ClearsSubTokenAndResubscribes() throws Exception { + public void testUnsubscribe2502KeepsStaticSubTokenAndResubscribes() throws Exception { LinkedBlockingQueue subscribedQ = new LinkedBlockingQueue<>(); CountDownLatch connected = new CountDownLatch(1); Options opts = new Options(); @@ -75,12 +75,13 @@ public void testUnsubscribe2502ClearsSubTokenAndResubscribes() throws Exception assertNotNull("subscribed", subscribedQ.poll(5, TimeUnit.SECONDS)); assertEquals("initial subscribe carries the token", "sub-token-0", lastSubscribe().getToken()); - // Server sends "state invalidated" unsubscribe — the subscription must - // drop its token and resubscribe with an empty token (no token getter - // configured, so nothing repopulates it). + // Server sends "state invalidated" unsubscribe. Without a token getter + // nothing could replace the token, so the subscription keeps its static + // token and resubscribes with it: a resubscribe without a token would be + // rejected (103) and end the subscription for good. server.unsubscribePush("ch", Client.UNSUBSCRIBED_STATE_INVALIDATED, "state invalidated"); assertNotNull("resubscribed after 2502", subscribedQ.poll(5, TimeUnit.SECONDS)); - assertEquals("token cleared by 2502", "", lastSubscribe().getToken()); + assertEquals("static token kept after 2502", "sub-token-0", lastSubscribe().getToken()); } finally { client.close(1000); } @@ -156,7 +157,8 @@ public void getConnectionToken(ConnectionTokenEvent e, TokenCallback cb) { // Server sends "state invalidated" disconnect — the client must clear // its connection token, fetch a fresh one via the token getter on - // reconnect, and invalidate the subscription (resubscribe w/o token). + // reconnect, and invalidate the subscription. The subscription has a + // static token and no getter: it keeps the token. server.disconnect(Client.DISCONNECTED_STATE_INVALIDATED, "state invalidated"); assertNotNull("reconnected after 3014", connectedQ.poll(5, TimeUnit.SECONDS)); @@ -164,7 +166,7 @@ public void getConnectionToken(ConnectionTokenEvent e, TokenCallback cb) { assertEquals("reconnect uses freshly fetched token", "conn-token-1", lastConnect().getToken()); assertNotNull("resubscribed after 3014", subscribedQ.poll(5, TimeUnit.SECONDS)); - assertEquals("sub token cleared by 3014", "", lastSubscribe().getToken()); + assertEquals("static sub token kept after 3014", "sub-token-0", lastSubscribe().getToken()); } finally { client.close(1000); } diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/StaticTokenTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/StaticTokenTest.java new file mode 100644 index 0000000..41acc29 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/StaticTokenTest.java @@ -0,0 +1,170 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** + * Clients and subscriptions without a token getter keep the token they have: nothing + * else could replace it. + */ +public class StaticTokenTest { + + private FakeCentrifugoServer server; + private Client client; + private final LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + + @Before + public void setUp() throws IOException { + server = new FakeCentrifugoServer(); + server.start(); + } + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + server.stop(); + } + + private Client newClient(String token) { + Options opts = new Options(); + if (token != null) { + opts.setToken(token); + } + opts.setMinReconnectDelay(50); + opts.setMaxReconnectDelay(100); + client = new Client(server.url(), opts, new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + events.add("connected"); + } + + @Override + public void onDisconnected(Client c, DisconnectedEvent e) { + events.add("disconnected:" + e.getCode()); + } + + @Override + public void onError(Client c, ErrorEvent e) { + events.add("error:" + e.getError().getClass().getSimpleName()); + } + }); + return client; + } + + private List connectTokens() { + List out = new ArrayList<>(); + for (Protocol.Command cmd : server.received()) { + if (cmd.hasConnect()) { + out.add(cmd.getConnect().getToken()); + } + } + return out; + } + + private String nextEvent() throws InterruptedException { + return events.poll(5, TimeUnit.SECONDS); + } + + /** State invalidation (3014) to a client with a static token: it reconnects with that token. */ + @Test + public void testStateInvalidationKeepsStaticToken() throws Exception { + newClient("static").connect(); + assertEquals("connected", nextEvent()); + server.disconnect(Client.DISCONNECTED_STATE_INVALIDATED, "state invalidated"); + assertEquals("connected", nextEvent()); + assertEquals(java.util.Arrays.asList("static", "static"), connectTokens()); + } + + /** State invalidation (3014) to an anonymous client: it reconnects. */ + @Test + public void testStateInvalidationReconnectsAnonymousClient() throws Exception { + newClient(null).connect(); + assertEquals("connected", nextEvent()); + server.disconnect(Client.DISCONNECTED_STATE_INVALIDATED, "state invalidated"); + assertEquals("connected", nextEvent()); + assertEquals(ClientState.CONNECTED, client.getState()); + } + + /** + * After a token expired error (109) without a token getter, the app sets a new token and + * connects again: the new token is used. + */ + @Test + public void testSetTokenAfterExpiredTokenWithoutGetter() throws Exception { + server.onCommand = cmd -> cmd.hasConnect() && cmd.getConnect().getToken().equals("expired") + ? Protocol.Reply.newBuilder().setId(cmd.getId()) + .setError(Protocol.Error.newBuilder().setCode(109).setMessage("token expired").build()).build() + : null; + newClient("expired").connect(); + // 109, then a local configuration error: no getter can get another token. + String event; + do { + event = nextEvent(); + assertNotNull("disconnected after the expired token", event); + } while (!event.startsWith("disconnected:")); + assertEquals("expired", connectTokens().get(0)); + events.clear(); + + client.setToken("fresh"); + client.connect(); + assertEquals("connected with the token set by the app", "connected", nextEvent()); + List tokens = connectTokens(); + assertEquals("fresh", tokens.get(tokens.size() - 1)); + } + + /** + * A subscription token expired (109) without a token getter: a configuration error and + * unsubscribed as unauthorized, not a resubscribe without a token. + */ + @Test + public void testExpiredStaticSubscriptionTokenUnsubscribesUnauthorized() throws Exception { + server.onCommand = cmd -> cmd.hasSubscribe() + ? Protocol.Reply.newBuilder().setId(cmd.getId()) + .setError(Protocol.Error.newBuilder().setCode(109).setMessage("token expired").build()).build() + : null; + newClient(null).connect(); + assertEquals("connected", nextEvent()); + LinkedBlockingQueue subEvents = new LinkedBlockingQueue<>(); + SubscriptionOptions subOpts = new SubscriptionOptions(); + subOpts.setToken("sub-static"); + Subscription sub = client.newSubscription("private:ch", subOpts, new SubscriptionEventListener() { + @Override + public void onError(Subscription s, SubscriptionErrorEvent e) { + subEvents.add("error:" + e.getError().getClass().getSimpleName()); + } + + @Override + public void onUnsubscribed(Subscription s, UnsubscribedEvent e) { + subEvents.add("unsubscribed:" + e.getCode()); + } + }); + sub.subscribe(); + assertEquals("error:ConfigurationError", subEvents.poll(5, TimeUnit.SECONDS)); + assertEquals("unsubscribed:" + Client.UNSUBSCRIBED_UNAUTHORIZED, subEvents.poll(5, TimeUnit.SECONDS)); + Thread.sleep(300); + int subscribes = 0; + for (Protocol.Command cmd : server.received()) { + if (cmd.hasSubscribe()) { + subscribes++; + assertEquals("never subscribes without its token", "sub-static", cmd.getSubscribe().getToken()); + } + } + assertEquals(1, subscribes); + assertNull(subEvents.poll(100, TimeUnit.MILLISECONDS)); + } +} From c1f41f0e9125f1f8996ce4028ceac709835258fd Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:48:31 +0300 Subject: [PATCH 05/11] Never leave a step half-done when app code throws - Token and state getters that throw instead of calling back are treated as calling back with that error: a token error and a retry with backoff. A throwing connection getter stopped the client for good ("bad protocol"); a throwing subscription getter left the subscription subscribing forever, and inside the connect reply's resubscribe loop it left the other subscriptions unsubscribed and the ping timer unarmed. Only the first callback of a getter counts. - An exception while a connect or subscribe reply is handled (e.g. thrown by an onConnected or onSubscribed handler) was only printed: the client stayed connected without its resubscribes and ping timer. It now gets the same visible stop as an exception while a frame is dispatched: an error event, then disconnected with "bad protocol"; connect() works again afterwards. - A handler that throws in connect() or subscribe() no longer stops the connect or subscribe, and one that throws during a teardown no longer stops the other subscriptions from moving to subscribing or the reconnect from being scheduled. - Any exception escaping a client step is reported through onError (UnclassifiedError) instead of vanishing in the executor's Future. As centrifuge-js. --- .../github/centrifugal/centrifuge/Client.java | 153 ++++++++++-- .../centrifugal/centrifuge/Subscription.java | 15 +- .../centrifuge/AppExceptionTest.java | 228 ++++++++++++++++++ 3 files changed, 370 insertions(+), 26 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/AppExceptionTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index 348b58a..52adec4 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -64,7 +64,31 @@ public class Client { private final Map serverSubs = new ConcurrentHashMap<>(); private final Backoff backoff; - private final ExecutorService executor = Executors.newSingleThreadExecutor(); + // Runs every step of the client. An exception escaping a step (e.g. thrown by an app + // event handler) is reported through onError instead of vanishing in the task's + // Future, which left the rest of the step silently undone. + private final ExecutorService executor = new java.util.concurrent.ThreadPoolExecutor( + 1, 1, 0L, TimeUnit.MILLISECONDS, new java.util.concurrent.LinkedBlockingQueue()) { + @Override + protected void afterExecute(Runnable r, Throwable t) { + super.afterExecute(r, t); + if (t == null && r instanceof java.util.concurrent.Future) { + java.util.concurrent.Future future = (java.util.concurrent.Future) r; + if (future.isDone() && !future.isCancelled()) { + try { + future.get(); + } catch (java.util.concurrent.ExecutionException e) { + t = e.getCause(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + if (t != null) { + Client.this.reportUncaught(t); + } + } + }; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); private int pingInterval; private boolean sendPong; @@ -165,6 +189,74 @@ public ClientState getState() { private int _id = 0; + /** Reports an exception that escaped a step, e.g. thrown by an event handler. */ + void reportUncaught(Throwable t) { + try { + this.listener.onError(this, new ErrorEvent(new UnclassifiedError(t))); + } catch (Throwable e) { + // The error handler threw too: nothing left to report to. + e.printStackTrace(); + } + } + + /** + * An exception while handling data from the server (a reply or a push, including an + * app handler run for it): reported, then the client stops visibly with "bad + * protocol", as for a frame that fails to dispatch. Before, exceptions inside reply + * handling were only printed, leaving e.g. a connected client without its + * resubscribes and ping timer. + */ + private void handleDispatchError(Throwable e) { + e.printStackTrace(); + this.reportUncaught(e); + this.processDisconnect(DISCONNECTED_BAD_PROTOCOL, "bad protocol (message)", false); + } + + /** + * Calls an app token getter. A getter that throws instead of calling back is treated + * as calling back with that error; only the first callback counts. + */ + static void fetchConnectionToken(ConnectionTokenGetter getter, ConnectionTokenEvent event, TokenCallback cb) { + TokenCallback once = onceToken(cb); + try { + getter.getConnectionToken(event, once); + } catch (Throwable t) { + once.Done(t, null); + } + } + + static void fetchSubscriptionToken(SubscriptionTokenGetter getter, SubscriptionTokenEvent event, TokenCallback cb) { + TokenCallback once = onceToken(cb); + try { + getter.getSubscriptionToken(event, once); + } catch (Throwable t) { + once.Done(t, null); + } + } + + static void fetchSubscriptionState(SubscriptionStateGetter getter, SubscriptionGetStateEvent event, StateCallback cb) { + java.util.concurrent.atomic.AtomicBoolean done = new java.util.concurrent.atomic.AtomicBoolean(); + StateCallback once = (e, position) -> { + if (done.compareAndSet(false, true)) { + cb.Done(e, position); + } + }; + try { + getter.getSubscriptionState(event, once); + } catch (Throwable t) { + once.Done(t, null); + } + } + + private static TokenCallback onceToken(TokenCallback cb) { + java.util.concurrent.atomic.AtomicBoolean done = new java.util.concurrent.atomic.AtomicBoolean(); + return (e, token) -> { + if (done.compareAndSet(false, true)) { + cb.Done(e, token); + } + }; + } + private int getNextId() { return ++_id; } @@ -180,8 +272,13 @@ public void connect() { Client.this.reconnectAttempts = 0; Client.this.setState(ClientState.CONNECTING); ConnectingEvent event = new ConnectingEvent(CONNECTING_CONNECT_CALLED, "connect called"); - Client.this.listener.onConnecting(Client.this, event); - Client.this._connect(); + try { + Client.this.listener.onConnecting(Client.this, event); + } finally { + // A handler that throws doesn't stop the connect; one that called + // disconnect() queued it after this step. + Client.this._connect(); + } }); } @@ -324,13 +421,30 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { // subscribe reply regardless of whether the server reuses the same ID. this.subsById.clear(); + try { + this.finishTeardown(code, reason, shouldReconnect, previousState, needEvent); + } finally { + if (shouldReconnect) { + // Also when a handler threw. A handler may have called disconnect() + // meanwhile: scheduleReconnect checks the state. + this.scheduleReconnect(); + } + } + } + + /** The part of processDisconnect that emits events: a handler may throw in it. */ + private void finishTeardown(int code, String reason, boolean shouldReconnect, ClientState previousState, boolean needEvent) { synchronized (this.subs) { - for (Map.Entry entry : this.subs.entrySet()) { - Subscription sub = entry.getValue(); + for (Subscription sub : new ArrayList<>(this.subs.values())) { if (sub.getState() == SubscriptionState.UNSUBSCRIBED) { continue; } - sub.moveToSubscribing(SUBSCRIBING_TRANSPORT_CLOSED, "transport closed"); + try { + sub.moveToSubscribing(SUBSCRIBING_TRANSPORT_CLOSED, "transport closed"); + } catch (Throwable t) { + // A handler threw: the other subscriptions must still move. + this.reportUncaught(t); + } } } @@ -348,8 +462,12 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { this.futures.clear(); if (previousState == ClientState.CONNECTED) { - for (Map.Entry entry : this.serverSubs.entrySet()) { - this.listener.onSubscribing(this, new ServerSubscribingEvent(entry.getKey())); + for (String channel : new ArrayList<>(this.serverSubs.keySet())) { + try { + this.listener.onSubscribing(this, new ServerSubscribingEvent(channel)); + } catch (Throwable t) { + this.reportUncaught(t); + } } } @@ -362,11 +480,6 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { this.listener.onDisconnected(this, event); } } - - if (shouldReconnect) { - // A handler may have called disconnect() meanwhile: scheduleReconnect checks. - this.scheduleReconnect(); - } } /** @@ -660,7 +773,7 @@ private void handleConnectionOpen() { return; } final WebSocket connectionWs = this.ws; - this.opts.getTokenGetter().getConnectionToken(connectionTokenEvent, (err, token) -> this.executor.submit(() -> { + Client.fetchConnectionToken(this.opts.getTokenGetter(), connectionTokenEvent, (err, token) -> this.executor.submit(() -> { // If the connection has been replaced (reconnect, disconnect) // since this token request was issued, the callback is stale. if (Client.this.ws != connectionWs) { @@ -734,9 +847,8 @@ private void sendSubscribeSynchronized(Subscription sub, Protocol.SubscribeReque } try { this.handleSubscribeReply(sub, unsubscribeCount, reply); - } catch (Exception e) { - // Should never happen. - e.printStackTrace(); + } catch (Throwable e) { + this.handleDispatchError(e); } this.futures.remove(cmd.getId()); }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { @@ -1092,7 +1204,7 @@ private void sendRefresh() { } this.executor.submit(() -> { final WebSocket refreshWs = Client.this.ws; - Client.this.opts.getTokenGetter().getConnectionToken(new ConnectionTokenEvent(), (err, token) -> Client.this.executor.submit(() -> { + Client.fetchConnectionToken(Client.this.opts.getTokenGetter(), new ConnectionTokenEvent(), (err, token) -> Client.this.executor.submit(() -> { // If the connection has been replaced since this refresh was // issued, the callback (and any token it carries) is stale. if (Client.this.ws != refreshWs) { @@ -1190,9 +1302,8 @@ private void sendConnect() { this.futures.remove(cmd.getId()); try { this.handleConnectReply(reply); - } catch (Exception e) { - // Should never happen. - e.printStackTrace(); + } catch (Throwable e) { + this.handleDispatchError(e); } }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { // A timeout completes the future on the CompletableFuture delay diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index 1876ff8..b46e2dc 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -118,7 +118,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; } @@ -326,8 +326,13 @@ public void subscribe() { 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(); + } }); } @@ -383,7 +388,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; } @@ -410,7 +415,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; } diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/AppExceptionTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/AppExceptionTest.java new file mode 100644 index 0000000..4ede134 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/AppExceptionTest.java @@ -0,0 +1,228 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * An exception thrown by app code (a token getter, an event handler) never leaves the + * client half-way through a step: it is reported, and the client either goes on or + * stops visibly. + */ +public class AppExceptionTest { + + private FakeCentrifugoServer server; + private Client client; + private final LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + + @Before + public void setUp() throws IOException { + server = new FakeCentrifugoServer(); + server.start(); + } + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + server.stop(); + } + + private Options fastOptions() { + Options opts = new Options(); + opts.setMinReconnectDelay(50); + opts.setMaxReconnectDelay(100); + return opts; + } + + private String nextEvent(String prefix) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + String e = events.poll(100, TimeUnit.MILLISECONDS); + if (e != null && e.startsWith(prefix)) { + return e; + } + } + return null; + } + + /** A connection token getter that throws: a token error, then the next attempt connects. */ + @Test + public void testThrowingConnectionTokenGetterRetries() throws Exception { + AtomicInteger calls = new AtomicInteger(); + Options opts = fastOptions(); + opts.setTokenGetter(new ConnectionTokenGetter() { + @Override + public void getConnectionToken(ConnectionTokenEvent event, TokenCallback cb) { + if (calls.incrementAndGet() == 1) { + throw new IllegalStateException("token backend down"); + } + cb.Done(null, "token"); + } + }); + client = new Client(server.url(), opts, new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + events.add("connected"); + } + + @Override + public void onError(Client c, ErrorEvent e) { + events.add("error:" + e.getError().getClass().getSimpleName()); + } + }); + client.connect(); + assertEquals("error:TokenError", nextEvent("error:")); + assertNotNull("connected on the next attempt", nextEvent("connected")); + assertEquals(2, calls.get()); + } + + /** A subscription token getter that throws: a token error, then the resubscribe succeeds. */ + @Test + public void testThrowingSubscriptionTokenGetterRetries() throws Exception { + client = new Client(server.url(), fastOptions(), new EventListener() {}); + client.connect(); + AtomicInteger calls = new AtomicInteger(); + SubscriptionOptions subOpts = new SubscriptionOptions(); + subOpts.setMinResubscribeDelay(50); + subOpts.setMaxResubscribeDelay(100); + subOpts.setTokenGetter(new SubscriptionTokenGetter() { + @Override + public void getSubscriptionToken(SubscriptionTokenEvent event, TokenCallback cb) { + if (calls.incrementAndGet() == 1) { + throw new IllegalStateException("token backend down"); + } + cb.Done(null, "sub-token"); + } + }); + Subscription sub = client.newSubscription("ch", subOpts, new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + events.add("subscribed"); + } + + @Override + public void onError(Subscription s, SubscriptionErrorEvent e) { + events.add("sub_error:" + e.getError().getClass().getSimpleName()); + } + }); + sub.subscribe(); + assertEquals("sub_error:SubscriptionTokenError", nextEvent("sub_error:")); + assertNotNull("subscribed after the retry", nextEvent("subscribed")); + } + + /** A connecting handler that throws doesn't stop connect(): reported, and connected. */ + @Test + public void testThrowingConnectingHandlerDoesNotStopConnect() throws Exception { + client = new Client(server.url(), fastOptions(), new EventListener() { + @Override + public void onConnecting(Client c, ConnectingEvent e) { + throw new IllegalStateException("handler bug"); + } + + @Override + public void onConnected(Client c, ConnectedEvent e) { + events.add("connected"); + } + + @Override + public void onError(Client c, ErrorEvent e) { + events.add("error:" + e.getError().getClass().getSimpleName()); + } + }); + client.connect(); + assertEquals("error:UnclassifiedError", nextEvent("error:")); + assertNotNull("connected", nextEvent("connected")); + } + + /** + * A connected handler that throws while the connect reply is handled: reported, and the + * client stops visibly (bad protocol) instead of staying connected without its + * resubscribes and ping timer. connect() works again afterwards. + */ + @Test + public void testThrowingConnectedHandlerStopsVisibly() throws Exception { + AtomicInteger connects = new AtomicInteger(); + client = new Client(server.url(), fastOptions(), new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + events.add("connected"); + if (connects.incrementAndGet() == 1) { + throw new IllegalStateException("handler bug"); + } + } + + @Override + public void onDisconnected(Client c, DisconnectedEvent e) { + events.add("disconnected:" + e.getCode()); + } + + @Override + public void onError(Client c, ErrorEvent e) { + events.add("error:" + e.getError().getClass().getSimpleName()); + } + }); + client.connect(); + assertEquals("error:UnclassifiedError", nextEvent("error:")); + assertEquals("disconnected:" + Client.DISCONNECTED_BAD_PROTOCOL, nextEvent("disconnected:")); + client.connect(); + assertNotNull("connected again", nextEvent("connected")); + } + + /** + * A subscribing handler that throws during a reconnect teardown: every subscription still + * moves to subscribing and resubscribes after the reconnect. + */ + @Test + public void testThrowingSubscribingHandlerInTeardownDoesNotStopOthers() throws Exception { + CountDownLatch connected = new CountDownLatch(1); + client = new Client(server.url(), fastOptions(), new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + }); + client.connect(); + assertTrue(connected.await(5, TimeUnit.SECONDS)); + LinkedBlockingQueue subscribed = new LinkedBlockingQueue<>(); + Subscription[] subs = new Subscription[3]; + for (int i = 0; i < subs.length; i++) { + final String name = "ch" + i; + subs[i] = client.newSubscription(name, new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + subscribed.add(name); + } + + @Override + public void onSubscribing(Subscription s, SubscribingEvent e) { + if (e.getCode() == Client.SUBSCRIBING_TRANSPORT_CLOSED) { + throw new IllegalStateException("handler bug"); + } + } + }); + subs[i].subscribe(); + } + for (int i = 0; i < subs.length; i++) { + assertNotNull("subscribed", subscribed.poll(5, TimeUnit.SECONDS)); + } + server.disconnect(3001, "reconnect"); + for (int i = 0; i < subs.length; i++) { + assertNotNull("resubscribed after the reconnect: " + i, subscribed.poll(5, TimeUnit.SECONDS)); + } + for (Subscription s : subs) { + assertEquals(SubscriptionState.SUBSCRIBED, s.getState()); + } + } +} From e1730cff579cc084330a7bc29399e216aa31ced3 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:50:07 +0300 Subject: [PATCH 06/11] Remove only the subscription passed, and refuse to subscribe a removed one - removeSubscription() removed whatever subscription held the channel: called again for a subscription removed before, it dropped the newer subscription of the channel from the registry without unsubscribing it. It stayed subscribed on the server while its publications were dropped. - subscribe() on a removed subscription subscribed on the server while the client no longer tracked it: never resubscribed on reconnect, publications dropped. It now throws IllegalStateException. As centrifuge-js. --- .../github/centrifugal/centrifuge/Client.java | 14 ++- .../centrifugal/centrifuge/Subscription.java | 19 ++++ .../centrifuge/RemoveSubscriptionTest.java | 101 ++++++++++++++++++ 3 files changed, 130 insertions(+), 4 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/RemoveSubscriptionTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index 52adec4..f533415 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -1026,16 +1026,22 @@ public Subscription getSubscription(String channel) { /** * Say Client that Subscription should be removed from internal registry. Subscription will be - * automatically unsubscribed before removing. + * automatically unsubscribed before removing. The channel is free for a new subscription at + * once. A Subscription this client doesn't hold (e.g. one removed before, whose channel has a + * new subscription now) is ignored. A removed Subscription can't subscribe again. * * @param sub: Subscription to remove from registry. */ public void removeSubscription(Subscription sub) { synchronized (this.subs) { - sub.unsubscribe(); - if (this.subs.get(sub.getChannel()) != null) { - this.subs.remove(sub.getChannel()); + // A subscription removed before must not remove a newer one of its channel + // (as centrifuge-js). + if (this.subs.get(sub.getChannel()) != sub) { + return; } + this.subs.remove(sub.getChannel()); + sub.markRemoved(); + sub.unsubscribe(); } } diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index b46e2dc..c293ec3 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -43,6 +43,8 @@ public class Subscription { // 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; @@ -68,6 +70,10 @@ public class Subscription { this(client, channel, listener, new SubscriptionOptions()); } + void markRemoved() { + this.removed = true; + } + long getUnsubscribeCount() { return unsubscribeCount; } @@ -320,8 +326,21 @@ 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; } diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/RemoveSubscriptionTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/RemoveSubscriptionTest.java new file mode 100644 index 0000000..6669fd6 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/RemoveSubscriptionTest.java @@ -0,0 +1,101 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.fail; + +public class RemoveSubscriptionTest { + + private FakeCentrifugoServer server; + private Client client; + + @Before + public void setUp() throws Exception { + server = new FakeCentrifugoServer(); + server.start(); + CountDownLatch connected = new CountDownLatch(1); + client = new Client(server.url(), new Options(), new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + }); + client.connect(); + connected.await(5, TimeUnit.SECONDS); + } + + @After + public void tearDown() throws InterruptedException { + client.close(1000); + server.stop(); + } + + private Subscription subscribed(String channel, LinkedBlockingQueue events) throws Exception { + Subscription sub = client.newSubscription(channel, new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + events.add("subscribed"); + } + + @Override + public void onUnsubscribed(Subscription s, UnsubscribedEvent e) { + events.add("unsubscribed"); + } + }); + sub.subscribe(); + assertEquals("subscribed", events.poll(5, TimeUnit.SECONDS)); + return sub; + } + + /** + * removeSubscription() of a subscription removed before must not remove the newer + * subscription to the same channel. + */ + @Test + public void testRemovingOldSubscriptionAgainKeepsNewOne() throws Exception { + LinkedBlockingQueue oldEvents = new LinkedBlockingQueue<>(); + Subscription old = subscribed("ch", oldEvents); + client.removeSubscription(old); + assertEquals("unsubscribed", oldEvents.poll(5, TimeUnit.SECONDS)); + + LinkedBlockingQueue newEvents = new LinkedBlockingQueue<>(); + Subscription fresh = subscribed("ch", newEvents); + int commandsBefore = server.received().size(); + + client.removeSubscription(old); + Thread.sleep(300); + assertSame("the new subscription stays registered", fresh, client.getSubscription("ch")); + assertEquals(SubscriptionState.SUBSCRIBED, fresh.getState()); + for (Protocol.Command cmd : server.received().subList(commandsBefore, server.received().size())) { + if (cmd.hasUnsubscribe()) { + fail("no unsubscribe sent for the new subscription"); + } + } + } + + /** A removed subscription can't subscribe again: the client no longer tracks it. */ + @Test + public void testSubscribeOnRemovedSubscriptionThrows() throws Exception { + LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + Subscription sub = subscribed("ch", events); + client.removeSubscription(sub); + assertNotNull(events.poll(5, TimeUnit.SECONDS)); + try { + sub.subscribe(); + fail("subscribe() on a removed subscription must throw"); + } catch (IllegalStateException expected) { + // expected + } + } +} From b67a3a364364b0b3033e42dd7ad58f4fd6196fe3 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:54:14 +0300 Subject: [PATCH 07/11] Settle every call exactly once, on the client thread, after replies already received Calls (publish, rpc, history, presence, send, subscription calls, and the connect, subscribe, unsubscribe and refresh commands) armed their timeout on the stage after the result handler: - a result callback slower than the timeout was followed by a second, TimeoutException callback; a callback that threw was called again with its own exception; - the timeout failed the call on the CompletableFuture timer thread even when the reply was already received and waiting for the client thread, e.g. behind a slow event handler or after a process suspension: a publish reported as failed although the server accepted it, a "subscribe timeout" reconnect of a healthy connection; - subscription calls ran their timeout callback on that timer thread, concurrently with event handlers. A call now has one timer that hops to the client thread before failing it, so replies already queued are handled first, and a timer running far too late gives a reply still in the socket a grace period. The call settles once, always on the client thread; an exception from its callback is reported through onError. Calls waiting for a connection are failed by disconnect() and close(); after close() they were never called back at all. --- .../github/centrifugal/centrifuge/Client.java | 123 ++++++++++--- .../centrifugal/centrifuge/Subscription.java | 16 +- .../centrifuge/CallSettleTest.java | 168 ++++++++++++++++++ 3 files changed, 273 insertions(+), 34 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallSettleTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index f533415..93dc885 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -356,6 +356,12 @@ public boolean close(long awaitMilliseconds) throws InterruptedException { void processDisconnect(int code, String reason, Boolean shouldReconnect) { if (this.getState() == ClientState.DISCONNECTED || this.getState() == ClientState.CLOSED) { + if (!shouldReconnect) { + // Calls made while disconnected wait for a connection: disconnect() and + // close() end that wait. Before, they waited for their timeout, and after + // close() (whose scheduler no longer runs timers) forever. + this.failPendingCalls(); + } return; } @@ -432,6 +438,13 @@ void processDisconnect(int code, String reason, Boolean shouldReconnect) { } } + private void failPendingCalls() { + // From a copy: a failure handler may register a new call. + for (CompletableFuture f : new ArrayList<>(this.futures.values())) { + f.completeExceptionally(new IOException()); + } + } + /** The part of processDisconnect that emits events: a handler may throw in it. */ private void finishTeardown(int code, String reason, boolean shouldReconnect, ClientState previousState, boolean needEvent) { synchronized (this.subs) { @@ -448,10 +461,7 @@ private void finishTeardown(int code, String reason, boolean shouldReconnect, Cl } } - for (Map.Entry> entry : this.futures.entrySet()) { - CompletableFuture f = entry.getValue(); - f.completeExceptionally(new IOException()); - } + this.failPendingCalls(); // Drop the pending command registry along with the futures: no reply can // arrive for a connection that is gone, and command IDs are never reused. // Failure handlers do remove their own entry, but only after re-checking @@ -753,6 +763,67 @@ public void onFailure(WebSocket webSocket, Throwable t, Response response) { }), this.opts.getTimeout(), TimeUnit.MILLISECONDS); } + private static long nowMs() { + return System.nanoTime() / 1_000_000; + } + + /** + * Settles a call exactly once: with its result, or with an error — a failure of the + * connection, or a TimeoutException after the client timeout. Both handlers run on the + * executor. + * + *

The timer hops to the executor before failing the call, so a reply already received + * and queued is handled first; a timer running far too late (the process was suspended) + * first gives a reply still in the socket a grace period. Before, the + * timeout was armed on the stage after the result handler, so a slow or throwing + * handler got the timeout as a second callback, and it failed a call on + * its own thread although the reply was already waiting. + */ + void settle(CompletableFuture f, java8.util.function.Consumer onResult, + java8.util.function.Function onError) { + final long due = nowMs() + this.opts.getTimeout(); + ScheduledFuture timer; + try { + timer = this.scheduler.schedule(() -> this.submitOrDrop(() -> this.expire(f, due)), + this.opts.getTimeout(), TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + timer = null; + } + final ScheduledFuture armed = timer; + f.whenComplete((result, error) -> { + if (armed != null) { + armed.cancel(false); + } + try { + if (error == null) { + onResult.accept(result); + } else { + onError.apply(error instanceof java8.util.concurrent.CompletionException && error.getCause() != null + ? error.getCause() : error); + } + } catch (Throwable t) { + // E.g. an app callback that threw: reported, never called again. + this.reportUncaught(t); + } + }); + } + + private void expire(CompletableFuture f, long due) { + if (f.isDone()) { + return; + } + if (nowMs() - due >= LATE_TIMER_MS) { + try { + this.scheduler.schedule(() -> this.submitOrDrop(() -> f.completeExceptionally(new java.util.concurrent.TimeoutException())), + LATE_TIMER_GRACE_MS, TimeUnit.MILLISECONDS); + return; + } catch (RejectedExecutionException ignored) { + // Closed: fail now. + } + } + f.completeExceptionally(new java.util.concurrent.TimeoutException()); + } + /** Submits to the executor, dropping the task once the client is closed. */ private void submitOrDrop(Runnable task) { try { @@ -841,7 +912,7 @@ private void sendSubscribeSynchronized(Subscription sub, Protocol.SubscribeReque CompletableFuture f = new CompletableFuture<>(); this.futures.put(cmd.getId(), f); - f.thenAccept(reply -> { + this.settle(f, reply -> { if (Client.this.getState() != ClientState.CONNECTED) { return; } @@ -851,7 +922,7 @@ private void sendSubscribeSynchronized(Subscription sub, Protocol.SubscribeReque this.handleDispatchError(e); } this.futures.remove(cmd.getId()); - }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { + }, e -> { this.executor.submit(() -> { if (Client.this.getState() != ClientState.CONNECTED) { return; @@ -901,7 +972,7 @@ private void sendUnsubscribeSynchronized(String channel) { final WebSocket unsubscribeWs = this.ws; CompletableFuture f = new CompletableFuture<>(); this.futures.put(cmd.getId(), f); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.futures.remove(cmd.getId()); if (reply.getError().getCode() != 0 && this.ws == unsubscribeWs && this.getState() == ClientState.CONNECTED) { // The server may still hold the subscription: its publications would @@ -909,7 +980,7 @@ private void sendUnsubscribeSynchronized(String channel) { // A new connection starts from a clean server state (as centrifuge-js). this.processDisconnect(CONNECTING_UNSUBSCRIBE_ERROR, "unsubscribe error", true); } - }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { + }, e -> { this.executor.submit(() -> { if (Client.this.getState() != ClientState.CONNECTED) { return; @@ -1304,14 +1375,14 @@ private void sendConnect() { final WebSocket connectWs = this.ws; CompletableFuture f = new CompletableFuture<>(); this.futures.put(cmd.getId(), f); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.futures.remove(cmd.getId()); try { this.handleConnectReply(reply); } catch (Throwable e) { this.handleDispatchError(e); } - }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { + }, e -> { // A timeout completes the future on the CompletableFuture delay // scheduler thread - hop to the executor like other command failures. this.executor.submit(() -> { @@ -1543,10 +1614,10 @@ private void sendSynchronized(byte[] data, CompletionCallback cb) { CompletableFuture f = new CompletableFuture<>(); this.futures.put(cmd.getId(), f); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); cb.onDone(null); - }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { + }, e -> { this.executor.submit(() -> { this.cleanCommandFuture(cmd); cb.onDone(e); @@ -1615,7 +1686,7 @@ private void rpcSynchronized(String method, byte[] data, ResultCallback f = new CompletableFuture<>(); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { cb.onDone(getReplyError(reply), null); @@ -1625,7 +1696,7 @@ private void rpcSynchronized(String method, byte[] data, ResultCallback { + }, e -> { this.executor.submit(() -> { Client.this.cleanCommandFuture(cmd); cb.onDone(e, null); @@ -1660,7 +1731,7 @@ private void publishSynchronized(String channel, byte[] data, ResultCallback f = new CompletableFuture<>(); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { cb.onDone(getReplyError(reply), null); @@ -1668,7 +1739,7 @@ private void publishSynchronized(String channel, byte[] data, ResultCallback { + }, e -> { this.executor.submit(() -> { Client.this.cleanCommandFuture(cmd); cb.onDone(e, null); @@ -1706,7 +1777,7 @@ private void historySynchronized(String channel, HistoryOptions opts, ResultCall .build(); CompletableFuture f = new CompletableFuture<>(); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { cb.onDone(getReplyError(reply), null); @@ -1728,7 +1799,7 @@ private void historySynchronized(String channel, HistoryOptions opts, ResultCall result.setEpoch(replyResult.getEpoch()); cb.onDone(null, result); } - }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { + }, e -> { this.executor.submit(() -> { Client.this.cleanCommandFuture(cmd); cb.onDone(e, null); @@ -1754,7 +1825,7 @@ private void presenceSynchronized(String channel, ResultCallback .build(); CompletableFuture f = new CompletableFuture<>(); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { cb.onDone(getReplyError(reply), null); @@ -1769,7 +1840,7 @@ private void presenceSynchronized(String channel, ResultCallback PresenceResult result = new PresenceResult(presence); cb.onDone(null, result); } - }).orTimeout(this.opts.getTimeout(), TimeUnit.MILLISECONDS).exceptionally(e -> { + }, e -> { this.executor.submit(() -> { Client.this.cleanCommandFuture(cmd); cb.onDone(e, null); @@ -1795,7 +1866,7 @@ private void presenceStatsSynchronized(String channel, ResultCallback f = new CompletableFuture<>(); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { cb.onDone(getReplyError(reply), null); @@ -1806,7 +1877,7 @@ private void presenceStatsSynchronized(String channel, ResultCallback { + }, e -> { this.executor.submit(() -> { Client.this.cleanCommandFuture(cmd); cb.onDone(e, null); @@ -1828,7 +1899,7 @@ private void refreshSynchronized(String token, ResultCallback f = new CompletableFuture<>(); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { cb.onDone(getReplyError(reply), null); @@ -1836,7 +1907,7 @@ private void refreshSynchronized(String token, ResultCallback { + }, e -> { this.executor.submit(() -> { Client.this.cleanCommandFuture(cmd); cb.onDone(e, null); @@ -1859,7 +1930,7 @@ void subRefreshSynchronized(String channel, String token, ResultCallback f = new CompletableFuture<>(); - f.thenAccept(reply -> { + this.settle(f, reply -> { this.cleanCommandFuture(cmd); if (reply.getError().getCode() != 0) { cb.onDone(getReplyError(reply), null); @@ -1867,7 +1938,7 @@ void subRefreshSynchronized(String channel, String token, ResultCallback { + }, e -> { this.executor.submit(() -> { Client.this.cleanCommandFuture(cmd); cb.onDone(e, null); diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index c293ec3..a648224 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -542,14 +542,14 @@ private void publishSynchronized(byte[] data, ResultCallback cb) CompletableFuture 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; @@ -567,14 +567,14 @@ private void historySynchronized(HistoryOptions opts, ResultCallback 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; @@ -592,14 +592,14 @@ private void presenceSynchronized(ResultCallback cb) { CompletableFuture 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; @@ -617,14 +617,14 @@ private void presenceStatsSynchronized(ResultCallback cb) { CompletableFuture 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; diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallSettleTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallSettleTest.java new file mode 100644 index 0000000..ad4fffe --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/CallSettleTest.java @@ -0,0 +1,168 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** A call settles exactly once, and a reply already received wins over its timeout. */ +public class CallSettleTest { + + private FakeCentrifugoServer server; + private Client client; + private final LinkedBlockingQueue errors = new LinkedBlockingQueue<>(); + + @Before + public void setUp() throws IOException { + server = new FakeCentrifugoServer(); + server.start(); + } + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + server.stop(); + } + + private void connect(int timeoutMs, EventListener extra) throws InterruptedException { + Options opts = new Options(); + opts.setTimeout(timeoutMs); + CountDownLatch connected = new CountDownLatch(1); + client = new Client(server.url(), opts, new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + + @Override + public void onError(Client c, ErrorEvent e) { + errors.add(e.getError().getClass().getSimpleName()); + } + + @Override + public void onMessage(Client c, MessageEvent e) { + extra.onMessage(c, e); + } + }); + client.connect(); + assertTrue("connected", connected.await(5, TimeUnit.SECONDS)); + } + + /** A result callback slower than the timeout is not followed by a timeout callback. */ + @Test + public void testSlowCallbackIsCalledOnce() throws Exception { + connect(300, new EventListener() {}); + List calls = new CopyOnWriteArrayList<>(); + client.publish("ch", "x".getBytes(StandardCharsets.UTF_8), (err, result) -> { + calls.add(err == null ? "ok" : err.getClass().getSimpleName()); + try { + Thread.sleep(600); + } catch (InterruptedException ignored) { + } + }); + Thread.sleep(1500); + assertEquals(java.util.Collections.singletonList("ok"), calls); + } + + /** A callback that throws is called once; the exception is reported through onError. */ + @Test + public void testThrowingCallbackIsCalledOnce() throws Exception { + connect(300, new EventListener() {}); + List calls = new CopyOnWriteArrayList<>(); + client.publish("ch", "x".getBytes(StandardCharsets.UTF_8), (err, result) -> { + calls.add(err == null ? "ok" : err.getClass().getSimpleName()); + throw new IllegalStateException("callback bug"); + }); + Thread.sleep(800); + assertEquals(java.util.Collections.singletonList("ok"), calls); + assertEquals("UnclassifiedError", errors.poll(1, TimeUnit.SECONDS)); + } + + /** + * A reply received while a handler holds the executor (here past the call timeout) is + * delivered: the timeout must not fail a call whose reply is already waiting. + */ + @Test + public void testReplyQueuedBehindBusyExecutorIsNotTimedOut() throws Exception { + server.onCommand = cmd -> { + if (cmd.hasPublish()) { + // A push the client's handler is slow with, then the publish reply. + server.sendPush(Protocol.Push.newBuilder() + .setMessage(Protocol.Message.newBuilder().build()).build()); + return Protocol.Reply.newBuilder().setId(cmd.getId()) + .setPublish(Protocol.PublishResult.newBuilder().build()).build(); + } + return null; + }; + connect(500, new EventListener() { + @Override + public void onMessage(Client c, MessageEvent e) { + try { + Thread.sleep(1200); + } catch (InterruptedException ignored) { + } + } + }); + LinkedBlockingQueue result = new LinkedBlockingQueue<>(); + client.publish("ch", "x".getBytes(StandardCharsets.UTF_8), + (err, r) -> result.add(err == null ? "ok" : err.getClass().getSimpleName())); + assertEquals("ok", result.poll(5, TimeUnit.SECONDS)); + assertNull("called once", result.poll(1, TimeUnit.SECONDS)); + } + + /** A call made while disconnected gets its callback when the client is closed. */ + @Test + public void testCallWaitingForConnectionFailsOnClose() throws Exception { + Options opts = new Options(); + opts.setTimeout(5000); + client = new Client(server.url(), opts, new EventListener() {}); + LinkedBlockingQueue result = new LinkedBlockingQueue<>(); + client.publish("ch", "x".getBytes(StandardCharsets.UTF_8), + (err, r) -> result.add(err == null ? "ok" : "error")); + Thread.sleep(100); + client.close(1000); + client = null; + String outcome = result.poll(2, TimeUnit.SECONDS); + assertNotNull("callback called after close()", outcome); + assertEquals("error", outcome); + } + + /** + * A subscription call that times out (here a publish waiting for a subscribe that never + * completes) gets its callback on the client's thread, like every other callback, not on + * a timer thread where it would run concurrently with event handlers. + */ + @Test + public void testSubscriptionCallTimeoutCallbackRunsOnClientThread() throws Exception { + server.deferCommand = cmd -> cmd.hasSubscribe(); + LinkedBlockingQueue handlerThread = new LinkedBlockingQueue<>(); + connect(300, new EventListener() {}); + Subscription sub = client.newSubscription("ch", new SubscriptionEventListener() { + @Override + public void onSubscribing(Subscription s, SubscribingEvent e) { + handlerThread.add(Thread.currentThread().getName()); + } + }); + sub.subscribe(); + String clientThread = handlerThread.poll(5, TimeUnit.SECONDS); + assertNotNull(clientThread); + LinkedBlockingQueue callbackThread = new LinkedBlockingQueue<>(); + sub.publish("x".getBytes(StandardCharsets.UTF_8), (err, r) -> callbackThread.add(Thread.currentThread().getName())); + assertEquals(clientThread, callbackThread.poll(5, TimeUnit.SECONDS)); + } +} From cf162c4eb27c0d530a8cdc85ad654d8385321452 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 08:58:21 +0300 Subject: [PATCH 08/11] Tie subscription token requests, retries and refreshes to the client's connection - A subscription refresh whose token request was still pending when the connection dropped was treated as current after the resubscribe (the resubscribe reused the token, so the attempt counter didn't move): it sent a refresh for the new subscribed period and started a second refresh chain . Leaving the subscribed state now ends the refresh flow. - subscribe() while the client was disconnected or connecting requested the subscription token (and state) at once, then again on connect, with two requests in flight. A subscribe attempt now waits for the connection: the connect reply resubscribes every subscribing subscription (as centrifuge-js). - A reconnect cancelled a subscription's pending resubscribe backoff and retried at once. The backoff is now kept across the reconnect (as centrifuge-js), and a new retry replaces the pending one instead of leaving it to fire as well. --- .../centrifugal/centrifuge/Subscription.java | 24 ++- .../centrifuge/SubscriptionFlowTest.java | 191 ++++++++++++++++++ 2 files changed, 214 insertions(+), 1 deletion(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/SubscriptionFlowTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index a648224..d315160 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -115,6 +115,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(); } @@ -195,7 +200,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) { @@ -399,6 +405,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 @@ -473,6 +485,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() { @@ -514,6 +531,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()), diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/SubscriptionFlowTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/SubscriptionFlowTest.java new file mode 100644 index 0000000..aa84d91 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/SubscriptionFlowTest.java @@ -0,0 +1,191 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** Token requests, retries and refreshes of a subscription across connection changes. */ +public class SubscriptionFlowTest { + + private FakeCentrifugoServer server; + private Client client; + + @Before + public void setUp() throws IOException { + server = new FakeCentrifugoServer(); + server.start(); + } + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + server.stop(); + } + + private Client newClient(CountDownLatch connected) { + Options opts = new Options(); + opts.setMinReconnectDelay(50); + opts.setMaxReconnectDelay(100); + client = new Client(server.url(), opts, new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + }); + return client; + } + + private int commands(java.util.function.Predicate p) { + int n = 0; + for (Protocol.Command cmd : server.received()) { + if (p.test(cmd)) { + n++; + } + } + return n; + } + + /** subscribe() before connect(): the token is requested once, after the client connected. */ + @Test + public void testTokenNotRequestedWhileDisconnected() throws Exception { + CountDownLatch connected = new CountDownLatch(1); + newClient(connected); + List getterCalls = new CopyOnWriteArrayList<>(); + SubscriptionOptions subOpts = new SubscriptionOptions(); + subOpts.setTokenGetter(new SubscriptionTokenGetter() { + @Override + public void getSubscriptionToken(SubscriptionTokenEvent event, TokenCallback cb) { + getterCalls.add(client.getState()); + cb.Done(null, "token"); + } + }); + LinkedBlockingQueue subscribed = new LinkedBlockingQueue<>(); + Subscription sub = client.newSubscription("ch", subOpts, new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + subscribed.add("subscribed"); + } + }); + sub.subscribe(); + Thread.sleep(200); + client.connect(); + assertNotNull(subscribed.poll(5, TimeUnit.SECONDS)); + assertEquals(java.util.Collections.singletonList(ClientState.CONNECTED), getterCalls); + } + + /** A subscribe error's retry backoff is kept across a reconnect. */ + @Test + public void testResubscribeBackoffKeptAcrossReconnect() throws Exception { + CountDownLatch connected = new CountDownLatch(1); + newClient(connected).connect(); + assertTrue(connected.await(5, TimeUnit.SECONDS)); + List calls = new CopyOnWriteArrayList<>(); + SubscriptionOptions subOpts = new SubscriptionOptions(); + subOpts.setMinResubscribeDelay(1500); + subOpts.setMaxResubscribeDelay(1500); + subOpts.setTokenGetter(new SubscriptionTokenGetter() { + @Override + public void getSubscriptionToken(SubscriptionTokenEvent event, TokenCallback cb) { + calls.add(System.nanoTime()); + if (calls.size() == 1) { + cb.Done(new Exception("token backend down"), null); + } else { + cb.Done(null, "token"); + } + } + }); + LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + Subscription sub = client.newSubscription("ch", subOpts, new SubscriptionEventListener() { + @Override + public void onError(Subscription s, SubscriptionErrorEvent e) { + events.add("error"); + } + + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + events.add("subscribed"); + } + }); + sub.subscribe(); + assertEquals("error", events.poll(5, TimeUnit.SECONDS)); + server.disconnect(3001, "reconnect"); + assertEquals("subscribed", events.poll(5, TimeUnit.SECONDS)); + long retryAfterMs = TimeUnit.NANOSECONDS.toMillis(calls.get(1) - calls.get(0)); + assertTrue("retried after its backoff (" + retryAfterMs + " ms), not at the reconnect", retryAfterMs >= 1300); + } + + /** + * A refresh whose token request is still pending when the connection drops belongs to the + * subscribed period that ended: after the resubscribe there is one refresh chain, not two. + */ + @Test + public void testRefreshInFlightAcrossReconnectDoesNotStartSecondChain() throws Exception { + server.onSubscribe = (channel, req) -> Protocol.SubscribeResult.newBuilder().setExpires(true).setTtl(1).build(); + server.onCommand = cmd -> cmd.hasSubRefresh() + ? Protocol.Reply.newBuilder().setId(cmd.getId()) + .setSubRefresh(Protocol.SubRefreshResult.newBuilder().setExpires(true).setTtl(1).build()).build() + : null; + CountDownLatch connected = new CountDownLatch(1); + newClient(connected).connect(); + assertTrue(connected.await(5, TimeUnit.SECONDS)); + AtomicInteger getterCalls = new AtomicInteger(); + CountDownLatch slowRefreshStarted = new CountDownLatch(1); + CountDownLatch resubscribed = new CountDownLatch(1); + SubscriptionOptions subOpts = new SubscriptionOptions(); + subOpts.setTokenGetter(new SubscriptionTokenGetter() { + @Override + public void getSubscriptionToken(SubscriptionTokenEvent event, TokenCallback cb) { + int n = getterCalls.incrementAndGet(); + if (n == 2) { + // The first refresh: answered right after the connection dropped and the + // subscription resubscribed, before the new period's first refresh. + slowRefreshStarted.countDown(); + new Thread(() -> { + try { + resubscribed.await(5, TimeUnit.SECONDS); + Thread.sleep(100); + } catch (InterruptedException ignored) { + } + cb.Done(null, "token-" + n); + }).start(); + return; + } + cb.Done(null, "token-" + n); + } + }); + LinkedBlockingQueue subscribed = new LinkedBlockingQueue<>(); + Subscription sub = client.newSubscription("ch", subOpts, new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + subscribed.add("subscribed"); + } + }); + sub.subscribe(); + assertNotNull(subscribed.poll(5, TimeUnit.SECONDS)); + assertTrue("refresh started", slowRefreshStarted.await(5, TimeUnit.SECONDS)); + server.disconnect(3001, "reconnect"); + assertNotNull("resubscribed", subscribed.poll(5, TimeUnit.SECONDS)); + resubscribed.countDown(); + + // ttl=1s: one chain sends about 4 refreshes in the next 4s, two chains about 8. + int before = commands(Protocol.Command::hasSubRefresh); + Thread.sleep(4000); + int refreshes = commands(Protocol.Command::hasSubRefresh) - before; + assertTrue("one refresh chain: " + refreshes + " sub_refresh commands in 4s", refreshes <= 5); + } +} From 9a18b0d469dcddbce8865d083014ed729e96b1a5 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 09:01:29 +0300 Subject: [PATCH 09/11] Take the epoch from publications; report an invalid endpoint - A subscribe reply without an epoch (a channel with no stream yet) left the epoch empty: the server sends it with the channel's first publication, but the client ignored it and recovered with an empty epoch, which skips the server's epoch check. The epoch now comes with the publication's offset while none is known, and a reply without an epoch no longer erases a known one; for server-side subscriptions too (as centrifuge-js). - connect() with an endpoint OkHttp can't open left the client connecting with nothing scheduled. It now reports a ConfigurationError and stays disconnected. - setTagsFilter() writes a field the client thread reads: now volatile. --- .../github/centrifugal/centrifuge/Client.java | 14 ++ .../centrifugal/centrifuge/Subscription.java | 15 +- .../centrifuge/EpochAndEndpointTest.java | 133 ++++++++++++++++++ 3 files changed, 160 insertions(+), 2 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/EpochAndEndpointTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index 93dc885..7f7c0c6 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -269,6 +269,15 @@ public void connect() { if (Client.this.getState() == ClientState.CONNECTED || Client.this.getState() == ClientState.CONNECTING) { return; } + try { + new Request.Builder().url(Client.this.endpoint); + } catch (IllegalArgumentException e) { + // No retry can fix an endpoint OkHttp can't open: report it and stay + // disconnected. Before, the client stayed connecting with nothing + // scheduled. + Client.this.listener.onError(Client.this, new ErrorEvent(new ConfigurationError(e))); + return; + } Client.this.reconnectAttempts = 0; Client.this.setState(ClientState.CONNECTING); ConnectingEvent event = new ConnectingEvent(CONNECTING_CONNECT_CALLED, "connect called"); @@ -1449,6 +1458,11 @@ void handlePub(String channel, Protocol.Publication pub, long id) throws Excepti event.setTags(pub.getTagsMap()); if (pub.getOffset() > 0) { serverSub.setLastOffset(pub.getOffset()); + // As for client-side subscriptions. + String knownEpoch = serverSub.getEpoch(); + if ((knownEpoch == null || knownEpoch.isEmpty()) && !pub.getEpoch().isEmpty()) { + serverSub.setLastEpoch(pub.getEpoch()); + } } this.listener.onPublication(this, event); } diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index d315160..a361932 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -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 @@ -238,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); } @@ -250,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 diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/EpochAndEndpointTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/EpochAndEndpointTest.java new file mode 100644 index 0000000..5c11644 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/EpochAndEndpointTest.java @@ -0,0 +1,133 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class EpochAndEndpointTest { + + private FakeCentrifugoServer server; + private Client client; + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + if (server != null) { + server.stop(); + } + } + + private Subscription recoverableSub(LinkedBlockingQueue events) throws Exception { + CountDownLatch connected = new CountDownLatch(1); + Options opts = new Options(); + opts.setMinReconnectDelay(50); + opts.setMaxReconnectDelay(100); + client = new Client(server.url(), opts, new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + }); + client.connect(); + assertTrue(connected.await(5, TimeUnit.SECONDS)); + Subscription sub = client.newSubscription("ch", new SubscriptionEventListener() { + @Override + public void onSubscribed(Subscription s, SubscribedEvent e) { + events.add("subscribed"); + } + + @Override + public void onPublication(Subscription s, PublicationEvent e) { + events.add("publication:" + e.getOffset()); + } + }); + sub.subscribe(); + assertEquals("subscribed", events.poll(5, TimeUnit.SECONDS)); + return sub; + } + + private Protocol.SubscribeRequest subscribeRequest(int index) { + int n = 0; + for (Protocol.Command cmd : server.received()) { + if (cmd.hasSubscribe() && n++ == index) { + return cmd.getSubscribe(); + } + } + return null; + } + + /** + * A subscribe reply without an epoch (no stream yet): the epoch comes with the first + * publication, and the next recovery sends it. An empty epoch would skip the server's + * epoch check. + */ + @Test + public void testEpochTakenFromFirstPublication() throws Exception { + server = new FakeCentrifugoServer(); + server.onSubscribe = (channel, req) -> Protocol.SubscribeResult.newBuilder().setRecoverable(true).build(); + server.start(); + LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + recoverableSub(events); + server.sendPush(Protocol.Push.newBuilder().setChannel("ch") + .setPub(Protocol.Publication.newBuilder().setOffset(1).setEpoch("E1").build()).build()); + assertEquals("publication:1", events.poll(5, TimeUnit.SECONDS)); + server.disconnect(3001, "reconnect"); + assertEquals("subscribed", events.poll(5, TimeUnit.SECONDS)); + Protocol.SubscribeRequest resubscribe = subscribeRequest(1); + assertNotNull(resubscribe); + assertTrue(resubscribe.getRecover()); + assertEquals(1, resubscribe.getOffset()); + assertEquals("E1", resubscribe.getEpoch()); + } + + /** A subscribe reply without an epoch doesn't drop the epoch already known. */ + @Test + public void testReplyWithoutEpochKeepsKnownEpoch() throws Exception { + server = new FakeCentrifugoServer(); + AtomicInteger replies = new AtomicInteger(); + server.onSubscribe = (channel, req) -> replies.incrementAndGet() == 1 + ? Protocol.SubscribeResult.newBuilder().setRecoverable(true).setEpoch("E1").build() + : Protocol.SubscribeResult.newBuilder().setRecoverable(true).setRecovered(true).setWasRecovering(true).build(); + server.start(); + LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + recoverableSub(events); + server.disconnect(3001, "reconnect"); + assertEquals("subscribed", events.poll(5, TimeUnit.SECONDS)); + server.disconnect(3001, "reconnect"); + assertEquals("subscribed", events.poll(5, TimeUnit.SECONDS)); + assertEquals("E1", subscribeRequest(2).getEpoch()); + } + + /** An endpoint OkHttp can't open: a configuration error, and the client stays disconnected. */ + @Test + public void testInvalidEndpointReportsConfigurationError() throws Exception { + List errors = new CopyOnWriteArrayList<>(); + CountDownLatch errored = new CountDownLatch(1); + client = new Client("localhost:8000/connection/websocket", new Options(), new EventListener() { + @Override + public void onError(Client c, ErrorEvent e) { + errors.add(e.getError().getClass().getSimpleName()); + errored.countDown(); + } + }); + client.connect(); + assertTrue(errored.await(5, TimeUnit.SECONDS)); + Thread.sleep(200); + assertEquals(java.util.Collections.singletonList("ConfigurationError"), errors); + assertEquals(ClientState.DISCONNECTED, client.getState()); + } +} From a47122de6f86dad30c750ef0ecaf1fbb9fb02304 Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 09:01:54 +0300 Subject: [PATCH 10/11] Document the client thread, blocking in listeners and listener exceptions --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index e53f19a..c4a4f7e 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,27 @@ To use with Android don't forget to set INTERNET permission to `AndroidManifest. ``` +## 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. From 2904f38781890196d52e73dbd1f47add2853b48c Mon Sep 17 00:00:00 2001 From: FZambia Date: Mon, 12 Oct 2026 09:28:47 +0300 Subject: [PATCH 11/11] Drop the rest of a frame after a teardown; fix retry, GC and socket follow-ups Follow-ups to the commits above, each pinned by a test that fails without it: - A teardown in the middle of a frame (a disconnect push, a reconnect on an error reply) was followed by the rest of the frame: a server ping in it was answered on the closed transport (NullPointerException, then a terminal "bad protocol" stop), or with pong off re-armed a no-ping timer that later tore down the next connection. The rest of a frame is now dropped once its transport is gone, and the connect reply cancels any no-ping timer still armed (as centrifuge-js). - A resubscribe retry timer that fired just before the app's unsubscribe() ran subscribed again afterwards: a server subscription the client doesn't track. The retry now acts only while the subscription is subscribing. - A client that was disconnected but never closed was no longer collected: the executor reporting step exceptions captured the client and its worker thread is a GC root. The reporting is now a wrapper around the standard single-thread executor, which shuts down once the client is unreachable. Cancelled timers are also removed from the scheduler at once: kept until their delay passed (e.g. a no-ping timer, ping interval + max delay), they held a disconnected client too. - After the teardown of a dead or half-open link, the old socket stayed open for up to 60s next to the new connection, waiting for the peer's close frame. It is now cancelled after a 1s grace period. The test fake server now answers the client's close frame, as a real server does (answerClose = false keeps the half-open behaviour), counts open sockets, and can send several replies in one frame. --- .../github/centrifugal/centrifuge/Client.java | 110 +++++++-- .../centrifugal/centrifuge/Subscription.java | 9 +- .../centrifuge/FakeCentrifugoServer.java | 51 +++++ .../centrifuge/FrameAndLifecycleTest.java | 216 ++++++++++++++++++ .../centrifuge/TransportTeardownTest.java | 140 ++++++++++++ 5 files changed, 504 insertions(+), 22 deletions(-) create mode 100644 centrifuge/src/test/java/io/github/centrifugal/centrifuge/FrameAndLifecycleTest.java diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java index 7f7c0c6..cab4de4 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Client.java @@ -66,30 +66,76 @@ public class Client { // Runs every step of the client. An exception escaping a step (e.g. thrown by an app // event handler) is reported through onError instead of vanishing in the task's - // Future, which left the rest of the step silently undone. - private final ExecutorService executor = new java.util.concurrent.ThreadPoolExecutor( - 1, 1, 0L, TimeUnit.MILLISECONDS, new java.util.concurrent.LinkedBlockingQueue()) { + // Future, which left the rest of the step silently undone. The worker + // thread references only the inner executor, which shuts itself down once the client + // is unreachable: a client that is disconnected but never closed is still collected. + private final ExecutorService executor = new ReportingExecutor(Executors.newSingleThreadExecutor()); + + /** Wraps every task so an exception it throws is reported, then delegates. */ + private final class ReportingExecutor extends java.util.concurrent.AbstractExecutorService { + private final ExecutorService delegate; + + ReportingExecutor(ExecutorService delegate) { + this.delegate = delegate; + } + @Override - protected void afterExecute(Runnable r, Throwable t) { - super.afterExecute(r, t); - if (t == null && r instanceof java.util.concurrent.Future) { - java.util.concurrent.Future future = (java.util.concurrent.Future) r; - if (future.isDone() && !future.isCancelled()) { - try { - future.get(); - } catch (java.util.concurrent.ExecutionException e) { - t = e.getCause(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } + public void execute(Runnable task) { + this.delegate.execute(() -> { + try { + task.run(); + } catch (Throwable t) { + Client.this.reportUncaught(t); } - } - if (t != null) { - Client.this.reportUncaught(t); - } + }); + } + + @Override + protected java.util.concurrent.RunnableFuture newTaskFor(Runnable task, T value) { + // submit(): report from inside the task, before FutureTask stores the exception. + return super.newTaskFor(() -> { + try { + task.run(); + } catch (Throwable t) { + Client.this.reportUncaught(t); + } + }, value); + } + + @Override + public void shutdown() { + this.delegate.shutdown(); + } + + @Override + public List shutdownNow() { + return this.delegate.shutdownNow(); + } + + @Override + public boolean isShutdown() { + return this.delegate.isShutdown(); } - }; - private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); + + @Override + public boolean isTerminated() { + return this.delegate.isTerminated(); + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + return this.delegate.awaitTermination(timeout, unit); + } + } + // Timers. A cancelled timer is removed from the queue at once: kept until its delay + // passed (e.g. the no-ping timer, ping interval + max delay), it held the client. + private final ScheduledExecutorService scheduler = newScheduler(); + + private static ScheduledExecutorService newScheduler() { + java.util.concurrent.ScheduledThreadPoolExecutor scheduler = new java.util.concurrent.ScheduledThreadPoolExecutor(1); + scheduler.setRemoveOnCancelPolicy(true); + return scheduler; + } private int pingInterval; private boolean sendPong; private ScheduledFuture pingTask; @@ -116,6 +162,8 @@ ScheduledExecutorService getScheduler() { // handled first, as centrifuge-js lateCallTimer / lateCallGrace. static final long LATE_TIMER_MS = 1000; static final long LATE_TIMER_GRACE_MS = 1000; + // How long a closed socket may wait for the peer's close frame before it's cancelled. + static final long CLOSE_GRACE_MS = 1000; private static final int MESSAGE_SIZE_LIMIT_EXCEEDED_STATUS = 1009; static final int DISCONNECTED_DISCONNECT_CALLED = 0; @@ -520,6 +568,14 @@ private void closeTransport() { } if (open) { transport.close(NORMAL_CLOSURE_STATUS, null); + // A peer on a dead or half-open link never answers the close frame: OkHttp would + // keep the socket for 60s next to the next connection. A healthy peer answers + // within the grace period, and cancel() of a closed socket does nothing. + try { + this.scheduler.schedule(transport::cancel, CLOSE_GRACE_MS, TimeUnit.MILLISECONDS); + } catch (RejectedExecutionException e) { + transport.cancel(); + } } else { transport.cancel(); } @@ -681,6 +737,14 @@ public void onMessage(WebSocket webSocket, ByteString bytes) { Client.this.processDisconnect(DISCONNECTED_BAD_PROTOCOL, "bad protocol (message)", false); break; } + if (Client.this.ws != webSocket) { + // A message of this frame tore the transport down (e.g. a + // disconnect push, a reconnect on an error reply): the rest + // of the frame belongs to the connection that ended, e.g. a + // ping that must not be answered or re-arm the ping timer on + // the next one (as centrifuge-js). + break; + } } }); } catch (RejectedExecutionException ignored) { @@ -1276,6 +1340,10 @@ private void handleConnectReply(Protocol.Reply reply) { } this.connectAsyncCommands.clear(); + if (this.pingTask != null) { + // One no-ping timer per connection: never leave an earlier one armed. + this.pingTask.cancel(true); + } this.pingTask = this.scheduler.schedule(Client.this::waitServerPing, this.pingInterval + this.opts.getMaxServerPingDelay(), TimeUnit.MILLISECONDS); if (result.getExpires()) { diff --git a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java index a361932..f024b14 100644 --- a/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java +++ b/centrifuge/src/main/java/io/github/centrifugal/centrifuge/Subscription.java @@ -556,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() { diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/FakeCentrifugoServer.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/FakeCentrifugoServer.java index 96103a5..05c178d 100644 --- a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/FakeCentrifugoServer.java +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/FakeCentrifugoServer.java @@ -161,12 +161,43 @@ public void disconnect(int code, String reason) { } } + /** + * Answer the client's close frame, as a real server does. Set to false to simulate a dead + * or half-open link whose peer never answers. + */ + public volatile boolean answerClose = true; + + private final java.util.concurrent.atomic.AtomicInteger openSockets = new java.util.concurrent.atomic.AtomicInteger(); + + /** WebSocket connections currently open on the server side. */ + public int openSockets() { + return openSockets.get(); + } + private final class ServerListener extends WebSocketListener { @Override public void onOpen(WebSocket webSocket, Response response) { + openSockets.incrementAndGet(); currentSocket.set(webSocket); } + @Override + public void onClosed(WebSocket webSocket, int code, String reason) { + openSockets.decrementAndGet(); + } + + @Override + public void onFailure(WebSocket webSocket, Throwable t, Response response) { + openSockets.decrementAndGet(); + } + + @Override + public void onClosing(WebSocket webSocket, int code, String reason) { + if (answerClose) { + webSocket.close(1000, null); + } + } + @Override public void onMessage(WebSocket webSocket, ByteString bytes) { InputStream stream = new ByteArrayInputStream(bytes.toByteArray()); @@ -256,6 +287,26 @@ public void sendReply(Protocol.Reply reply) { } /** Send a raw push (wrapped in a reply) to the active connection. */ + /** + * Send several replies (or pushes, wrapped in replies) in one WebSocket frame, as the + * server does when it batches queued messages. + */ + public void sendFrame(Protocol.Reply... replies) { + WebSocket s = currentSocket.get(); + if (s == null) { + return; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + for (Protocol.Reply reply : replies) { + reply.writeDelimitedTo(out); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + s.send(ByteString.of(out.toByteArray())); + } + public void sendPush(Protocol.Push push) { sendReply(Protocol.Reply.newBuilder().setPush(push).build()); } diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/FrameAndLifecycleTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/FrameAndLifecycleTest.java new file mode 100644 index 0000000..6317285 --- /dev/null +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/FrameAndLifecycleTest.java @@ -0,0 +1,216 @@ +package io.github.centrifugal.centrifuge; + +import java.io.IOException; +import java.lang.ref.WeakReference; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import io.github.centrifugal.centrifuge.internal.protocol.Protocol; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * The rest of a frame after a teardown, retry timers that fire around unsubscribe(), and the + * lifetime of a client that is disconnected but never closed. + */ +public class FrameAndLifecycleTest { + + private FakeCentrifugoServer server; + private Client client; + private final List events = new CopyOnWriteArrayList<>(); + + @Before + public void setUp() throws IOException { + server = new FakeCentrifugoServer(); + server.start(); + } + + @After + public void tearDown() throws InterruptedException { + if (client != null) { + client.close(1000); + } + server.stop(); + } + + private static Protocol.Reply disconnectPush(int code) { + return Protocol.Reply.newBuilder().setPush(Protocol.Push.newBuilder() + .setDisconnect(Protocol.Disconnect.newBuilder().setCode(code).setReason("reconnect").build()).build()).build(); + } + + private static final Protocol.Reply PING = Protocol.Reply.newBuilder().build(); + + private Client connect(Options opts, CountDownLatch connectedTwice) throws InterruptedException { + CountDownLatch connected = new CountDownLatch(1); + client = new Client(server.url(), opts, new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + events.add("connected"); + connected.countDown(); + connectedTwice.countDown(); + } + + @Override + public void onConnecting(Client c, ConnectingEvent e) { + events.add("connecting:" + e.getCode()); + } + + @Override + public void onDisconnected(Client c, DisconnectedEvent e) { + events.add("disconnected:" + e.getCode()); + } + + @Override + public void onError(Client c, ErrorEvent e) { + events.add("error:" + e.getError().getClass().getSimpleName()); + } + }); + client.connect(); + assertTrue("connected", connected.await(5, TimeUnit.SECONDS)); + return client; + } + + /** + * A server ping after a disconnect push in the same frame belongs to the connection that + * ended: it must not be answered (the transport is gone), and the client reconnects. + */ + @Test + public void testPingAfterDisconnectPushInSameFrameIsIgnored() throws Exception { + server.connectResult = Protocol.ConnectResult.newBuilder() + .setClient("fake-client").setVersion("0.0.0").setPing(25).setPong(true).build(); + Options opts = new Options(); + opts.setMinReconnectDelay(50); + opts.setMaxReconnectDelay(100); + CountDownLatch connectedTwice = new CountDownLatch(2); + connect(opts, connectedTwice); + server.sendFrame(disconnectPush(3001), PING); + assertTrue("reconnected: " + events, connectedTwice.await(5, TimeUnit.SECONDS)); + Thread.sleep(200); + assertEquals(java.util.Arrays.asList("connecting:0", "connected", "connecting:3001", "connected"), events); + assertEquals(ClientState.CONNECTED, client.getState()); + } + + /** + * Same frame shape with pong off: the old connection's ping must not re-arm a no-ping timer + * that later tears down the next, healthy connection. + */ + @Test + public void testPingAfterDisconnectPushInSameFrameLeavesNoStalePingTimer() throws Exception { + server.connectResult = Protocol.ConnectResult.newBuilder() + .setClient("fake-client").setVersion("0.0.0").setPing(1).build(); + Options opts = new Options(); + opts.setMinReconnectDelay(300); + opts.setMaxReconnectDelay(400); + opts.setMaxServerPingDelay(300); + CountDownLatch connectedTwice = new CountDownLatch(2); + connect(opts, connectedTwice); + // The next connection pings rarely: only a stale timer could fire in the next seconds. + server.connectResult = Protocol.ConnectResult.newBuilder() + .setClient("fake-client").setVersion("0.0.0").setPing(25).build(); + server.sendFrame(disconnectPush(3001), PING); + assertTrue("reconnected: " + events, connectedTwice.await(5, TimeUnit.SECONDS)); + Thread.sleep(2500); + assertEquals(java.util.Arrays.asList("connecting:0", "connected", "connecting:3001", "connected"), events); + } + + /** + * A resubscribe retry timer that fires while the client thread is busy, after the app + * called unsubscribe(): the retry belongs to an attempt that ended and must not subscribe. + */ + @Test + public void testRetryTimerAfterUnsubscribeDoesNotSubscribe() throws Exception { + AtomicInteger subscribes = new AtomicInteger(); + server.onCommand = cmd -> cmd.hasSubscribe() && subscribes.incrementAndGet() == 1 + ? Protocol.Reply.newBuilder().setId(cmd.getId()) + .setError(Protocol.Error.newBuilder().setCode(100).setMessage("internal").setTemporary(true).build()).build() + : null; + CountDownLatch handlerRunning = new CountDownLatch(1); + CountDownLatch connected = new CountDownLatch(1); + client = new Client(server.url(), new Options(), new EventListener() { + @Override + public void onConnected(Client c, ConnectedEvent e) { + connected.countDown(); + } + + @Override + public void onMessage(Client c, MessageEvent e) { + handlerRunning.countDown(); + try { + Thread.sleep(700); + } catch (InterruptedException ignored) { + } + } + }); + client.connect(); + assertTrue(connected.await(5, TimeUnit.SECONDS)); + LinkedBlockingQueue subEvents = new LinkedBlockingQueue<>(); + SubscriptionOptions subOpts = new SubscriptionOptions(); + subOpts.setMinResubscribeDelay(300); + subOpts.setMaxResubscribeDelay(300); + Subscription sub = client.newSubscription("ch", subOpts, new SubscriptionEventListener() { + @Override + public void onError(Subscription s, SubscriptionErrorEvent e) { + subEvents.add("error"); + } + }); + sub.subscribe(); + assertEquals("error", subEvents.poll(5, TimeUnit.SECONDS)); + // Hold the client thread: unsubscribe() is queued first, the retry timer fires behind it. + server.sendPush(Protocol.Push.newBuilder().setMessage(Protocol.Message.newBuilder().build()).build()); + assertTrue(handlerRunning.await(5, TimeUnit.SECONDS)); + sub.unsubscribe(); + Thread.sleep(1500); + List wire = new java.util.ArrayList<>(); + for (Protocol.Command cmd : server.received()) { + if (cmd.hasSubscribe()) { + wire.add("subscribe"); + } else if (cmd.hasUnsubscribe()) { + wire.add("unsubscribe"); + } + } + assertEquals("no subscribe after the app's unsubscribe", "unsubscribe", wire.get(wire.size() - 1)); + assertEquals(SubscriptionState.UNSUBSCRIBED, sub.getState()); + } + + /** A client that was connected, then disconnected but never closed, is garbage-collected. */ + @Test + public void testDisconnectedClientIsCollected() throws Exception { + WeakReference ref = connectAndDisconnect(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (ref.get() != null && System.nanoTime() < deadline) { + System.gc(); + Thread.sleep(100); + } + assertTrue("collected", ref.get() == null); + } + + private WeakReference connectAndDisconnect() throws InterruptedException { + CountDownLatch connected = new CountDownLatch(1); + CountDownLatch disconnected = new CountDownLatch(1); + Client c = new Client(server.url(), new Options(), new EventListener() { + @Override + public void onConnected(Client cl, ConnectedEvent e) { + connected.countDown(); + } + + @Override + public void onDisconnected(Client cl, DisconnectedEvent e) { + disconnected.countDown(); + } + }); + c.connect(); + assertTrue(connected.await(5, TimeUnit.SECONDS)); + c.disconnect(); + assertTrue(disconnected.await(5, TimeUnit.SECONDS)); + return new WeakReference<>(c); + } +} diff --git a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java index d4093c2..43c0547 100644 --- a/centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java +++ b/centrifuge/src/test/java/io/github/centrifugal/centrifuge/TransportTeardownTest.java @@ -66,6 +66,8 @@ public void testReconnectAfterNoPingDoesNotWaitForPeerClose() throws Exception { server = new FakeCentrifugoServer(); server.connectResult = Protocol.ConnectResult.newBuilder() .setClient("fake-client").setVersion("0.0.0").setPing(1).build(); + // A dead link: the peer never answers the client's close frame. + server.answerClose = false; server.start(); Options opts = new Options(); opts.setMaxServerPingDelay(300); @@ -89,6 +91,144 @@ public void onConnecting(Client c, ConnectingEvent e) { assertTrue("reconnected within 5s of no ping, connect commands: " + connectCommands(), connectCommands() >= 2); } + /** + * After "no ping" on a link that went dead (nothing gets through any more, so the close + * frame never reaches the peer), the client doesn't keep the dead connection's socket open + * next to the new one: OkHttp would keep it for up to 60s waiting for the peer's close frame. + */ + @Test + public void testDeadConnectionSocketIsReleased() throws Exception { + server = new FakeCentrifugoServer(); + server.connectResult = Protocol.ConnectResult.newBuilder() + .setClient("fake-client").setVersion("0.0.0").setPing(1).build(); + server.start(); + java.net.URI upstream = java.net.URI.create(server.url()); + CountingRelay relay = new CountingRelay(upstream.getHost(), upstream.getPort()); + try { + Options opts = new Options(); + opts.setMaxServerPingDelay(300); + opts.setMinReconnectDelay(100); + opts.setMaxReconnectDelay(200); + LinkedBlockingQueue connecting = new LinkedBlockingQueue<>(); + CountDownLatch firstConnected = new CountDownLatch(1); + CountDownLatch secondConnected = new CountDownLatch(2); + client = new Client("ws://127.0.0.1:" + relay.port() + "/connection/websocket", opts, new EventListener() { + @Override + public void onConnecting(Client c, ConnectingEvent e) { + connecting.add(e.getCode()); + } + + @Override + public void onConnected(Client c, ConnectedEvent e) { + firstConnected.countDown(); + secondConnected.countDown(); + // From the second connection on, the server pings rarely: one no-ping only. + server.connectResult = Protocol.ConnectResult.newBuilder() + .setClient("fake-client").setVersion("0.0.0").setPing(25).build(); + } + }); + client.connect(); + assertTrue("connected", firstConnected.await(5, TimeUnit.SECONDS)); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + // The link of the first connection goes dead. + relay.blackholeExisting(); + Integer code; + do { + code = connecting.poll(100, TimeUnit.MILLISECONDS); + } while ((code == null || code != Client.CONNECTING_NO_PING) && System.nanoTime() < deadline); + assertEquals("no ping", Integer.valueOf(Client.CONNECTING_NO_PING), code); + assertTrue("reconnected", secondConnected.await(5, TimeUnit.SECONDS)); + deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(3); + while (relay.open() != 1 && System.nanoTime() < deadline) { + Thread.sleep(20); + } + assertEquals("only the new connection's socket is open", 1, relay.open()); + } finally { + relay.close(); + } + } + + /** A TCP relay that counts the client connections it currently relays. */ + private static final class CountingRelay { + private final ServerSocket listener = new ServerSocket(0); + private final java.util.concurrent.atomic.AtomicInteger open = new java.util.concurrent.atomic.AtomicInteger(); + private final List holes = new java.util.concurrent.CopyOnWriteArrayList<>(); + + /** Existing connections drop everything from now on; new connections work. */ + void blackholeExisting() { + for (java.util.concurrent.atomic.AtomicBoolean hole : holes) { + hole.set(true); + } + } + + CountingRelay(String host, int port) throws IOException { + Thread acceptor = new Thread(() -> { + try { + while (true) { + Socket client = listener.accept(); + Socket upstream = new Socket(host, port); + open.incrementAndGet(); + java.util.concurrent.atomic.AtomicBoolean closed = new java.util.concurrent.atomic.AtomicBoolean(); + Runnable done = () -> { + if (closed.compareAndSet(false, true)) { + open.decrementAndGet(); + try { + client.close(); + } catch (IOException ignored) { + } + try { + upstream.close(); + } catch (IOException ignored) { + } + } + }; + java.util.concurrent.atomic.AtomicBoolean hole = new java.util.concurrent.atomic.AtomicBoolean(); + holes.add(hole); + pump(client, upstream, done, hole); + pump(upstream, client, done, hole); + } + } catch (IOException ignored) { + } + }); + acceptor.setDaemon(true); + acceptor.start(); + } + + private static void pump(Socket from, Socket to, Runnable done, java.util.concurrent.atomic.AtomicBoolean hole) { + Thread t = new Thread(() -> { + byte[] buf = new byte[8192]; + try { + InputStream in = from.getInputStream(); + java.io.OutputStream out = to.getOutputStream(); + int n; + while ((n = in.read(buf)) >= 0) { + // Blackholed: keep reading (to see the client close), forward nothing. + if (!hole.get()) { + out.write(buf, 0, n); + out.flush(); + } + } + } catch (IOException ignored) { + } + done.run(); + }); + t.setDaemon(true); + t.start(); + } + + int port() { + return listener.getLocalPort(); + } + + int open() { + return open.get(); + } + + void close() throws IOException { + listener.close(); + } + } + private int startSilentServer() throws IOException { silent = new ServerSocket(0); Thread acceptor = new Thread(() -> {