Skip to content

Commit e3f3053

Browse files
committed
fix(compat-0.3): close the SSE stream on terminal events
The 0.3 SSE listeners only stop reading a stream when the server tears the connection down. The native listeners close it themselves as soon as the event that ends the task arrives, and that difference is visible on a late resubscription to a task that already finished. - RestSSEEventListener_v0_3 took the cancellation future in onMessage and then dropped it: handleMessage() never received it, so neither a final status update nor a terminal task snapshot closed the connection. The listener now passes the future to an auto-close check, the same way AbstractSSEEventListener.handleEvent does. - SSEEventListener_v0_3 cancelled on a final status update only, and treated a task snapshot that is already in a final state as a still running stream, although that snapshot is what a resubscription to a finished task receives. Both listeners now use the same predicate as AbstractSSEEventListener.shouldAutoClose: a final status update, or a task whose state is final. The terminal callback keeps going through signalTerminal(), so a completion that arrives after the auto-close is still dropped.
1 parent 18694d9 commit e3f3053

4 files changed

Lines changed: 296 additions & 5 deletions

File tree

‎compat-0.3/client/transport/jsonrpc/src/main/java/org/a2aproject/sdk/compat03/client/transport/jsonrpc/sse/SSEEventListener_v0_3.java‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import org.a2aproject.sdk.compat03.spec.JSONRPCError_v0_3;
99
import org.a2aproject.sdk.compat03.spec.StreamingEventKind_v0_3;
1010
import org.a2aproject.sdk.compat03.spec.TaskStatusUpdateEvent_v0_3;
11+
import org.a2aproject.sdk.compat03.spec.Task_v0_3;
1112

1213
import java.util.concurrent.Future;
1314
import java.util.concurrent.atomic.AtomicBoolean;
@@ -71,7 +72,7 @@ private void handleMessage(JsonObject jsonObject, Future<Void> future) throws Js
7172
String resultJson = jsonObject.get("result").toString();
7273
StreamingEventKind_v0_3 event = JsonUtil_v0_3.fromJson(resultJson, StreamingEventKind_v0_3.class);
7374
eventHandler.accept(event);
74-
if (event instanceof TaskStatusUpdateEvent_v0_3 tsue && tsue.isFinal()) {
75+
if (shouldAutoClose(event)) {
7576
signalTerminal(null);
7677
future.cancel(true); // close SSE channel
7778
}
@@ -80,4 +81,22 @@ private void handleMessage(JsonObject jsonObject, Future<Void> future) throws Js
8081
}
8182
}
8283

84+
/**
85+
* Determines whether the stream is finished, using the same predicate as
86+
* {@code AbstractSSEEventListener.shouldAutoClose} in the native transport: a final status
87+
* update, or a task snapshot that is already in a final state.
88+
*
89+
* @param event the streaming event to check
90+
* @return {@code true} when the connection should be closed, {@code false} otherwise
91+
*/
92+
private boolean shouldAutoClose(StreamingEventKind_v0_3 event) {
93+
if (event instanceof TaskStatusUpdateEvent_v0_3 tsue && tsue.isFinal()) {
94+
return true;
95+
}
96+
if (event instanceof Task_v0_3 task) {
97+
return task.status().state().isFinal();
98+
}
99+
return false;
100+
}
101+
83102
}

‎compat-0.3/client/transport/jsonrpc/src/test/java/org/a2aproject/sdk/compat03/client/transport/jsonrpc/sse/SSEEventListener_v0_3_Test.java‎

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@
2020
import java.util.concurrent.atomic.AtomicReference;
2121

2222
import org.a2aproject.sdk.compat03.client.transport.jsonrpc.JsonStreamingMessages_v0_3;
23+
import org.a2aproject.sdk.compat03.json.JsonProcessingException_v0_3;
24+
import org.a2aproject.sdk.compat03.json.JsonUtil_v0_3;
2325
import org.a2aproject.sdk.compat03.spec.Artifact_v0_3;
2426
import org.a2aproject.sdk.compat03.spec.JSONRPCError_v0_3;
2527
import org.a2aproject.sdk.compat03.spec.Message_v0_3;
@@ -190,7 +192,7 @@ public void testOnFailure() {
190192
}
191193

