Repository navigation
Expand file tree
/
Copy pathDefaultRequestHandlerTest.java
More file actions
512 lines (429 loc) · 20.2 KB
/
Copy pathDefaultRequestHandlerTest.java
File metadata and controls
512 lines (429 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
package io.a2a.server.requesthandlers;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import io.a2a.server.ServerCallContext;
import io.a2a.server.agentexecution.AgentExecutor;
import io.a2a.server.agentexecution.RequestContext;
import io.a2a.server.events.EventQueue;
import io.a2a.server.events.EventQueueItem;
import io.a2a.server.events.EventQueueUtil;
import io.a2a.server.events.InMemoryQueueManager;
import io.a2a.server.events.MainEventBus;
import io.a2a.server.events.MainEventBusProcessor;
import io.a2a.server.tasks.AgentEmitter;
import io.a2a.server.tasks.InMemoryPushNotificationConfigStore;
import io.a2a.server.tasks.InMemoryTaskStore;
import io.a2a.server.tasks.PushNotificationConfigStore;
import io.a2a.server.tasks.PushNotificationSender;
import io.a2a.server.tasks.TaskStore;
import io.a2a.spec.A2AError;
import io.a2a.spec.Event;
import io.a2a.spec.EventKind;
import io.a2a.spec.Message;
import io.a2a.spec.MessageSendConfiguration;
import io.a2a.spec.MessageSendParams;
import io.a2a.spec.Task;
import io.a2a.spec.TaskArtifactUpdateEvent;
import io.a2a.spec.TaskState;
import io.a2a.spec.TaskStatus;
import io.a2a.spec.TaskStatusUpdateEvent;
import io.a2a.spec.TextPart;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Integration tests for DefaultRequestHandler focusing on AUTH_REQUIRED workflow.
* Tests verify the special interrupt behavior where AUTH_REQUIRED tasks:
* 1. Return immediately to the client
* 2. Continue agent execution in background
* 3. Keep queues open for late events
* 4. Perform async cleanup
*/
public class DefaultRequestHandlerTest {
private static final MessageSendConfiguration DEFAULT_CONFIG = MessageSendConfiguration.builder()
.returnImmediately(true)
.acceptedOutputModes(List.of())
.build();
private static final ServerCallContext NULL_CONTEXT = null;
private static final Message MESSAGE = Message.builder()
.messageId("111")
.role(Message.Role.ROLE_AGENT)
.parts(new TextPart("test message"))
.build();
private static final PushNotificationSender NOOP_PUSHNOTIFICATION_SENDER = task -> {};
// Test infrastructure components
protected AgentExecutor executor;
protected TaskStore taskStore;
protected RequestHandler requestHandler;
protected InMemoryQueueManager queueManager;
protected MainEventBus mainEventBus;
protected MainEventBusProcessor mainEventBusProcessor;
protected AgentExecutorMethod agentExecutorExecute;
protected AgentExecutorMethod agentExecutorCancel;
protected final Executor internalExecutor = Executors.newCachedThreadPool();
@BeforeEach
public void init() {
// Create test AgentExecutor with mocked execute/cancel methods
executor = new AgentExecutor() {
@Override
public void execute(RequestContext context, AgentEmitter agentEmitter) throws A2AError {
if (agentExecutorExecute != null) {
agentExecutorExecute.invoke(context, agentEmitter);
}
}
@Override
public void cancel(RequestContext context, AgentEmitter agentEmitter) throws A2AError {
if (agentExecutorCancel != null) {
agentExecutorCancel.invoke(context, agentEmitter);
}
}
};
// Set up infrastructure
InMemoryTaskStore inMemoryTaskStore = new InMemoryTaskStore();
taskStore = inMemoryTaskStore;
PushNotificationConfigStore pushConfigStore = new InMemoryPushNotificationConfigStore();
// Create MainEventBus and MainEventBusProcessor
mainEventBus = new MainEventBus();
queueManager = new InMemoryQueueManager(inMemoryTaskStore, mainEventBus);
mainEventBusProcessor = new MainEventBusProcessor(mainEventBus, taskStore, NOOP_PUSHNOTIFICATION_SENDER, queueManager);
EventQueueUtil.start(mainEventBusProcessor);
// Create DefaultRequestHandler
requestHandler = DefaultRequestHandler.create(
executor, taskStore, queueManager, pushConfigStore, mainEventBusProcessor, internalExecutor, internalExecutor);
}
@AfterEach
public void cleanup() {
agentExecutorExecute = null;
agentExecutorCancel = null;
// Stop MainEventBusProcessor background thread
if (mainEventBusProcessor != null) {
EventQueueUtil.stop(mainEventBusProcessor);
}
}
/**
* Functional interface for test agent executor methods.
*/
protected interface AgentExecutorMethod {
void invoke(RequestContext context, AgentEmitter agentEmitter) throws A2AError;
}
/**
* Test 1: Non-streaming AUTH_REQUIRED returns immediately while agent continues.
* Verifies:
* - Task returned immediately with AUTH_REQUIRED state
* - Agent still running in background (not blocked)
* - TaskStore persisted AUTH_REQUIRED state
* - Agent completes after release
* - Final state persisted to TaskStore
*/
@Test
void testAuthRequired_NonStreaming_ReturnsImmediately() throws Exception {
// Arrange: Set up agent that emits AUTH_REQUIRED then waits
CountDownLatch authRequiredEmitted = new CountDownLatch(1);
CountDownLatch continueAgent = new CountDownLatch(1);
agentExecutorExecute = (context, emitter) -> {
// Emit AUTH_REQUIRED - client should receive immediately
emitter.requiresAuth(Message.builder()
.role(Message.Role.ROLE_AGENT)
.parts(new TextPart("Please authenticate with OAuth provider"))
.build());
authRequiredEmitted.countDown();
// Agent continues processing (simulating waiting for out-of-band auth)
try {
continueAgent.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Complete after "auth received"
emitter.complete();
};
// Create MessageSendParams
MessageSendParams params = MessageSendParams.builder()
.message(MESSAGE)
.configuration(DEFAULT_CONFIG)
.build();
// Act: Send message (non-streaming)
EventKind eventKind = requestHandler.onMessageSend(params, NULL_CONTEXT);
// Assert: Task returned immediately with AUTH_REQUIRED state
assertNotNull(eventKind, "Result should not be null");
assertInstanceOf(Task.class, eventKind, "Result should be a Task");
Task result = (Task) eventKind;
assertEquals(TaskState.TASK_STATE_AUTH_REQUIRED, result.status().state(),
"Task should be in AUTH_REQUIRED state");
assertTrue(authRequiredEmitted.await(2, TimeUnit.SECONDS),
"AUTH_REQUIRED should be emitted quickly");
// Verify agent still running (continueAgent latch not counted down yet)
assertFalse(continueAgent.await(100, TimeUnit.MILLISECONDS),
"Agent should still be waiting (not completed yet)");
// Verify TaskStore has AUTH_REQUIRED state
Task storedTask = taskStore.get(result.id());
assertNotNull(storedTask, "Task should be persisted in TaskStore");
assertEquals(TaskState.TASK_STATE_AUTH_REQUIRED, storedTask.status().state(),
"TaskStore should have AUTH_REQUIRED state");
// Release agent to complete
continueAgent.countDown();
// Wait for completion and verify final state
Thread.sleep(1000); // Allow time for completion to process through MainEventBus
Task finalTask = taskStore.get(result.id());
assertEquals(TaskState.TASK_STATE_COMPLETED, finalTask.status().state(),
"TaskStore should have COMPLETED state after agent finishes");
}
/**
* Test 2: Queue remains open after AUTH_REQUIRED for late events.
* Verifies:
* - Queue stays open after AUTH_REQUIRED response
* - Can tap into queue after AUTH_REQUIRED
* - Late artifacts arrive on tapped queue
* - Completion event arrives on tapped queue
*/
@Test
void testAuthRequired_QueueRemainsOpen() throws Exception {
// Arrange: Agent emits AUTH_REQUIRED then continues with late events
CountDownLatch authEmitted = new CountDownLatch(1);
CountDownLatch continueAgent = new CountDownLatch(1);
agentExecutorExecute = (context, emitter) -> {
// Emit AUTH_REQUIRED
emitter.requiresAuth(Message.builder()
.role(Message.Role.ROLE_AGENT)
.parts(new TextPart("Authenticate required"))
.build());
authEmitted.countDown();
// Wait for test to tap queue
try {
continueAgent.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Emit late artifact after AUTH_REQUIRED
emitter.addArtifact(List.of(new TextPart("Late artifact after auth")));
emitter.complete();
};
// Create MessageSendParams
MessageSendParams params = MessageSendParams.builder()
.message(MESSAGE)
.configuration(DEFAULT_CONFIG)
.build();
// Act: Send message, get AUTH_REQUIRED response
EventKind eventKind = requestHandler.onMessageSend(params, NULL_CONTEXT);
assertInstanceOf(Task.class, eventKind);
Task task = (Task) eventKind;
assertTrue(authEmitted.await(2, TimeUnit.SECONDS),
"AUTH_REQUIRED should be emitted");
// Tap into the queue (simulates client resubscription after AUTH_REQUIRED)
EventQueue tappedQueue = queueManager.tap(task.id());
assertNotNull(tappedQueue, "Queue should remain open after AUTH_REQUIRED");
// Release agent to continue and emit late events
continueAgent.countDown();
// Assert: Late events arrive on tapped queue
// First event should be the late artifact
EventQueueItem item = tappedQueue.dequeueEventItem(5000);
assertNotNull(item, "Should receive late artifact event");
Event event = item.getEvent();
assertInstanceOf(TaskArtifactUpdateEvent.class, event,
"First event should be TaskArtifactUpdateEvent");
// Second event should be completion
item = tappedQueue.dequeueEventItem(5000);
assertNotNull(item, "Should receive completion event");
event = item.getEvent();
assertInstanceOf(TaskStatusUpdateEvent.class, event,
"Second event should be TaskStatusUpdateEvent");
assertEquals(TaskState.TASK_STATE_COMPLETED,
((TaskStatusUpdateEvent) event).status().state(),
"Task should be completed");
}
/**
* Test 3: TaskStore persistence through AUTH_REQUIRED lifecycle.
* Verifies:
* - AUTH_REQUIRED state persisted correctly
* - State transitions persisted (AUTH_REQUIRED → WORKING → COMPLETED)
* - TaskStore always reflects current state
*/
@Test
void testAuthRequired_TaskStorePersistence() throws Exception {
// Arrange: Agent emits AUTH_REQUIRED, then WORKING, then COMPLETED
CountDownLatch authEmitted = new CountDownLatch(1);
CountDownLatch continueAgent = new CountDownLatch(1);
agentExecutorExecute = (context, emitter) -> {
// Emit AUTH_REQUIRED
emitter.requiresAuth();
authEmitted.countDown();
// Wait for test to verify AUTH_REQUIRED persisted
try {
continueAgent.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Continue working (simulating auth received out-of-band)
emitter.startWork();
// Complete the task
emitter.complete();
};
// Create MessageSendParams
MessageSendParams params = MessageSendParams.builder()
.message(MESSAGE)
.configuration(DEFAULT_CONFIG)
.build();
// Act: Send message
EventKind eventKind = requestHandler.onMessageSend(params, NULL_CONTEXT);
assertInstanceOf(Task.class, eventKind);
Task task = (Task) eventKind;
assertTrue(authEmitted.await(2, TimeUnit.SECONDS),
"AUTH_REQUIRED should be emitted");
// Assert: Verify AUTH_REQUIRED state persisted
Task storedTask1 = taskStore.get(task.id());
assertNotNull(storedTask1, "Task should be in TaskStore");
assertEquals(TaskState.TASK_STATE_AUTH_REQUIRED, storedTask1.status().state(),
"TaskStore should have AUTH_REQUIRED state");
// Release agent to continue
continueAgent.countDown();
// Wait for state transitions to process
Thread.sleep(1000);
// Verify WORKING state persisted
Task storedTask2 = taskStore.get(task.id());
// Note: WORKING might be skipped if processing is fast, so we accept either WORKING or COMPLETED
TaskState state2 = storedTask2.status().state();
assertTrue(state2 == TaskState.TASK_STATE_WORKING || state2 == TaskState.TASK_STATE_COMPLETED,
"TaskStore should have WORKING or COMPLETED state");
// Wait a bit more and verify final COMPLETED state
Thread.sleep(500);
Task storedTask3 = taskStore.get(task.id());
assertEquals(TaskState.TASK_STATE_COMPLETED, storedTask3.status().state(),
"TaskStore should have COMPLETED state after agent finishes");
}
/**
* Test 4: Streaming with AUTH_REQUIRED continues in background.
* Verifies:
* - Client receives AUTH_REQUIRED in stream
* - Agent continues emitting artifacts after AUTH_REQUIRED
* - Artifacts stream to client
* - Completion event arrives in stream
*/
@Test
void testAuthRequired_Streaming_ContinuesInBackground() throws Exception {
// Arrange: Agent emits AUTH_REQUIRED, then streams artifacts
CountDownLatch authEmitted = new CountDownLatch(1);
CountDownLatch continueAgent = new CountDownLatch(1);
agentExecutorExecute = (context, emitter) -> {
// Emit AUTH_REQUIRED
emitter.requiresAuth();
authEmitted.countDown();
// Wait briefly (simulating auth happening out-of-band)
try {
continueAgent.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Continue streaming artifacts
emitter.addArtifact(List.of(new TextPart("Artifact 1")));
emitter.addArtifact(List.of(new TextPart("Artifact 2")));
emitter.complete();
};
// Create MessageSendParams
MessageSendParams params = MessageSendParams.builder()
.message(MESSAGE)
.configuration(DEFAULT_CONFIG)
.build();
// Act: Send message with streaming enabled
EventKind eventKind = requestHandler.onMessageSend(params, NULL_CONTEXT);
assertInstanceOf(Task.class, eventKind);
Task result = (Task) eventKind;
assertTrue(authEmitted.await(2, TimeUnit.SECONDS),
"AUTH_REQUIRED should be emitted");
// Verify AUTH_REQUIRED received
assertEquals(TaskState.TASK_STATE_AUTH_REQUIRED, result.status().state(),
"Should receive AUTH_REQUIRED state");
// Tap queue to receive subsequent events
EventQueue tappedQueue = queueManager.tap(result.id());
// Release agent to continue streaming
continueAgent.countDown();
// Assert: Verify artifacts stream through
EventQueueItem item1 = tappedQueue.dequeueEventItem(5000);
assertNotNull(item1, "Should receive first artifact");
assertInstanceOf(TaskArtifactUpdateEvent.class, item1.getEvent());
EventQueueItem item2 = tappedQueue.dequeueEventItem(5000);
assertNotNull(item2, "Should receive second artifact");
assertInstanceOf(TaskArtifactUpdateEvent.class, item2.getEvent());
// Verify completion arrives
EventQueueItem completionItem = tappedQueue.dequeueEventItem(5000);
assertNotNull(completionItem, "Should receive completion");
Event completionEvent = completionItem.getEvent();
assertInstanceOf(TaskStatusUpdateEvent.class, completionEvent);
assertEquals(TaskState.TASK_STATE_COMPLETED,
((TaskStatusUpdateEvent) completionEvent).status().state());
}
/**
* Test 5: Resubscription after AUTH_REQUIRED works correctly.
* Verifies:
* - Queue stays open after AUTH_REQUIRED and client disconnect
* - Can resubscribe (tap) after AUTH_REQUIRED
* - Late events received on resubscribed queue
* - Completion event arrives on resubscribed queue
*/
@Test
void testAuthRequired_Resubscription() throws Exception {
// Arrange: Agent emits AUTH_REQUIRED, simulates client disconnect, then continues
CountDownLatch authEmitted = new CountDownLatch(1);
CountDownLatch continueAgent = new CountDownLatch(1);
agentExecutorExecute = (context, emitter) -> {
// Emit AUTH_REQUIRED
emitter.requiresAuth();
authEmitted.countDown();
// Wait for test to simulate disconnect and resubscribe
try {
continueAgent.await(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
// Emit late events after "client reconnect"
emitter.addArtifact(List.of(new TextPart("Event after reconnect")));
emitter.complete();
};
// Create MessageSendParams
MessageSendParams params = MessageSendParams.builder()
.message(MESSAGE)
.configuration(DEFAULT_CONFIG)
.build();
// Act: Send message, get AUTH_REQUIRED
EventKind eventKind = requestHandler.onMessageSend(params, NULL_CONTEXT);
assertInstanceOf(Task.class, eventKind);
Task task = (Task) eventKind;
assertTrue(authEmitted.await(2, TimeUnit.SECONDS),
"AUTH_REQUIRED should be emitted");
assertEquals(TaskState.TASK_STATE_AUTH_REQUIRED, task.status().state(),
"Should receive AUTH_REQUIRED state");
// Simulate client disconnect by just waiting
Thread.sleep(100);
// Client reconnects: tap into queue (resubscription)
EventQueue resubscribedQueue = queueManager.tap(task.id());
assertNotNull(resubscribedQueue,
"Should be able to resubscribe after AUTH_REQUIRED");
// Release agent to continue
continueAgent.countDown();
// Assert: Late events arrive on resubscribed queue
EventQueueItem item = resubscribedQueue.dequeueEventItem(5000);
assertNotNull(item, "Should receive late artifact on resubscribed queue");
assertInstanceOf(TaskArtifactUpdateEvent.class, item.getEvent(),
"Should receive artifact update event");
// Verify completion arrives
EventQueueItem completionItem = resubscribedQueue.dequeueEventItem(5000);
assertNotNull(completionItem, "Should receive completion event");
Event completionEvent = completionItem.getEvent();
assertInstanceOf(TaskStatusUpdateEvent.class, completionEvent,
"Should receive status update event");
assertEquals(TaskState.TASK_STATE_COMPLETED,
((TaskStatusUpdateEvent) completionEvent).status().state(),
"Task should be completed");
}
}