Skip to content

Commit 70ec9c8

Browse files
committed
fix(streaming): honor retry hints and preserve cancellation outcomes
1 parent 40c6753 commit 70ec9c8

7 files changed

Lines changed: 187 additions & 12 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66

77
- Repeated default header settings now replace earlier values case-insensitively, while per-request headers retain precedence.
88
- Realtime handshake and connection failures now retain the underlying exception through `RealtimeException.getCause()` for diagnostics.
9+
- Resumable SSE subscriptions honor valid `Retry-After` and `retry-after-ms` response headers after HTTP retries are exhausted, while cancellation and total deadlines still interrupt reconnect waits.
10+
- Closing an active event subscription records cancellation before releasing its reader, preventing a race that could incorrectly report successful completion.
911

1012
### Validation
1113

‎docs/session-streaming.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ try (EventStream<SessionEvent> stream = client.sessions().events().resumableStre
4747
}
4848
```
4949

50-
`resumableStream` is lazy and reconnects after EOF, transport failures and retryable HTTP errors. Reconnect waits use jittered exponential backoff from 500 ms to a 10-second cap. This continues until closed, the total deadline expires, a terminal event arrives, or a nonretryable error occurs. `maxRetries` governs each HTTP handshake, not the lifetime of this explicitly persistent subscription. A connection that yields events after five seconds resets its backoff.
50+
`resumableStream` is lazy and reconnects after EOF, transport failures and retryable HTTP errors. For HTTP errors, reconnect waits honor valid `retry-after-ms` or `Retry-After` (seconds or HTTP date), including after the HTTP retry budget is exhausted. Server delays must be positive and at most 2³¹−1 milliseconds, following the ordinary HTTP retry policy. Otherwise, reconnect waits use jittered exponential backoff from 500 ms to a 10-second cap. Cancellation and the total deadline interrupt either kind of wait. This continues until closed, the total deadline expires, a terminal event arrives, or a nonretryable error occurs. `maxRetries` governs each HTTP handshake, not the lifetime of this explicitly persistent subscription. A connection that yields events after five seconds resets its backoff.
5151

5252
- Reconnect retains the path, filters and request options, but replaces `Last-Event-ID` with the last fully **yielded** frame's ID. Calling `hasNext()` alone does not advance the public checkpoint. An incomplete or invalid frame is not acknowledged. An empty SSE ID clears the cursor. The SSE frame ID is used, not an assumed JSON payload ID.
5353
- It calls the shared Credential again for each connection. `ServiceAccountCredential` reuses or refreshes SAT according to expiry; it does not send an SA Key to business endpoints. There is no mid-connection token refresh or forced reconnect just because a token expires.

‎src/main/java/com/qoder/cloudagents/core/internal/RetryPolicy.java‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,16 +23,21 @@ public static boolean shouldRetry(
2323
}
2424

2525
public static long delayMillis(Headers headers, int attempt, Clock clock, double random) {
26-
Double delay = number(headers.get("retry-after-ms"));
26+
Long delay = retryAfterMillis(headers.get("retry-after-ms"), headers.get("retry-after"), clock);
27+
if (delay != null) return delay;
28+
return (long) (Math.min(500 * Math.pow(2, Math.min(attempt, 5)), 8000) * (1 - random * .25));
29+
}
30+
31+
public static Long retryAfterMillis(String retryAfterMs, String retryAfter, Clock clock) {
32+
Double delay = number(retryAfterMs);
2733
if (delay == null || delay == 0) {
28-
String after = headers.get("retry-after");
29-
Double seconds = number(after);
34+
Double seconds = number(retryAfter);
3035
if (seconds != null) delay = seconds * 1000;
31-
else if (after != null) {
36+
else if (retryAfter != null) {
3237
try {
3338
delay =
3439
(double)
35-
(ZonedDateTime.parse(after, DateTimeFormatter.RFC_1123_DATE_TIME)
40+
(ZonedDateTime.parse(retryAfter, DateTimeFormatter.RFC_1123_DATE_TIME)
3641
.toInstant()
3742
.toEpochMilli()
3843
- clock.millis());
@@ -43,7 +48,7 @@ else if (after != null) {
4348
}
4449
if (delay != null && Double.isFinite(delay) && delay > 0 && delay <= MAX_DELAY_MS)
4550
return Math.max(1, (long) Math.ceil(delay));
46-
return (long) (Math.min(500 * Math.pow(2, Math.min(attempt, 5)), 8000) * (1 - random * .25));
51+
return null;
4752
}
4853

4954
private static Double number(String value) {

‎src/main/java/com/qoder/cloudagents/streaming/EventStream.java‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import com.qoder.cloudagents.errors.*;
66
import java.io.IOException;
77
import java.nio.charset.CharacterCodingException;
8+
import java.time.Clock;
89
import java.util.*;
910
import java.util.concurrent.*;
1011
import java.util.concurrent.atomic.AtomicBoolean;
@@ -167,7 +168,7 @@ private Item<T> readNext() {
167168
finish();
168169
return null;
169170
}
170-
reconnect();
171+
reconnect(null);
171172
continue;
172173
}
173174
if (frame.type.equals("ping")) continue;
@@ -198,10 +199,22 @@ private boolean recover(RuntimeException error) {
198199
fail(error);
199200
throw error;
200201
}
201-
reconnect();
202+
Long delay = null;
203+
if (error instanceof ApiStatusException) {
204+
ApiStatusException status = (ApiStatusException) error;
205+
delay =
206+
RetryPolicy.retryAfterMillis(
207+
header(status, "retry-after-ms"), header(status, "retry-after"), Clock.systemUTC());
208+
}
209+
reconnect(delay);
202210
return true;
203211
}
204212

213+
private static String header(ApiStatusException error, String name) {
214+
List<String> values = error.headers().get(name);
215+
return values == null || values.isEmpty() ? null : values.get(values.size() - 1);
216+
}
217+
205218
private static boolean retryable(RuntimeException error) {
206219
if (error instanceof ApiStatusException) {
207220
ApiStatusException status = (ApiStatusException) error;
@@ -214,9 +227,12 @@ private static boolean retryable(RuntimeException error) {
214227
return error instanceof ApiConnectionException;
215228
}
216229

217-
private synchronized void reconnect() {
230+
private synchronized void reconnect(Long retryAfterMillis) {
218231
releaseConnection();
219-
long delay = ThreadLocalRandom.current().nextLong(Math.max(1, backoff / 2), backoff + 1);
232+
long delay =
233+
retryAfterMillis != null
234+
? retryAfterMillis
235+
: ThreadLocalRandom.current().nextLong(Math.max(1, backoff / 2), backoff + 1);
220236
backoff = Math.min(backoff * 2, 10000);
221237
long until = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(delay);
222238
try {

‎src/main/java/com/qoder/cloudagents/streaming/EventSubscription.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ public CompletableFuture<Void> completion() {
2222
/** In-flight user callbacks may finish; no further callback is scheduled. */
2323
@Override
2424
public void close() {
25-
close.run();
25+
// Record cancellation before waking the reader, which could otherwise report success.
2626
completion.cancel(false);
27+
close.run();
2728
}
2829
}

‎src/test/java/com/qoder/cloudagents/SessionStreamsTest.java‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import okhttp3.mockwebserver.*;
1515
import org.junit.jupiter.api.*;
1616
import org.junit.jupiter.params.ParameterizedTest;
17+
import org.junit.jupiter.params.provider.CsvSource;
1718
import org.junit.jupiter.params.provider.ValueSource;
1819

1920
@Timeout(15)
@@ -378,6 +379,93 @@ void explicitResumeRetriesTransientStatus(int code) throws Exception {
378379
assertEquals(2, server.getRequestCount());
379380
}
380381

382+
@ParameterizedTest
383+
@CsvSource({
384+
"429, Retry-After, 1, 0",
385+
"503, retry-after-ms, 800, 0",
386+
"429, retry-after-ms, 800, 1"
387+
})
388+
void reconnectHonorsServerDelayAfterHttpRetryBudget(
389+
int status, String header, String value, int retries) throws Exception {
390+
if (retries > 0)
391+
server.enqueue(
392+
new MockResponse()
393+
.setResponseCode(status)
394+
.setHeader("retry-after-ms", "1")
395+
.setBody("{}"));
396+
server.enqueue(
397+
new MockResponse().setResponseCode(status).setHeader(header, value).setBody("{}"));
398+
server.enqueue(sse(event("end", "session.deleted")));
399+
try (EventStream<SessionEvent> stream =
400+
client
401+
.sessions()
402+
.events()
403+
.resumableStream(
404+
"s",
405+
SessionEventStreamParams.builder().build(),
406+
RequestOptions.builder()
407+
.maxRetries(retries)
408+
.totalTimeout(Duration.ofSeconds(5))
409+
.build())) {
410+
EventSubscription subscription = stream.subscribe(e -> {});
411+
for (int i = 0; i <= retries; i++) take();
412+
assertNull(server.takeRequest(600, TimeUnit.MILLISECONDS));
413+
take();
414+
subscription.completion().get(2, TimeUnit.SECONDS);
415+
assertEquals(retries + 2, server.getRequestCount());
416+
}
417+
}
418+
419+
@Test
420+
void totalDeadlineInterruptsServerRetryDelay() {
421+
server.enqueue(
422+
new MockResponse().setResponseCode(429).setHeader("Retry-After", "30").setBody("{}"));
423+
server.enqueue(sse(event("end", "session.deleted")));
424+
try (EventStream<SessionEvent> stream =
425+
client
426+
.sessions()
427+
.events()
428+
.resumableStream("s", SessionEventStreamParams.builder().build(), deadline(1000))) {
429+
assertThrows(ApiTimeoutException.class, () -> stream.iterator().hasNext());
430+
assertEquals(1, server.getRequestCount());
431+
}
432+
}
433+
434+
@Test
435+
void subscriptionCloseInterruptsServerRetryDelayAndReportsCancellation() throws Exception {
436+
server.enqueue(
437+
new MockResponse().setResponseCode(429).setHeader("Retry-After", "30").setBody("{}"));
438+
server.enqueue(sse(event("end", "session.deleted")));
439+
ExecutorService reader = Executors.newSingleThreadExecutor();
440+
CompletableFuture<Void> finished = new CompletableFuture<>();
441+
try (EventStream<SessionEvent> stream =
442+
client
443+
.sessions()
444+
.events()
445+
.resumableStream("s", SessionEventStreamParams.builder().build(), deadline(5000))) {
446+
EventSubscription subscription =
447+
stream.subscribe(
448+
e -> fail("No event expected during the server retry delay"),
449+
task ->
450+
reader.execute(
451+
() -> {
452+
try {
453+
task.run();
454+
} finally {
455+
finished.complete(null);
456+
}
457+
}));
458+
take();
459+
assertNull(server.takeRequest(600, TimeUnit.MILLISECONDS));
460+
subscription.close();
461+
assertThrows(CancellationException.class, () -> subscription.completion().get());
462+
finished.get(1, TimeUnit.SECONDS);
463+
assertEquals(1, server.getRequestCount());
464+
} finally {
465+
reader.shutdownNow();
466+
}
467+
}
468+
381469
@Test
382470
void retryHintFalseStopsResume() {
383471
server.enqueue(
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.qoder.cloudagents.streaming;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import java.util.concurrent.*;
6+
import java.util.concurrent.atomic.AtomicReference;
7+
import org.junit.jupiter.api.*;
8+
9+
@Timeout(5)
10+
class EventSubscriptionTest {
11+
@Test
12+
void closeKeepsCancellationWhenReaderFinishesDuringCleanup() throws Exception {
13+
ExecutorService executor = Executors.newSingleThreadExecutor();
14+
CountDownLatch closing = new CountDownLatch(1);
15+
AtomicReference<EventSubscription> reference = new AtomicReference<>();
16+
Future<?> reader =
17+
executor.submit(
18+
() -> {
19+
assertTrue(closing.await(2, TimeUnit.SECONDS));
20+
reference.get().completion().complete(null);
21+
return null;
22+
});
23+
EventSubscription subscription =
24+
new EventSubscription(
25+
() -> {
26+
closing.countDown();
27+
try {
28+
reader.get(2, TimeUnit.SECONDS);
29+
} catch (Exception error) {
30+
throw new AssertionError(error);
31+
}
32+
});
33+
reference.set(subscription);
34+
try {
35+
subscription.close();
36+
assertTrue(subscription.completion().isCancelled());
37+
assertThrows(CancellationException.class, () -> subscription.completion().join());
38+
} finally {
39+
closing.countDown();
40+
executor.shutdownNow();
41+
}
42+
}
43+
44+
@Test
45+
void closePreservesAnAlreadyCompletedOutcomeAndStillReleasesResources() {
46+
for (boolean failed : new boolean[] {false, true}) {
47+
CountDownLatch released = new CountDownLatch(1);
48+
EventSubscription subscription = new EventSubscription(released::countDown);
49+
RuntimeException error = new IllegalStateException("reader failed");
50+
if (failed) subscription.completion().completeExceptionally(error);
51+
else subscription.completion().complete(null);
52+
subscription.close();
53+
assertFalse(subscription.completion().isCancelled());
54+
assertEquals(0, released.getCount());
55+
if (failed)
56+
assertSame(
57+
error,
58+
assertThrows(CompletionException.class, () -> subscription.completion().join())
59+
.getCause());
60+
else assertNull(subscription.completion().join());
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)