@@ -676,6 +676,8 @@ private GbCacheManager createCacheManager() {
676676 private final AtomicBoolean sseReconnectScheduled = new AtomicBoolean (false );
677677 private final AtomicBoolean sseConnected = new AtomicBoolean (false );
678678 private final AtomicInteger sseRetryAttempts = new AtomicInteger (0 );
679+ /** Attempt number whose delay applies when reconnecting after an opened stream ends. */
680+ private static final int FIRST_RETRY_ATTEMPT = 2 ;
679681 private final AtomicBoolean shuttingDown = new AtomicBoolean (false );
680682 private final Object initLock = new Object ();
681683
@@ -800,14 +802,15 @@ private void createEventSourceListenerAndStartListening(Boolean retryOnFailure)
800802 .addHeader (HttpHeaders .ACCEPT .getHeader (), HttpHeaders .SSE_HEADER .getHeader ())
801803 .build ();
802804
805+ AtomicBoolean streamOpened = new AtomicBoolean (false );
803806 GBEventSourceListener gbEventSourceListener =
804807 new GBEventSourceListener (
805808 new GBEventSourceHandler () {
806809 @ Override
807810 public void onClose (EventSource eventSource ) {
808811 sseConnected .set (false );
809812 eventSource .cancel ();
810- scheduleSseReconnect (retryOnFailure );
813+ onSseStreamClosed (retryOnFailure , streamOpened . get () );
811814 }
812815
813816 @ Override
@@ -828,12 +831,13 @@ public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @
828831 super .onFailure (eventSource , t , response );
829832 sseConnected .set (false );
830833 eventSource .cancel ();
831- scheduleSseReconnect (retryOnFailure );
834+ onSseStreamFailed (retryOnFailure , streamOpened . get (), t , response );
832835 }
833836
834837 @ Override
835838 public void onOpen (@ NotNull EventSource eventSource , @ NotNull Response response ) {
836839 super .onOpen (eventSource , response );
840+ streamOpened .set (true );
837841 sseConnected .set (true );
838842 sseRetryAttempts .set (0 );
839843 sseReconnectScheduled .set (false );
@@ -845,10 +849,71 @@ public void onOpen(@NotNull EventSource eventSource, @NotNull Response response)
845849 .newEventSource (sseRequest , gbEventSourceListener ));
846850 }
847851
848- private synchronized void scheduleSseReconnect (Boolean retryOnFailure ) {
849- if (!Boolean .TRUE .equals (retryOnFailure )
850- || this .shuttingDown .get ()
851- || !this .sseReconnectScheduled .compareAndSet (false , true )) {
852+ private void onSseStreamClosed (Boolean retryOnFailure , boolean streamOpened ) {
853+ if (streamOpened ) {
854+ scheduleSseReconnectAfterClose (retryOnFailure , null );
855+ } else {
856+ scheduleSseReconnectAfterFailure (retryOnFailure , "stream closed before it was opened" );
857+ }
858+ }
859+
860+ /**
861+ * An I/O error on a stream that had opened is how load balancers and proxies usually end long
862+ * streams (idle timeout, connection reset), so it is handled like a close. Errors before the
863+ * stream opened, and non-I/O errors, are failed attempts.
864+ */
865+ private void onSseStreamFailed (
866+ Boolean retryOnFailure ,
867+ boolean streamOpened ,
868+ @ Nullable Throwable throwable ,
869+ @ Nullable Response response
870+ ) {
871+ String cause = describeSseFailure (throwable , response );
872+ if (streamOpened && throwable instanceof IOException ) {
873+ scheduleSseReconnectAfterClose (retryOnFailure , cause );
874+ } else {
875+ scheduleSseReconnectAfterFailure (retryOnFailure , cause );
876+ }
877+ }
878+
879+ /**
880+ * Reconnects after an opened stream ended, e.g. a proxy enforcing a maximum stream duration.
881+ * This is routine, so it is not counted as a failed attempt: a clean close is logged at DEBUG,
882+ * an interruption at INFO with its cause. The reconnect still waits the policy's first retry
883+ * delay (initial delay capped by max delay) so a server that ends every stream immediately
884+ * cannot drive a tight reconnect loop.
885+ *
886+ * @param interruptionCause cause when the stream was cut by an I/O error, {@code null} for a clean close
887+ */
888+ private synchronized void scheduleSseReconnectAfterClose (Boolean retryOnFailure , @ Nullable String interruptionCause ) {
889+ String endReason = interruptionCause == null
890+ ? "stream closed by the server"
891+ : "stream interrupted (" + interruptionCause + ")" ;
892+ if (!tryReserveSseReconnect (retryOnFailure , endReason )) {
893+ return ;
894+ }
895+
896+ this .sseRetryAttempts .set (0 );
897+ long delayMillis = reconnectDelayAfterOpenedStreamMillis ();
898+ if (interruptionCause == null ) {
899+ log .debug ("SSE stream closed by the server. Reconnecting in {}ms." , delayMillis );
900+ } else {
901+ log .info ("SSE stream interrupted ({}). Reconnecting in {}ms." , interruptionCause , delayMillis );
902+ }
903+ submitSseReconnect (retryOnFailure , delayMillis );
904+ }
905+
906+ private long reconnectDelayAfterOpenedStreamMillis () {
907+ return this .retryPolicy .getDelayMillisBeforeAttempt (FIRST_RETRY_ATTEMPT );
908+ }
909+
910+ /**
911+ * Reconnects after a failed connection attempt, counting it against the retry policy.
912+ *
913+ * @param failureCause human-readable cause (HTTP status and/or exception) included in the log
914+ */
915+ private synchronized void scheduleSseReconnectAfterFailure (Boolean retryOnFailure , String failureCause ) {
916+ if (!tryReserveSseReconnect (retryOnFailure , "connection failed (" + failureCause + ")" )) {
852917 return ;
853918 }
854919
@@ -858,18 +923,58 @@ private synchronized void scheduleSseReconnect(Boolean retryOnFailure) {
858923 if (nextConnectionAttempt > maxAttempts ) {
859924 this .sseRetryAttempts .set (maxAttempts );
860925 this .sseReconnectScheduled .set (false );
861- log .error ("SSE connection retries exhausted after {} attempts." , maxAttempts );
926+ log .error ("SSE connection failed ({}). Retries exhausted after {} attempts." , failureCause , maxAttempts );
862927 return ;
863928 }
864929
865930 long delayMillis = this .retryPolicy .getDelayMillisBeforeAttempt (nextConnectionAttempt );
866931 log .warn (
867- "SSE connection failed. Retry attempt {}/{} in {}ms." ,
932+ "SSE connection failed ({}). Retry attempt {}/{} in {}ms." ,
933+ failureCause ,
868934 nextConnectionAttempt ,
869935 maxAttempts ,
870936 delayMillis
871937 );
938+ submitSseReconnect (retryOnFailure , delayMillis );
939+ }
872940
941+ /**
942+ * @param endReason how the stream ended, logged when SSE stops because reconnects are disabled
943+ * @return whether the caller now owns the single pending reconnect
944+ */
945+ private boolean tryReserveSseReconnect (Boolean retryOnFailure , String endReason ) {
946+ if (this .shuttingDown .get ()) {
947+ return false ;
948+ }
949+ if (!Boolean .TRUE .equals (retryOnFailure )) {
950+ log .warn ("SSE {}. Reconnect on failure is disabled, so SSE updates have stopped." , endReason );
951+ return false ;
952+ }
953+ return this .sseReconnectScheduled .compareAndSet (false , true );
954+ }
955+
956+ private static String describeSseFailure (@ Nullable Throwable throwable , @ Nullable Response response ) {
957+ StringBuilder cause = new StringBuilder ();
958+ if (response != null ) {
959+ cause .append ("HTTP " ).append (response .code ());
960+ }
961+ if (throwable != null ) {
962+ if (cause .length () > 0 ) {
963+ cause .append (", " );
964+ }
965+ cause .append (throwable .getClass ().getSimpleName ());
966+ if (throwable .getMessage () != null ) {
967+ cause .append (": " ).append (throwable .getMessage ());
968+ }
969+ }
970+ return cause .length () == 0 ? "unknown cause" : cause .toString ();
971+ }
972+
973+ /**
974+ * Caller must hold this instance's monitor, which {@link #shutdown()} also takes before tearing
975+ * down {@code sseRetryScheduler}.
976+ */
977+ private void submitSseReconnect (Boolean retryOnFailure , long delayMillis ) {
873978 if (this .sseRetryScheduler == null || this .sseRetryScheduler .isShutdown ()) {
874979 this .sseRetryScheduler = Executors .newSingleThreadScheduledExecutor (SSE_RETRY_THREAD_FACTORY );
875980 }
@@ -1514,7 +1619,7 @@ public void shutdown() {
15141619 executorService .shutdown ();
15151620 log .info ("Polling scheduler shut down" );
15161621 }
1517- // Synchronize on the same monitor as scheduleSseReconnect() so a reconnect that passed the
1622+ // Synchronize on the same monitor as the scheduleSseReconnect* methods so a reconnect that passed the
15181623 // shuttingDown check cannot create a new scheduler after we have torn it down (which would
15191624 // leak an executor). shuttingDown is set above, so once we hold the lock no new scheduler
15201625 // will be created.
0 commit comments