Skip to content

Commit 04755c5

Browse files
committed
feat: Implement PushNotifications as per the 1.0 spec
1 parent ce6453c commit 04755c5

9 files changed

Lines changed: 347 additions & 142 deletions

File tree

‎extras/push-notification-config-store-database-jpa/src/test/java/io/a2a/extras/pushnotificationconfigstore/database/jpa/JpaDatabasePushNotificationConfigStoreIntegrationTest.java‎

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -151,11 +151,12 @@ public void testJpaDatabasePushNotificationConfigStoreIntegration() throws Excep
151151
assertTrue(updateLatch.await(10, TimeUnit.SECONDS), "Timeout waiting for task update");
152152

153153
// Step 5: Poll for the async notification to be captured
154+
// With the new StreamingEventKind support, we receive all event types (Task, Message, TaskArtifactUpdateEvent, etc.)
154155
long end = System.currentTimeMillis() + 5000;
155156
boolean notificationReceived = false;
156157

157158
while (System.currentTimeMillis() < end) {
158-
if (!mockPushNotificationSender.getCapturedTasks().isEmpty()) {
159+
if (!mockPushNotificationSender.getCapturedEvents().isEmpty()) {
159160
notificationReceived = true;
160161
break;
161162
}
@@ -165,17 +166,22 @@ public void testJpaDatabasePushNotificationConfigStoreIntegration() throws Excep
165166
assertTrue(notificationReceived, "Timeout waiting for push notification.");
166167

167168
// Step 6: Verify the captured notification
168-
Queue<Task> capturedTasks = mockPushNotificationSender.getCapturedTasks();
169-
170-
// Verify the notification contains the correct task with artifacts
171-
Task notifiedTaskWithArtifact = capturedTasks.stream()
172-
.filter(t -> taskId.equals(t.id()) && t.artifacts() != null && t.artifacts().size() > 0)
173-
.findFirst()
174-
.orElse(null);
175-
176-
assertNotNull(notifiedTaskWithArtifact, "Notification should contain the updated task with artifacts");
177-
assertEquals(taskId, notifiedTaskWithArtifact.id());
178-
assertEquals(1, notifiedTaskWithArtifact.artifacts().size(), "Task should have one artifact from the update");
169+
// Check if we received events for this task (could be Task, TaskArtifactUpdateEvent, etc.)
170+
Queue<io.a2a.spec.StreamingEventKind> capturedEvents = mockPushNotificationSender.getCapturedEvents();
171+
172+
// Look for Task events with artifacts OR TaskArtifactUpdateEvent for this task
173+
boolean hasTaskWithArtifact = capturedEvents.stream()
174+
.filter(e -> e instanceof Task)
175+
.map(e -> (Task) e)
176+
.anyMatch(t -> taskId.equals(t.id()) && t.artifacts() != null && t.artifacts().size() > 0);
177+
178+
boolean hasArtifactUpdateEvent = capturedEvents.stream()
179+
.filter(e -> e instanceof io.a2a.spec.TaskArtifactUpdateEvent)
180+
.map(e -> (io.a2a.spec.TaskArtifactUpdateEvent) e)
181+
.anyMatch(e -> taskId.equals(e.taskId()));
182+
183+
assertTrue(hasTaskWithArtifact || hasArtifactUpdateEvent,
184+
"Notification should contain either Task with artifacts or TaskArtifactUpdateEvent for task " + taskId);
179185

180186
// Step 7: Clean up - delete the push notification configuration
181187
client.deleteTaskPushNotificationConfigurations(

‎extras/push-notification-config-store-database-jpa/src/test/java/io/a2a/extras/pushnotificationconfigstore/database/jpa/MockPushNotificationSender.java‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import jakarta.enterprise.inject.Alternative;
99

1010
import io.a2a.server.tasks.PushNotificationSender;
11+
import io.a2a.spec.StreamingEventKind;
1112
import io.a2a.spec.Task;
1213

1314
/**
@@ -19,18 +20,30 @@
1920
@Priority(100)
2021
public class MockPushNotificationSender implements PushNotificationSender {
2122

22-
private final Queue<Task> capturedTasks = new ConcurrentLinkedQueue<>();
23+
private final Queue<StreamingEventKind> capturedEvents = new ConcurrentLinkedQueue<>();
2324

2425
@Override
25-
public void sendNotification(Task task) {
26-
capturedTasks.add(task);
26+
public void sendNotification(StreamingEventKind event) {
27+
capturedEvents.add(event);
2728
}
2829

30+
public Queue<StreamingEventKind> getCapturedEvents() {
31+
return capturedEvents;
32+
}
33+
34+
/**
35+
* For backward compatibility - provides access to Task events only.
36+
*/
2937
public Queue<Task> getCapturedTasks() {
30-
return capturedTasks;
38+
Queue<Task> tasks = new ConcurrentLinkedQueue<>();
39+
capturedEvents.stream()
40+
.filter(e -> e instanceof Task)
41+
.map(e -> (Task) e)
42+
.forEach(tasks::add);
43+
return tasks;
3144
}
3245

3346
public void clear() {
34-
capturedTasks.clear();
47+
capturedEvents.clear();
3548
}
3649
}

‎server-common/src/main/java/io/a2a/server/events/MainEventBusProcessor.java‎

Lines changed: 21 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import io.a2a.spec.InternalError;
1717
import io.a2a.spec.Message;
1818
import io.a2a.spec.Task;
19+
import io.a2a.spec.StreamingEventKind;
1920
import io.a2a.spec.TaskArtifactUpdateEvent;
2021
import io.a2a.spec.TaskStatusUpdateEvent;
2122
import org.slf4j.Logger;
@@ -220,16 +221,11 @@ private void processEvent(MainEventBusContext context) {
220221

221222
// Step 2: Send push notification AFTER successful persistence (only from active node)
222223
// Skip push notifications for replicated events to avoid duplicate notifications in multi-instance deployments
223-
if (eventToDistribute == event && !isReplicated) {
224-
// Capture task state immediately after persistence, before going async
225-
// This ensures we send the task as it existed when THIS event was processed,
226-
// not whatever state might exist later when the async callback executes
227-
Task taskSnapshot = taskStore.get(taskId);
228-
if (taskSnapshot != null) {
229-
sendPushNotification(taskId, taskSnapshot);
230-
} else {
231-
LOGGER.warn("Task {} not found in TaskStore after successful persistence, skipping push notification", taskId);
232-
}
224+
// Push notifications are sent for all StreamingEventKind events (Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent)
225+
// per A2A spec section 4.3.3
226+
if (eventToDistribute == event && !isReplicated && event instanceof StreamingEventKind streamingEvent) {
227+
// Send the streaming event directly - it will be wrapped in StreamResponse format by PushNotificationSender
228+
sendPushNotification(taskId, streamingEvent);
233229
}
234230

235231
// Step 3: Then distribute to ChildQueues (clients see either event or error AFTER persistence attempt)
@@ -313,7 +309,7 @@ private boolean updateTaskStore(String taskId, Event event, boolean isReplicated
313309
}
314310

315311
/**
316-
* Sends push notification for the task AFTER persistence.
312+
* Sends push notification for the streaming event AFTER persistence.
317313
* <p>
318314
* This is called after updateTaskStore() to ensure the notification contains
319315
* the latest persisted state, avoiding race conditions.
@@ -324,27 +320,32 @@ private boolean updateTaskStore(String taskId, Event event, boolean isReplicated
324320
* PushNotificationSender.sendNotification() was causing streaming delays.
325321
* </p>
326322
* <p>
327-
* <b>IMPORTANT:</b> The task parameter is a snapshot captured immediately after
328-
* persistence. This ensures we send the task state as it existed when THIS event
329-
* was processed, not whatever state might exist in TaskStore when the async
330-
* callback executes (subsequent events may have already updated the store).
323+
* <b>IMPORTANT:</b> The event parameter is the actual event being processed.
324+
* This ensures we send the event as it was when processed, not whatever state
325+
* might exist in TaskStore when the async callback executes (subsequent events
326+
* may have already updated the store).
327+
* </p>
328+
* <p>
329+
* Supports all StreamingEventKind event types per A2A spec section 4.3.3:
330+
* Task, Message, TaskStatusUpdateEvent, TaskArtifactUpdateEvent.
331+
* The event will be automatically wrapped in StreamResponse format by JsonUtil.
331332
* </p>
332333
* <p>
333334
* <b>NOTE:</b> Tests can inject a synchronous executor via setPushNotificationExecutor()
334335
* to ensure deterministic ordering of push notifications in the test environment.
335336
* </p>
336337
*
337338
* @param taskId the task ID
338-
* @param task the task snapshot to send (captured immediately after persistence)
339+
* @param event the streaming event to send (Task, Message, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent)
339340
*/
340-
private void sendPushNotification(String taskId, Task task) {
341+
private void sendPushNotification(String taskId, StreamingEventKind event) {
341342
Runnable pushTask = () -> {
342343
try {
343-
if (task != null) {
344+
if (event != null) {
344345
LOGGER.debug("Sending push notification for task {}", taskId);
345-
pushSender.sendNotification(task);
346+
pushSender.sendNotification(event);
346347
} else {
347-
LOGGER.debug("Skipping push notification - task snapshot is null for task {}", taskId);
348+
LOGGER.debug("Skipping push notification - event is null for task {}", taskId);
348349
}
349350
} catch (Exception e) {
350351
LOGGER.error("Error sending push notification for task {}", taskId, e);

‎server-common/src/main/java/io/a2a/server/tasks/BasePushNotificationSender.java‎

Lines changed: 42 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import static io.a2a.common.A2AHeaders.X_A2A_NOTIFICATION_TOKEN;
66

77
import io.a2a.spec.TaskPushNotificationConfig;
8+
import jakarta.annotation.Nullable;
89
import jakarta.enterprise.context.ApplicationScoped;
910
import jakarta.inject.Inject;
1011

@@ -20,8 +21,12 @@
2021
import io.a2a.jsonrpc.common.json.JsonUtil;
2122
import io.a2a.spec.ListTaskPushNotificationConfigParams;
2223
import io.a2a.spec.ListTaskPushNotificationConfigResult;
24+
import io.a2a.spec.Message;
2325
import io.a2a.spec.PushNotificationConfig;
26+
import io.a2a.spec.StreamingEventKind;
2427
import io.a2a.spec.Task;
28+
import io.a2a.spec.TaskArtifactUpdateEvent;
29+
import io.a2a.spec.TaskStatusUpdateEvent;
2530
import org.slf4j.Logger;
2631
import org.slf4j.LoggerFactory;
2732

@@ -62,11 +67,17 @@ public BasePushNotificationSender(PushNotificationConfigStore configStore, A2AHt
6267
}
6368

6469
@Override
65-
public void sendNotification(Task task) {
70+
public void sendNotification(StreamingEventKind event) {
71+
String taskId = extractTaskId(event);
72+
if (taskId == null) {
73+
LOGGER.warn("Cannot send push notification: event does not contain taskId");
74+
return;
75+
}
76+
6677
List<TaskPushNotificationConfig> configs = new ArrayList<>();
6778
String nextPageToken = null;
6879
do {
69-
ListTaskPushNotificationConfigResult pageResult = configStore.getInfo(new ListTaskPushNotificationConfigParams(task.id(),
80+
ListTaskPushNotificationConfigResult pageResult = configStore.getInfo(new ListTaskPushNotificationConfigParams(taskId,
7081
DEFAULT_PAGE_SIZE, nextPageToken, ""));
7182
if (!pageResult.configs().isEmpty()) {
7283
configs.addAll(pageResult.configs());
@@ -76,26 +87,45 @@ public void sendNotification(Task task) {
7687

7788
List<CompletableFuture<Boolean>> dispatchResults = configs
7889
.stream()
79-
.map(pushConfig -> dispatch(task, pushConfig.pushNotificationConfig()))
90+
.map(pushConfig -> dispatch(event, pushConfig.pushNotificationConfig()))
8091
.toList();
8192
CompletableFuture<Void> allFutures = CompletableFuture.allOf(dispatchResults.toArray(new CompletableFuture[0]));
8293
CompletableFuture<Boolean> dispatchResult = allFutures.thenApply(v -> dispatchResults.stream()
8394
.allMatch(CompletableFuture::join));
8495
try {
8596
boolean allSent = dispatchResult.get();
8697
if (!allSent) {
87-
LOGGER.warn("Some push notifications failed to send for taskId: " + task.id());
98+
LOGGER.warn("Some push notifications failed to send for taskId: " + taskId);
8899
}
89100
} catch (InterruptedException | ExecutionException e) {
90-
LOGGER.warn("Some push notifications failed to send for taskId " + task.id() + ": {}", e.getMessage(), e);
101+
LOGGER.warn("Some push notifications failed to send for taskId " + taskId + ": {}", e.getMessage(), e);
102+
}
103+
}
104+
105+
/**
106+
* Extracts the task ID from a StreamingEventKind event.
107+
*
108+
* @param event the streaming event
109+
* @return the task ID, or null if not available
110+
*/
111+
private @Nullable String extractTaskId(StreamingEventKind event) {
112+
if (event instanceof Task task) {
113+
return task.id();
114+
} else if (event instanceof Message message) {
115+
return message.taskId();
116+
} else if (event instanceof TaskStatusUpdateEvent statusUpdate) {
117+
return statusUpdate.taskId();
118+
} else if (event instanceof TaskArtifactUpdateEvent artifactUpdate) {
119+
return artifactUpdate.taskId();
91120
}
121+
return null;
92122
}
93123

94-
private CompletableFuture<Boolean> dispatch(Task task, PushNotificationConfig pushInfo) {
95-
return CompletableFuture.supplyAsync(() -> dispatchNotification(task, pushInfo));
124+
private CompletableFuture<Boolean> dispatch(StreamingEventKind event, PushNotificationConfig pushInfo) {
125+
return CompletableFuture.supplyAsync(() -> dispatchNotification(event, pushInfo));
96126
}
97127

98-
private boolean dispatchNotification(Task task, PushNotificationConfig pushInfo) {
128+
private boolean dispatchNotification(StreamingEventKind event, PushNotificationConfig pushInfo) {
99129
String url = pushInfo.url();
100130
String token = pushInfo.token();
101131

@@ -106,9 +136,11 @@ private boolean dispatchNotification(Task task, PushNotificationConfig pushInfo)
106136

107137
String body;
108138
try {
109-
body = JsonUtil.toJson(task);
139+
// JsonUtil.toJson automatically wraps StreamingEventKind in StreamResponse format
140+
// (task/message/statusUpdate/artifactUpdate) per A2A spec section 4.3.3
141+
body = JsonUtil.toJson(event);
110142
} catch (Throwable throwable) {
111-
LOGGER.debug("Error writing value as string: {}", throwable.getMessage(), throwable);
143+
LOGGER.debug("Error serializing StreamingEventKind to JSON: {}", throwable.getMessage(), throwable);
112144
return false;
113145
}
114146

‎server-common/src/main/java/io/a2a/server/tasks/PushNotificationSender.java‎

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package io.a2a.server.tasks;
22

3+
import io.a2a.spec.StreamingEventKind;
34
import io.a2a.spec.Task;
45

56
/**
@@ -27,7 +28,8 @@
2728
* {@link BasePushNotificationSender} provides HTTP webhook delivery:
2829
* <ul>
2930
* <li>Retrieves webhook URLs from {@link PushNotificationConfigStore}</li>
30-
* <li>Sends HTTP POST requests with task JSON payload</li>
31+
* <li>Wraps events in StreamResponse format (per A2A spec section 4.3.3)</li>
32+
* <li>Sends HTTP POST requests with StreamResponse JSON payload</li>
3133
* <li>Logs errors but doesn't fail the request</li>
3234
* </ul>
3335
*
@@ -47,11 +49,12 @@
4749
* @Priority(100)
4850
* public class KafkaPushNotificationSender implements PushNotificationSender {
4951
* @Inject
50-
* KafkaProducer<String, Task> producer;
52+
* KafkaProducer<String, StreamingEventKind> producer;
5153
*
5254
* @Override
53-
* public void sendNotification(Task task) {
54-
* producer.send("task-updates", task.id(), task);
55+
* public void sendNotification(StreamingEventKind event) {
56+
* String taskId = extractTaskId(event);
57+
* producer.send("task-updates", taskId, event);
5558
* }
5659
* }
5760
* }</pre>
@@ -78,18 +81,31 @@
7881
public interface PushNotificationSender {
7982

8083
/**
81-
* Sends a push notification containing the latest task state.
84+
* Sends a push notification containing a streaming event.
8285
* <p>
83-
* Called after the task has been persisted to {@link TaskStore}. Retrieve push
84-
* notification URLs or messaging configurations from {@link PushNotificationConfigStore}
85-
* using {@code task.id()}.
86+
* Called after the event has been persisted to {@link TaskStore}. The event is wrapped
87+
* in a StreamResponse format (per A2A spec section 4.3.3) with the appropriate oneof
88+
* field set (task, message, statusUpdate, or artifactUpdate).
89+
* </p>
90+
* <p>
91+
* Retrieve push notification URLs or messaging configurations from
92+
* {@link PushNotificationConfigStore} using the task ID extracted from the event.
93+
* </p>
94+
* <p>
95+
* Supported event types:
96+
* <ul>
97+
* <li>{@link Task} - wrapped in StreamResponse.task</li>
98+
* <li>{@link io.a2a.spec.Message} - wrapped in StreamResponse.message</li>
99+
* <li>{@link io.a2a.spec.TaskStatusUpdateEvent} - wrapped in StreamResponse.statusUpdate</li>
100+
* <li>{@link io.a2a.spec.TaskArtifactUpdateEvent} - wrapped in StreamResponse.artifactUpdate</li>
101+
* </ul>
86102
* </p>
87103
* <p>
88104
* <b>Error Handling:</b> Log errors but don't throw exceptions. Notifications are
89105
* best-effort and should not fail the primary request.
90106
* </p>
91107
*
92-
* @param task the task with current state and artifacts to send
108+
* @param event the streaming event to send (Task, Message, TaskStatusUpdateEvent, or TaskArtifactUpdateEvent)
93109
*/
94-
void sendNotification(Task task);
110+
void sendNotification(StreamingEventKind event);
95111
}

‎server-common/src/test/java/io/a2a/server/requesthandlers/AbstractA2ARequestHandlerTest.java‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
import io.a2a.spec.AgentInterface;
4242
import io.a2a.spec.Event;
4343
import io.a2a.spec.Message;
44+
import io.a2a.spec.StreamingEventKind;
4445
import io.a2a.spec.Task;
4546
import io.a2a.spec.TaskState;
4647
import io.a2a.spec.TaskStatus;
@@ -189,7 +190,7 @@ public boolean isReplicated() {
189190
@Dependent
190191
@IfBuildProfile("test")
191192
protected static class TestHttpClient implements A2AHttpClient {
192-
public final List<Task> tasks = Collections.synchronizedList(new ArrayList<>());
193+
public final List<StreamingEventKind> events = Collections.synchronizedList(new ArrayList<>());
193194
public volatile CountDownLatch latch;
194195

195196
@Override
@@ -218,8 +219,10 @@ public PostBuilder body(String body) {
218219
@Override
219220
public A2AHttpResponse post() throws IOException, InterruptedException {
220221
try {
221-
Task task = JsonUtil.fromJson(body, Task.class);
222-
tasks.add(task);
222+
// Parse StreamResponse format to extract the streaming event
223+
// The body contains a wrapper with one of: task, message, statusUpdate, artifactUpdate
224+
StreamingEventKind event = JsonUtil.fromJson(body, StreamingEventKind.class);
225+
events.add(event);
223226
return new A2AHttpResponse() {
224227
@Override
225228
public int status() {
@@ -237,7 +240,7 @@ public String body() {
237240
}
238241
};
239242
} catch (JsonProcessingException e) {
240-
throw new IOException("Failed to parse task JSON", e);
243+
throw new IOException("Failed to parse StreamingEventKind JSON", e);
241244
} finally {
242245
if (latch != null) {
243246
latch.countDown();

0 commit comments

Comments
 (0)