192194
@Test
193-
public void testFinalTaskStatusUpdateEventCancels() {
195+
public void testFinalTaskStatusUpdateEventCancels() throws Exception {
194196
TaskStatusUpdateEvent_v0_3 tsue = new TaskStatusUpdateEvent_v0_3.Builder()
195197
.taskId("1234")
196198
.contextId("xyz")
@@ -205,7 +207,64 @@ public void testFinalTaskStatusUpdateEventCancels() {
205207
error -> {}
206208
);
207209

210+
CancelCapturingFuture future = new CancelCapturingFuture();
211+
listener.onMessage(resultPayload(tsue), future);
208212

213+
assertInstanceOf(TaskStatusUpdateEvent_v0_3.class, receivedEvent.get());
214+
assertTrue(future.cancelHandlerCalled, "A final status update has to close the SSE connection");
215+
}
216+
217+
/**
218+
* A resubscription to a task that already finished only ever receives the task snapshot itself,
219+
* which ends the stream the same way a final status update does.
220+
*/
221+
@Test
222+
public void testTerminalTaskSnapshotCancels() throws Exception {
223+
Task_v0_3 task = new Task_v0_3.Builder()
224+
.id("1234")
225+
.contextId("xyz")
226+
.status(new TaskStatus_v0_3(TaskState_v0_3.COMPLETED))
227+
.build();
228+
229+
AtomicReference<StreamingEventKind_v0_3> receivedEvent = new AtomicReference<>();
230+
AtomicInteger terminalCalls = new AtomicInteger();
231+
AtomicReference<Throwable> terminalError = new AtomicReference<>(new Throwable("not invoked"));
232+
SSEEventListener_v0_3 listener = new SSEEventListener_v0_3(
233+
event -> receivedEvent.set(event),
234+
error -> {
235+
terminalCalls.incrementAndGet();
236+
terminalError.set(error);
237+
});
238+
239+
CancelCapturingFuture future = new CancelCapturingFuture();
240+
listener.onMessage(resultPayload(task), future);
241+
242+
assertInstanceOf(Task_v0_3.class, receivedEvent.get());
243+
assertTrue(future.cancelHandlerCalled, "A task that is already in a final state has to close the SSE connection");
244+
assertEquals(1, terminalCalls.get());
245+
assertNull(terminalError.get(), "Reaching the end of the task is a normal completion");
246+
}
247+
248+
@Test
249+
public void testRunningTaskSnapshotKeepsTheConnectionOpen() throws Exception {
250+
Task_v0_3 task = new Task_v0_3.Builder()
251+
.id("1234")
252+
.contextId("xyz")
253+
.status(new TaskStatus_v0_3(TaskState_v0_3.WORKING))
254+
.build();
255+
256+
AtomicReference<StreamingEventKind_v0_3> receivedEvent = new AtomicReference<>();
257+
AtomicInteger terminalCalls = new AtomicInteger();
258+
SSEEventListener_v0_3 listener = new SSEEventListener_v0_3(
259+
event -> receivedEvent.set(event),
260+
error -> terminalCalls.incrementAndGet());
261+
262+
CancelCapturingFuture future = new CancelCapturingFuture();
263+
listener.onMessage(resultPayload(task), future);
264+
265+
assertInstanceOf(Task_v0_3.class, receivedEvent.get());
266+
assertFalse(future.cancelHandlerCalled, "A stream that is still running must not be cancelled");
267+
assertEquals(0, terminalCalls.get(), "A stream that is still running has no terminal outcome yet");
209268
}
210269

211270
@Test
@@ -343,6 +402,13 @@ public void testFinalEventThenOnErrorDeliversNormalCompletionOnly() {
343402
assertNull(terminalError.get());
344403
}
345404

405+
/**
406+
* Wraps a streaming event into the JSON-RPC result envelope the listener receives on the wire.
407+
*/
408+
private static String resultPayload(StreamingEventKind_v0_3 event) throws JsonProcessingException_v0_3 {
409+
return "{\"jsonrpc\":\"2.0\",\"id\":\"1\",\"result\":" + JsonUtil_v0_3.toJson(event) + "}";
410+
}
411+
346412
private static class CancelCapturingFuture implements Future<Void> {
347413
private boolean cancelHandlerCalled;
348414

‎compat-0.3/client/transport/rest/src/main/java/org/a2aproject/sdk/compat03/client/transport/rest/sse/RestSSEEventListener_v0_3.java‎

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
import org.a2aproject.sdk.compat03.grpc.StreamResponse;
1212
import org.a2aproject.sdk.compat03.grpc.utils.ProtoUtils_v0_3;
1313
import org.a2aproject.sdk.compat03.spec.StreamingEventKind_v0_3;
14+
import org.a2aproject.sdk.compat03.spec.TaskStatusUpdateEvent_v0_3;
15+
import org.a2aproject.sdk.compat03.spec.Task_v0_3;
1416
import org.jspecify.annotations.Nullable;
1517

1618
public class RestSSEEventListener_v0_3 {
@@ -31,7 +33,7 @@ public void onMessage(String message, @Nullable Future<Void> completableFuture)
3133
LOGGER.fine("Streaming message received: " + message);
3234
org.a2aproject.sdk.compat03.grpc.StreamResponse.Builder builder = org.a2aproject.sdk.compat03.grpc.StreamResponse.newBuilder();
3335
JsonFormat.parser().merge(message, builder);
34-
handleMessage(builder.build());
36+
handleMessage(builder.build(), completableFuture);
3537
} catch (InvalidProtocolBufferException e) {
3638
signalTerminal(RestErrorMapper_v0_3.mapRestError(message, 500));
3739
}
@@ -72,7 +74,7 @@ private void signalTerminal(@Nullable Throwable error) {
7274
}
7375
}
7476

75-
private void handleMessage(StreamResponse response) {
77+
private void handleMessage(StreamResponse response, @Nullable Future<Void> future) {
7678
StreamingEventKind_v0_3 event;
7779
switch (response.getPayloadCase()) {
7880
case MSG ->
@@ -89,7 +91,46 @@ private void handleMessage(StreamResponse response) {
8991
return;
9092
}
9193
}
94+
handleEvent(event, future);
95+
}
96+
97+
/**
98+
* Delivers the event and closes the connection once the event carries the end of the task.
99+
* <p>
100+
* This mirrors {@code AbstractSSEEventListener.handleEvent}, which the native REST and JSON-RPC
101+
* listeners inherit: a stream that reaches a final state is cancelled client side instead of
102+
* waiting for the server to tear the connection down. That wait never ends when the server keeps
103+
* the response open, which is what happens on a late resubscription to an already finished task.
104+
*
105+
* @param event the parsed streaming event
106+
* @param future optional future for controlling the SSE connection
107+
*/
108+
private void handleEvent(StreamingEventKind_v0_3 event, @Nullable Future<Void> future) {
92109
eventHandler.accept(event);
110+
111+
if (shouldAutoClose(event) && future != null) {
112+
LOGGER.fine("Auto-closing SSE connection for final event: " + event.getClass().getSimpleName());
113+
signalTerminal(null);
114+
future.cancel(true); // close SSE channel
115+
}
116+
}
117+
118+
/**
119+
* Determines whether the stream is finished, using the same predicate as
120+
* {@code AbstractSSEEventListener.shouldAutoClose}: a final status update, or a task snapshot
121+
* that is already in a final state.
122+
*
123+
* @param event the streaming event to check
124+
* @return {@code true} when the connection should be closed, {@code false} otherwise
125+
*/
126+
private boolean shouldAutoClose(StreamingEventKind_v0_3 event) {
127+
if (event instanceof TaskStatusUpdateEvent_v0_3 tue && tue.isFinal()) {
128+
return true;
129+
}
130+
if (event instanceof Task_v0_3 task) {
131+
return task.status().state().isFinal();
132+
}
133+
return false;
93134
}
94135

95136
}

0 commit comments

Comments
 (0)