Skip to content

Commit c0bc48f

Browse files
kabirclaude
andauthored
feat: add TaskStreamLifecycleHook for stream lifecycle management (a2aproject#1008)
* feat: add TaskStreamLifecycleHook for stream lifecycle management Add a CDI-discoverable hook that lets users observe task stream lifecycle events (subscribe, unsubscribe, event) and close all ChildQueues for a task on demand via StreamCloseHandle. Wired through InMemoryQueueManager, MainEventBusProcessor, and ReplicatedQueueManager. Includes a stream-lifecycle example with integration tests for all three transports (JSONRPC, gRPC, REST) and documentation. This fixes a2aproject#990 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent fb4411f commit c0bc48f

24 files changed

Lines changed: 1574 additions & 9 deletions

File tree

‎docs/content/dev/examples.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,45 @@ The client expects an OpenTelemetry collector on port 5317. The easiest way is t
144144

145145
For more information, see the [OpenTelemetry extras module](extras/opentelemetry).
146146

147+
## Stream Lifecycle Hook
148+
149+
This example demonstrates the `TaskStreamLifecycleHook` — a CDI-discoverable hook that observes stream lifecycle events and can close all active streams on demand.
150+
151+
The server implements a hook that closes all subscriber streams when 3 clients connect to the same task. The client creates 3 subscribers sequentially, sending messages while the first two are active. When the third subscriber connects, the hook fires and all streams close gracefully.
152+
153+
### Start the Server
154+
155+
```bash
156+
cd examples/stream-lifecycle/server
157+
mvn quarkus:dev
158+
```
159+
160+
### Run the Client
161+
162+
```bash
163+
cd examples/stream-lifecycle/client
164+
mvn exec:java
165+
```
166+
167+
The client logs each event received by each subscriber, showing events flowing to subscribers 1 and 2 before the hook triggers.
168+
169+
#### Transport Protocol Selection
170+
171+
```bash
172+
# JSON-RPC (default)
173+
mvn exec:java
174+
175+
# gRPC
176+
mvn exec:java -Dquarkus.agentcard.protocol=GRPC
177+
178+
# HTTP+JSON/REST
179+
mvn exec:java -Dquarkus.agentcard.protocol=HTTP+JSON
180+
```
181+
182+
Select the same protocol on both server and client.
183+
184+
For implementation details, see the [Stream Lifecycle Hook section](server#6-stream-lifecycle-hook-optional) in the Server Guide.
185+
147186
## More Examples
148187

149188
- [a2a-samples repository](https://github.com/a2aproject/a2a-samples/tree/main/samples/java/agents) — Additional agent examples in Java and other languages

‎docs/content/dev/server.md‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,71 @@ See [Configuration](configuration) for all config properties and tuning.
158158

159159
See [Task Authorization](authorization) for per-user access control.
160160

161+
## 6. Stream Lifecycle Hook (Optional)
162+
163+
The `TaskStreamLifecycleHook` lets you observe and control streaming connections for a task. You are notified when clients subscribe, unsubscribe, or when events are distributed, and you can close all active streams on demand via the `StreamCloseHandle`.
164+
165+
### Implementing a Hook
166+
167+
Create a CDI bean that implements `TaskStreamLifecycleHook` and overrides the default no-op:
168+
169+
```java
170+
@ApplicationScoped
171+
@Alternative
172+
@Priority(1)
173+
public class MyStreamHook implements TaskStreamLifecycleHook {
174+
175+
@Override
176+
public void onSubscribe(String taskId, StreamCloseHandle handle) {
177+
// Called when a client subscribes to a task's event stream
178+
}
179+
180+
@Override
181+
public void onUnsubscribe(String taskId, StreamCloseHandle handle) {
182+
// Called when a client disconnects
183+
}
184+
185+
@Override
186+
public void onEvent(String taskId, Event event, StreamCloseHandle handle) {
187+
// Called after an event is persisted and distributed to all subscribers
188+
}
189+
}
190+
```
191+
192+
### StreamCloseHandle
193+
194+
Each callback receives a `StreamCloseHandle` with two methods:
195+
196+
- **`closeStreams()`** — Gracefully closes all active subscriber streams for the task. The agent executor continues running and the MainQueue stays alive (for non-finalized tasks), so new clients can resubscribe.
197+
- **`getActiveSubscriberCount()`** — Returns the number of currently connected subscribers.
198+
199+
### Example: Close Streams at a Subscriber Threshold
200+
201+
```java
202+
@ApplicationScoped
203+
@Alternative
204+
@Priority(1)
205+
public class CloseStreamsHook implements TaskStreamLifecycleHook {
206+
207+
private static final int MAX_SUBSCRIBERS = 3;
208+
209+
@Override
210+
public void onSubscribe(String taskId, StreamCloseHandle handle) {
211+
if (handle.getActiveSubscriberCount() >= MAX_SUBSCRIBERS) {
212+
handle.closeStreams();
213+
}
214+
}
215+
216+
@Override
217+
public void onUnsubscribe(String taskId, StreamCloseHandle handle) { }
218+
219+
@Override
220+
public void onEvent(String taskId, Event event, StreamCloseHandle handle) { }
221+
}
222+
```
223+
224+
See the [`examples/stream-lifecycle`](https://github.com/a2aproject/a2a-java/tree/main/examples/stream-lifecycle) directory for a complete working example with server, client, and integration tests for all three transports.
225+
161226
## Backward Compatibility with v0.3
162227

163228
See [Backward Compatibility](compatibility) for multi-version modules, version routing, and v0.3 client support.
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
# Stream Lifecycle Hook Example
2+
3+
This example demonstrates `TaskStreamLifecycleHook`, a CDI-discoverable hook that lets you observe and control streaming connections for a task. The server closes all active streams when 3 subscribers connect to the same task.
4+
5+
For example, in order to save resources associated with streaming connections, you might want to close streams:
6+
7+
* If no events are received for a Task in a given timeframe. This can help if you have a lot of Tasks taking a very long time to complete
8+
* Stopping rogue client opening too many subscriptions to the same Task
9+
10+
## Prerequisites
11+
12+
- Java 17 or higher
13+
- Maven
14+
15+
## What It Does
16+
17+
**Server** — An agent sends 20 progress messages (one every 500ms). A `CloseStreamsHook` monitors subscriber count and calls `StreamCloseHandle.closeStreams()` when 3 subscribers are connected, gracefully closing all streams.
18+
19+
**Client** — Connects 3 subscribers sequentially:
20+
1. Subscriber 1 sends a message (creates the task, starts streaming)
21+
2. Subscriber 2 subscribes to the same task after 1.5 seconds
22+
3. Both subscribers receive progress messages for 2 seconds
23+
4. Subscriber 3 subscribes — the hook fires and closes all streams
24+
5. All 3 subscribers see their streams end gracefully
25+
26+
## Run the Example
27+
28+
### 1. Build the SDK
29+
30+
From the repository root:
31+
32+
```bash
33+
mvn clean install -DskipTests
34+
```
35+
36+
### 2. Start the Server
37+
38+
```bash
39+
cd examples/stream-lifecycle/server
40+
mvn quarkus:dev
41+
```
42+
43+
### 3. Run the Client
44+
45+
In a separate terminal:
46+
47+
```bash
48+
cd examples/stream-lifecycle/client
49+
mvn exec:java
50+
```
51+
52+
### Expected Output (Client)
53+
54+
The exact event interleaving depends on timing, but you should see something like:
55+
56+
```
57+
Resolved agent card: Stream Lifecycle Demo Agent
58+
[Sub-1] Sending message to create task...
59+
[Sub-1] StatusUpdate — TASK_STATE_WORKING
60+
61+
=== Task created: <task-id> ===
62+
63+
[Sub-1] ArtifactEvent — Progress update 1/20
64+
[Sub-1] ArtifactEvent — Progress update 2/20
65+
[Sub-1] ArtifactEvent — Progress update 3/20
66+
[Sub-2] Subscribing to task <task-id>...
67+
68+
=== Subscribers 1 and 2 are active — receiving events... ===
69+
70+
[Sub-2] TaskEvent — state: TASK_STATE_WORKING, id: <task-id>
71+
[Sub-1] ArtifactEvent — Progress update 4/20
72+
[Sub-2] ArtifactEvent — Progress update 4/20
73+
[Sub-1] ArtifactEvent — Progress update 5/20
74+
[Sub-2] ArtifactEvent — Progress update 5/20
75+
...
76+
[Sub-3] Subscribing to task <task-id> (will trigger stream close)...
77+
[Sub-1] Stream closed.
78+
[Sub-2] Stream closed.
79+
[Sub-3] Stream closed.
80+
81+
=== All streams closed. ===
82+
```
83+
84+
### Expected Output (Server)
85+
86+
```
87+
[HOOK] Subscriber added for task <id>. Active subscribers: 1
88+
[AGENT] Starting execution for task <id>
89+
[AGENT] Sending: Progress update 1/20
90+
[HOOK] Event distributed for task <id>: Message (subscribers: 1)
91+
...
92+
[HOOK] Subscriber added for task <id>. Active subscribers: 2
93+
...
94+
[HOOK] Subscriber added for task <id>. Active subscribers: 3
95+
[HOOK] Subscriber count reached 3 for task <id> — closing all streams
96+
[HOOK] Subscriber removed for task <id>. Active subscribers: 2
97+
[HOOK] Subscriber removed for task <id>. Active subscribers: 1
98+
[HOOK] Subscriber removed for task <id>. Active subscribers: 0
99+
```
100+
101+
## Transport Protocol Selection
102+
103+
Set `quarkus.agentcard.protocol` on both server and client (must match). Available values:
104+
105+
| Value | Transport |
106+
|-------|-----------|
107+
| `JSONRPC` | JSON-RPC 2.0 (default) |
108+
| `GRPC` | gRPC |
109+
| `HTTP+JSON` | HTTP+JSON/REST |
110+
111+
```bash
112+
# Server — gRPC example
113+
mvn quarkus:dev -Dquarkus.agentcard.protocol=GRPC
114+
115+
# Client — must use the same value
116+
mvn exec:java -Dquarkus.agentcard.protocol=GRPC
117+
```
118+
119+
## Key Files
120+
121+
| File | Description |
122+
|------|-------------|
123+
| `server/.../CloseStreamsHook.java` | `TaskStreamLifecycleHook` implementation — closes streams at 3 subscribers |
124+
| `server/.../AgentExecutorProducer.java` | Agent that sends 20 progress messages over 10 seconds |
125+
| `server/.../AgentCardProducer.java` | Agent card with streaming enabled |
126+
| `client/.../StreamLifecycleClient.java` | Client that creates 3 subscribers and logs events |
127+
128+
## Integration Tests
129+
130+
The server module includes `@QuarkusTest` integration tests that verify the hook behavior across all three transports:
131+
132+
```bash
133+
cd examples/stream-lifecycle/server
134+
mvn test
135+
```
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
<?xml version="1.0"?>
2+
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"
3+
xmlns="http://maven.apache.org/POM/4.0.0"
4+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<parent>
8+
<groupId>org.a2aproject.sdk</groupId>
9+
<artifactId>a2a-java-sdk-examples-stream-lifecycle-parent</artifactId>
10+
<version>1.1.1.Final-SNAPSHOT</version>
11+
</parent>
12+
13+
<artifactId>a2a-java-sdk-examples-stream-lifecycle-client</artifactId>
14+
15+
<name>Java SDK A2A Examples - Stream Lifecycle Client</name>
16+
<description>Client demonstrating TaskStreamLifecycleHook with multiple subscribers</description>
17+
18+
<dependencies>
19+
<dependency>
20+
<groupId>org.a2aproject.sdk</groupId>
21+
<artifactId>a2a-java-sdk-client</artifactId>
22+
</dependency>
23+
<dependency>
24+
<groupId>org.a2aproject.sdk</groupId>
25+
<artifactId>a2a-java-sdk-jsonrpc-common</artifactId>
26+
</dependency>
27+
<dependency>
28+
<groupId>org.a2aproject.sdk</groupId>
29+
<artifactId>a2a-java-sdk-client-transport-grpc</artifactId>
30+
</dependency>
31+
<dependency>
32+
<groupId>io.grpc</groupId>
33+
<artifactId>grpc-netty</artifactId>
34+
</dependency>
35+
<dependency>
36+
<groupId>org.a2aproject.sdk</groupId>
37+
<artifactId>a2a-java-sdk-client-transport-rest</artifactId>
38+
</dependency>
39+
<dependency>
40+
<groupId>org.junit.jupiter</groupId>
41+
<artifactId>junit-jupiter-api</artifactId>
42+
<scope>compile</scope>
43+
</dependency>
44+
</dependencies>
45+
46+
<build>
47+
<plugins>
48+
<plugin>
49+
<groupId>org.codehaus.mojo</groupId>
50+
<artifactId>exec-maven-plugin</artifactId>
51+
<version>3.6.3</version>
52+
<configuration>
53+
<mainClass>org.a2aproject.sdk.examples.streamlifecycle.client.StreamLifecycleClient</mainClass>
54+
</configuration>
55+
</plugin>
56+
</plugins>
57+
</build>
58+
</project>

0 commit comments

Comments
 (0)