Skip to content

Commit dbe8f25

Browse files
authored
fix: defer CDI request context destruction for streaming requests (a2aproject#904)
* fix: defer CDI request context destruction for streaming requests Streaming (SSE) requests dispatch agent work to a background thread via ManagedExecutor and return immediately. The existing runInRequestContext() terminates the CDI request context in a finally block, destroying all @RequestScoped beans before the agent thread runs. This causes ContextNotActiveException when the agent accesses request-scoped beans (e.g. OIDC token propagation via @accesstoken). Add runInRequestContextDeferred() which deactivates the context (detaching it from the worker thread) but defers bean destruction to the HTTP response lifecycle via endHandler/closeHandler. This keeps all @RequestScoped beans alive for the duration of the streaming response. - JSONRPC routes: use runInRequestContextDeferred for the main handler (handles both streaming and non-streaming) - REST routes: add authenticatedStreaming() wrapper for message:stream and tasks/:subscribe endpoints - Apply same changes to compat-0.3 JSONRPC and REST routes - Add streaming variant of CDI propagation test
1 parent c1257e7 commit dbe8f25

6 files changed

Lines changed: 157 additions & 9 deletions

File tree

‎compat-0.3/reference/jsonrpc/src/main/java/org/a2aproject/sdk/compat03/server/apps/quarkus/A2AServerRoutes_v0_3.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ void setupRoutes(@Observes Router router) {
9696
.handler(BodyHandler.create())
9797
.blockingHandler(ctx -> {
9898
try {
99-
vertxSecurityHelper.runInRequestContext(ctx, () -> {
99+
vertxSecurityHelper.runInRequestContextDeferred(ctx, () -> {
100100
invokeJSONRPCHandler(ctx.body().asString(), ctx);
101101
});
102102
} catch (UnauthorizedException | ForbiddenException e) {

‎compat-0.3/reference/rest/src/main/java/org/a2aproject/sdk/compat03/server/rest/quarkus/A2AServerRoutes_v0_3.java‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ void setupRouter(@Observes @Priority(10) Router router) {
8787
// POST /v1/message:stream
8888
router.postWithRegex("^\\/v1\\/message:stream$")
8989
.handler(BodyHandler.create())
90-
.blockingHandler(authenticated(ctx -> {
90+
.blockingHandler(authenticatedStreaming(ctx -> {
9191
sendMessageStreaming(extractBody(ctx), ctx);
9292
}));
9393

@@ -104,7 +104,7 @@ void setupRouter(@Observes @Priority(10) Router router) {
104104
// POST /v1/tasks/{id}:subscribe
105105
router.postWithRegex("^\\/v1\\/tasks\\/([^/]+):subscribe$")
106106
.order(1)
107-
.blockingHandler(authenticated(this::resubscribeTask));
107+
.blockingHandler(authenticatedStreaming(this::resubscribeTask));
108108

109109
// POST /v1/tasks/:id/pushNotificationConfigs
110110
router.post("/v1/tasks/:id/pushNotificationConfigs")
@@ -158,6 +158,18 @@ private Handler<RoutingContext> authenticated(Consumer<RoutingContext> action) {
158158
};
159159
}
160160

161+
private Handler<RoutingContext> authenticatedStreaming(Consumer<RoutingContext> action) {
162+
return ctx -> {
163+
try {
164+
vertxSecurityHelper.runInRequestContextDeferred(ctx, () -> action.accept(ctx));
165+
} catch (UnauthorizedException | ForbiddenException e) {
166+
vertxSecurityHelper.handleAuthError(ctx, e);
167+
} catch (Exception e) {
168+
VertxSecurityHelper.handleGenericError(ctx);
169+
}
170+
};
171+
}
172+
161173
@Authenticated
162174
public void sendMessage(String body, RoutingContext rc) {
163175
ServerCallContext context = createCallContext(rc, SendMessageRequest_v0_3.METHOD);

‎reference/common/src/main/java/org/a2aproject/sdk/server/common/quarkus/VertxSecurityHelper.java‎

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
package org.a2aproject.sdk.server.common.quarkus;
22

3+
import java.util.Map;
4+
import java.util.concurrent.atomic.AtomicBoolean;
5+
36
import jakarta.enterprise.inject.Instance;
47
import jakarta.inject.Inject;
58
import jakarta.inject.Singleton;
69

710
import io.quarkus.arc.Arc;
11+
import io.quarkus.arc.InjectableContext;
812
import io.quarkus.arc.ManagedContext;
913
import io.quarkus.security.identity.CurrentIdentityAssociation;
1014
import io.quarkus.vertx.http.runtime.security.ChallengeData;
1115
import io.quarkus.vertx.http.runtime.security.HttpAuthenticator;
1216
import io.vertx.core.Context;
1317
import io.vertx.ext.web.RoutingContext;
14-
import java.util.Map;
1518

1619
/**
1720
* CDI helper for integrating Quarkus security with Vert.x Web routes.
@@ -122,6 +125,81 @@ public void runInRequestContext(RoutingContext ctx, Runnable task) {
122125
}
123126
}
124127

128+
/**
129+
* Authenticates the request and executes a task, deferring CDI context destruction to the HTTP
130+
* response lifecycle.
131+
*
132+
* <p>Unlike {@link #runInRequestContext}, this method does <b>not</b> terminate the CDI request
133+
* context when the task completes. Instead, it:
134+
* <ol>
135+
* <li>Activates the CDI request context and captures its {@link InjectableContext.ContextState}</li>
136+
* <li>Triggers HTTP authentication</li>
137+
* <li>Executes the task</li>
138+
* <li><b>Deactivates</b> the context (detaches from the worker thread without destroying beans)</li>
139+
* <li>Destroys the context state when the HTTP response ends or the connection closes</li>
140+
* </ol>
141+
*
142+
* <p>This is required for streaming (SSE) requests where the task dispatches work to a background
143+
* thread (via {@code CompletableFuture.runAsync} with a {@code ManagedExecutor}) and returns
144+
* immediately. The {@code ManagedExecutor} captures the CDI context at submit time and propagates
145+
* it to the agent thread — but only if the context hasn't been destroyed yet. By deferring
146+
* destruction to the response lifecycle, the agent thread can access all {@code @RequestScoped}
147+
* beans (including OIDC token credentials for token propagation).
148+
*
149+
* <p>This method is also safe for non-streaming requests: {@code response.end()} is called
150+
* synchronously inside the task, and the {@code endHandler} fires the cleanup shortly after.
151+
*
152+
* @param ctx the Vert.x routing context containing the HTTP request
153+
* @param task the code to execute within the authenticated request context
154+
* @throws io.quarkus.security.UnauthorizedException if authentication fails
155+
* @throws io.quarkus.security.ForbiddenException if authorization fails
156+
* @throws RuntimeException if the task throws an exception
157+
*/
158+
public void runInRequestContextDeferred(RoutingContext ctx, Runnable task) {
159+
if (Context.isOnEventLoopThread()) {
160+
throw new IllegalStateException(
161+
"Cannot perform blocking authentication on event loop thread. Use blockingHandler().");
162+
}
163+
ManagedContext requestContext = Arc.container().requestContext();
164+
boolean wasActive = requestContext.isActive();
165+
if (wasActive) {
166+
if (!httpAuthenticator.isUnsatisfied()) {
167+
var identity = httpAuthenticator.get().attemptAuthentication(ctx).await().indefinitely();
168+
currentIdentityAssociation.get().setIdentity(identity);
169+
}
170+
task.run();
171+
return;
172+
}
173+
174+
InjectableContext.ContextState state = requestContext.activate();
175+
176+
AtomicBoolean destroyed = new AtomicBoolean(false);
177+
Runnable cleanup = () -> {
178+
if (destroyed.compareAndSet(false, true)) {
179+
requestContext.destroy(state);
180+
}
181+
};
182+
183+
ctx.response().endHandler(v -> cleanup.run());
184+
ctx.response().closeHandler(v -> cleanup.run());
185+
186+
try {
187+
if (!httpAuthenticator.isUnsatisfied()) {
188+
var identity = httpAuthenticator.get().attemptAuthentication(ctx).await().indefinitely();
189+
currentIdentityAssociation.get().setIdentity(identity);
190+
}
191+
task.run();
192+
} catch (Throwable t) {
193+
// Destroy bean instances immediately on error. The subsequent deactivate() in the
194+
// finally block is still needed to detach the (now-empty) context from the worker
195+
// thread. destroy(state) only destroys beans — it does not deactivate the context.
196+
cleanup.run();
197+
throw t;
198+
} finally {
199+
requestContext.deactivate();
200+
}
201+
}
202+
125203
/**
126204
* Handles authentication or authorization errors by sending the appropriate HTTP error response.
127205
*

‎reference/jsonrpc/src/main/java/org/a2aproject/sdk/server/apps/quarkus/A2AServerRoutes.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ void setupRoutes(@Observes Router router) {
212212
.handler(BodyHandler.create())
213213
.blockingHandler(ctx -> {
214214
try {
215-
vertxSecurityHelper.runInRequestContext(ctx, () -> {
215+
vertxSecurityHelper.runInRequestContextDeferred(ctx, () -> {
216216
invokeJSONRPCHandler(ctx.body().asString(), ctx);
217217
});
218218
} catch (UnauthorizedException | ForbiddenException e) {

‎reference/rest/src/main/java/org/a2aproject/sdk/server/rest/quarkus/A2AServerRoutes.java‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ void setupRouter(@Observes @Priority(10) Router router) {
180180
// POST /{tenant}/message:stream - Streaming message with SSE
181181
router.postWithRegex("^\\/(?<tenant>[^\\/]*\\/?)message:stream$")
182182
.handler(BodyHandler.create())
183-
.blockingHandler(authenticated(ctx -> {
183+
.blockingHandler(authenticatedStreaming(ctx -> {
184184
String body = extractBody(ctx);
185185
sendMessageStreaming(body, ctx);
186186
}), false);
@@ -209,7 +209,7 @@ void setupRouter(@Observes @Priority(10) Router router) {
209209
// POST /{tenant}/tasks/{taskId}:subscribe - Subscribe to task updates (SSE)
210210
router.postWithRegex("^\\/(?<tenant>[^\\/]*\\/?)tasks\\/(?<taskId>[^/]+):subscribe$")
211211
.order(1)
212-
.blockingHandler(authenticated(this::subscribeToTask), false);
212+
.blockingHandler(authenticatedStreaming(this::subscribeToTask), false);
213213

214214
// Push Notification Routes
215215

@@ -264,6 +264,18 @@ private Handler<RoutingContext> authenticated(Consumer<RoutingContext> action) {
264264
};
265265
}
266266

267+
private Handler<RoutingContext> authenticatedStreaming(Consumer<RoutingContext> action) {
268+
return ctx -> {
269+
try {
270+
vertxSecurityHelper.runInRequestContextDeferred(ctx, () -> action.accept(ctx));
271+
} catch (UnauthorizedException | ForbiddenException e) {
272+
vertxSecurityHelper.handleAuthError(ctx, e);
273+
} catch (Exception e) {
274+
VertxSecurityHelper.handleGenericError(ctx);
275+
}
276+
};
277+
}
278+
267279
/**
268280
* Handles blocking message send requests.
269281
*

‎tests/server-common/src/test/java/org/a2aproject/sdk/server/apps/common/AbstractA2AServerTest.java‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -547,6 +547,51 @@ public void testRequestScopedBeanAvailableOnAgentExecutorThread() throws Excepti
547547
assertEquals("request-scoped:request-scoped-value", ((TextPart) part).text());
548548
}
549549

550+
@Test
551+
public void testRequestScopedBeanAvailableOnAgentExecutorThreadStreaming() throws Exception {
552+
Message message = Message.builder()
553+
.messageId("request-scoped-streaming-test")
554+
.role(Message.Role.ROLE_USER)
555+
.parts(new TextPart("request-scoped:test"))
556+
.build();
557+
558+
CountDownLatch latch = new CountDownLatch(1);
559+
AtomicReference<Task> receivedTask = new AtomicReference<>();
560+
AtomicReference<Throwable> errorRef = new AtomicReference<>();
561+
562+
getClient().sendMessage(message, List.of((event, agentCard) -> {
563+
if (event instanceof TaskEvent te) {
564+
receivedTask.set(te.getTask());
565+
if (te.getTask().status().state() == TaskState.TASK_STATE_COMPLETED) {
566+
latch.countDown();
567+
}
568+
} else if (event instanceof TaskUpdateEvent tue) {
569+
receivedTask.set(tue.getTask());
570+
if (tue.getTask().status().state() == TaskState.TASK_STATE_COMPLETED) {
571+
latch.countDown();
572+
}
573+
}
574+
}), error -> {
575+
if (!isStreamClosedError(error)) {
576+
errorRef.set(error);
577+
}
578+
latch.countDown();
579+
});
580+
581+
assertTrue(latch.await(10, TimeUnit.SECONDS), "Request should complete within timeout");
582+
assertNull(errorRef.get(), "Should not have received an error");
583+
584+
Task task = receivedTask.get();
585+
assertNotNull(task, "Should have received a task");
586+
assertEquals(TaskState.TASK_STATE_COMPLETED, task.status().state());
587+
assertNotNull(task.artifacts());
588+
assertFalse(task.artifacts().isEmpty());
589+
590+
Part<?> part = task.artifacts().get(0).parts().get(0);
591+
assertInstanceOf(TextPart.class, part);
592+
assertEquals("request-scoped:request-scoped-value", ((TextPart) part).text());
593+
}
594+
550595
@Test
551596
public void testSendMessageExistingTaskSuccess() throws Exception {
552597
saveTaskInTaskStore(MINIMAL_TASK);
@@ -2429,16 +2474,17 @@ private static String extractSseData(String line) {
24292474
}
24302475

24312476
protected boolean isStreamClosedError(Throwable throwable) {
2432-
// Unwrap the CompletionException
24332477
Throwable cause = throwable;
24342478

24352479
while (cause != null) {
24362480
if (cause instanceof EOFException) {
24372481
return true;
24382482
}
2483+
if (cause instanceof java.util.concurrent.CancellationException) {
2484+
return true;
2485+
}
24392486
if (cause instanceof IOException && cause.getMessage() != null
24402487
&& cause.getMessage().contains("cancelled")) {
2441-
// stream is closed upon cancellation
24422488
return true;
24432489
}
24442490
cause = cause.getCause();

0 commit comments

Comments
 (0)