Skip to content

Fix connection, subscription, token and call issues - #105

Merged
FZambia merged 11 commits into
masterfrom
validation-fixes
Oct 13, 2026
Merged

FZambia merged 11 commits into
masterfrom
validation-fixes

Conversation

@FZambia

@FZambia FZambia commented Oct 12, 2026

Copy link
Copy Markdown
Member

In short

What is better now

  • unsubscribe() followed by subscribe() works. The subscribe command could reach the server before the unsubscribe: the server answered "already subscribed" (105) and the subscription ended unsubscribed, or it looked subscribed while the server had no subscription. The same happened when removing a subscription and creating a new one for the channel. Commands now go out in the order of the calls, and a subscribe reply is applied only to the subscribe attempt that sent it.
  • Fast recovery from a dead connection. After "no ping" or a timeout on a dead or half-open link, the client waited about 60 seconds for OkHttp to give up on the old socket before reconnecting, and the recovery that followed often failed, so messages were lost. The client now closes the transport itself and reconnects within its backoff.
  • No publications after unsubscribing. Publications already on their way were delivered after onUnsubscribed and moved the stored position, so a later subscribe could skip or repeat messages. Pushes are now applied only to a subscription in the state they are for.
  • Static tokens keep working. A "state invalidated" disconnect (3014) stopped clients with a static token or none, and setToken() couldn't recover a client after a token expired error without a token getter.
  • Exceptions in app code don't break the client. A token getter or an event listener that threw could leave the client stuck connecting, a subscription stuck subscribing, or the client connected without its subscriptions. A throwing getter is now treated as a token error and retried; listener exceptions are reported through onError.
  • Calls finish exactly once, on the client thread, and a reply that already arrived wins over the timeout (for example after the device slept).

What to check when upgrading

  1. The WebSocket handshake is now limited by Options.setTimeout (5 s by default); before, only OkHttp's own limits applied (10 s by default). Set a larger timeout if the server or a proxy answers the upgrade slowly.
  2. A listener that throws while a server reply is handled (onConnected, onSubscribed) now stops the client visibly: onError, then onDisconnected with code 2 ("bad protocol"); connect() starts again. Other listener and callback exceptions are reported through onError and the client continues.
  3. subscribe() on a subscription removed with removeSubscription() throws IllegalStateException.
  4. Call callbacks receive the error itself (e.g. IOException when the connection was lost), not a CompletionException wrapping it.
  5. Call close() when a client is no longer needed. The new README section "Threads and event listeners" describes the client thread, asynchronous methods, and why not to block in listeners.

Changes

One commit per cause, each with tests that fail without it:

Commit Fixes Tests
Write the unsubscribe command before the unsubscribed event and drop replies of ended subscribe attempts unsubscribe()+subscribe() and remove+new ending unsubscribed (105); "ghost" subscriptions after a fast toggle UnsubscribeOrderTest
Tear the transport down in the teardown and bound the handshake by the client timeout ~60 s extra outage on a dead link; handshake not limited by the client timeout; disconnect() leaving the handshake socket open TransportTeardownTest
Apply pushes only to a subscription in the state they are for publications, join and leave after unsubscribing; an unsubscribe push bringing back an unsubscribed subscription; server-side subscription publications taken by an unsubscribed client-side subscription of the same channel; unsubscribe error reply ignored PushStateTest
Keep tokens that no token getter can replace 3014 stopping clients with a static token or none; static subscription tokens dropped; setToken() not recovering after 109 without a getter; subscription 109 without a getter resubscribing without a token StaticTokenTest, StateInvalidationTest
Never leave a step half-done when app code throws throwing token/state getters and listeners leaving the client stuck or stopped; exceptions lost in the executor AppExceptionTest
Remove only the subscription passed, and refuse to subscribe a removed one removeSubscription(old) removing the newer subscription of the channel; a removed subscription subscribing on the server RemoveSubscriptionTest
Settle every call exactly once, on the client thread, after replies already received callbacks called twice; timeouts for replies already received; subscription call callbacks on a timer thread; no callback for a call waiting for a connection when close() is called CallSettleTest
Tie subscription token requests, retries and refreshes to the client's connection a second refresh chain after a reconnect; tokens requested while disconnected; the resubscribe backoff dropped by a reconnect SubscriptionFlowTest
Take the epoch from publications; report an invalid endpoint empty epoch sent on recovery when the subscribe reply had none; an endpoint without a scheme leaving the client connecting forever EpochAndEndpointTest
Document the client thread, blocking in listeners and listener exceptions README —
Drop the rest of a frame after a teardown; fix retry, GC and socket follow-ups follow-ups to the commits above: a server ping after a disconnect push in the same frame, a retry timer firing around unsubscribe(), a disconnected client not being garbage-collected (cancelled timers no longer hold it), a dead socket kept open after a reconnect FrameAndLifecycleTest, TransportTeardownTest

The behaviour follows centrifuge-js and the TLA+ specification of the client SDK.

Verification

  • 99 unit tests (36 new) and 33 integration tests against Centrifugo (docker-compose.yml) pass; the API compatibility check (metalava) passes — no public API changes.
  • The new tests fail on master, each on the bug it covers.
  • The client was also exercised with an SDK validation harness, on 0.7.0, master and this branch: seeded chaos against an in-process fake server, a real Centrifugo behind fault-injecting proxies (connection kills, stalls, dead links, hung handshakes, process freezes) with delivery and recovery checks, token expiry scenarios on a server requiring tokens, and deterministic probes. The issues above were found there; on this branch the runs deliver every message without duplicates and recover after every fault.
  • Known limitations, unchanged: a "no ping" reconnect can happen while pings wait behind a slow listener; a slow token request of an abandoned connection attempt still completes once (its result is ignored).

…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.
…e 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.
- 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.
- 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.
- 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.
…d 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.
…lready 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.
…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.
- 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.
…ollow-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.
@FZambia
FZambia merged commit b49b754 into master Oct 13, 2026
12 checks passed
@FZambia
FZambia deleted the validation-fixes branch October 13, 2026 17:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant