Skip to content

Commit eaa6511

Browse files
kabirclaude
andauthored
fix: defer AgentCard resolution to prevent eager startup failures (a2aproject#1058)
* fix: defer AgentCard resolution to prevent eager startup failures (a2aproject#1033) All three handler implementations (gRPC, JSON-RPC, REST) now store Instance<AgentCard> and resolve lazily on first access instead of eagerly in the constructor. This prevents startup failures when the AgentCard producer depends on the HTTP server's bound address, which is not yet available at RUNTIME_INIT. This fixes a2aproject#1033 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> Signed-off-by: Kabir Khan <kkhan@redhat.com>
1 parent 8615f37 commit eaa6511

12 files changed

Lines changed: 411 additions & 84 deletions

File tree

‎reference/grpc/pom.xml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@
3636
<artifactId>a2a-java-sdk-jsonrpc-common</artifactId>
3737
<version>${project.version}</version>
3838
</dependency>
39+
<dependency>
40+
<groupId>${project.groupId}</groupId>
41+
<artifactId>a2a-java-sdk-server-common</artifactId>
42+
<type>test-jar</type>
43+
<scope>test</scope>
44+
</dependency>
3945
<dependency>
4046
<groupId>${project.groupId}</groupId>
4147
<artifactId>a2a-java-sdk-tests-server-common</artifactId>

‎reference/grpc/src/main/java/org/a2aproject/sdk/server/grpc/quarkus/QuarkusGrpcHandler.java‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,8 @@
7474
@Blocking
7575
public class QuarkusGrpcHandler extends GrpcHandler {
7676

77-
private final AgentCard agentCard;
78-
private final AgentCard extendedAgentCard;
77+
private final Instance<AgentCard> agentCard;
78+
private final @Nullable Instance<AgentCard> extendedAgentCard;
7979
private final RequestHandler requestHandler;
8080
private final Instance<CallContextFactory> callContextFactoryInstance;
8181
private final Executor executor;
@@ -106,17 +106,13 @@ public class QuarkusGrpcHandler extends GrpcHandler {
106106
* @param executor the executor for async operations (qualified with {@code @Internal})
107107
*/
108108
@Inject
109-
public QuarkusGrpcHandler(@PublicAgentCard AgentCard agentCard,
109+
public QuarkusGrpcHandler(@PublicAgentCard Instance<AgentCard> agentCard,
110110
@ExtendedAgentCard Instance<AgentCard> extendedAgentCard,
111111
RequestHandler requestHandler,
112112
Instance<CallContextFactory> callContextFactoryInstance,
113113
@Internal Executor executor) {
114114
this.agentCard = agentCard;
115-
if (extendedAgentCard != null && extendedAgentCard.isResolvable()) {
116-
this.extendedAgentCard = extendedAgentCard.get();
117-
} else {
118-
this.extendedAgentCard = null;
119-
}
115+
this.extendedAgentCard = extendedAgentCard;
120116
this.requestHandler = requestHandler;
121117
this.callContextFactoryInstance = callContextFactoryInstance;
122118
this.executor = executor;
@@ -129,12 +125,15 @@ protected RequestHandler getRequestHandler() {
129125

130126
@Override
131127
protected AgentCard getAgentCard() {
132-
return agentCard;
128+
return agentCard.get();
133129
}
134130

135131
@Override
136132
protected AgentCard getExtendedAgentCard() {
137-
return extendedAgentCard;
133+
if (extendedAgentCard != null && extendedAgentCard.isResolvable()) {
134+
return extendedAgentCard.get();
135+
}
136+
return null;
138137
}
139138

140139
@Override
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package org.a2aproject.sdk.server.grpc.quarkus;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.concurrent.atomic.AtomicBoolean;
6+
7+
import jakarta.enterprise.inject.Instance;
8+
9+
import org.a2aproject.sdk.server.FixedInstance;
10+
import org.a2aproject.sdk.server.TestInstances;
11+
import org.a2aproject.sdk.spec.AgentCapabilities;
12+
import org.a2aproject.sdk.spec.AgentCard;
13+
import org.a2aproject.sdk.spec.AgentInterface;
14+
import org.a2aproject.sdk.transport.grpc.handler.CallContextFactory;
15+
import org.junit.jupiter.api.Test;
16+
17+
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
18+
import static org.junit.jupiter.api.Assertions.assertEquals;
19+
import static org.junit.jupiter.api.Assertions.assertFalse;
20+
import static org.junit.jupiter.api.Assertions.assertTrue;
21+
22+
/**
23+
* Verifies that {@link QuarkusGrpcHandler} does not eagerly resolve {@link Instance} parameters
24+
* during construction. This guards against the regression described in
25+
* <a href="https://github.com/a2aproject/a2a-java/issues/1033">issue #1033</a>, where eager
26+
* resolution prevented startup when the AgentCard producer depended on the HTTP server address.
27+
*/
28+
class QuarkusGrpcHandlerLazyResolutionTest {
29+
30+
@Test
31+
void constructorDoesNotResolveAgentCardInstances() {
32+
Instance<AgentCard> throwOnGet = TestInstances.throwOnGet();
33+
34+
assertDoesNotThrow(() -> new QuarkusGrpcHandler(
35+
throwOnGet,
36+
throwOnGet,
37+
null,
38+
FixedInstance.empty(),
39+
Runnable::run));
40+
}
41+
42+
@Test
43+
void getExtendedAgentCardResolvesOnAccess() {
44+
AtomicBoolean resolved = new AtomicBoolean(false);
45+
AgentCard expected = AgentCard.builder()
46+
.name("extended").description("test").version("1.0.0")
47+
.supportedInterfaces(Collections.singletonList(new AgentInterface("gRPC", "http://localhost:9999")))
48+
.capabilities(AgentCapabilities.builder().build())
49+
.defaultInputModes(new ArrayList<>())
50+
.defaultOutputModes(new ArrayList<>())
51+
.skills(new ArrayList<>()).build();
52+
53+
Instance<AgentCard> trackingInstance = new FixedInstance<>(expected) {
54+
@Override
55+
public AgentCard get() {
56+
resolved.set(true);
57+
return super.get();
58+
}
59+
};
60+
61+
QuarkusGrpcHandler handler = new QuarkusGrpcHandler(
62+
FixedInstance.empty(),
63+
trackingInstance,
64+
null,
65+
FixedInstance.empty(),
66+
Runnable::run);
67+
68+
assertFalse(resolved.get(), "should not resolve during construction");
69+
AgentCard result = handler.getExtendedAgentCard();
70+
assertTrue(resolved.get(), "should resolve on access");
71+
assertEquals(expected, result);
72+
}
73+
}

‎server-common/src/main/java/org/a2aproject/sdk/server/AgentCardValidator.java‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,14 @@
55
import java.util.List;
66
import java.util.ServiceLoader;
77
import java.util.Set;
8+
import java.util.concurrent.atomic.AtomicBoolean;
9+
import java.util.function.Consumer;
10+
import java.util.function.Supplier;
811
import java.util.logging.Logger;
912
import java.util.stream.Collectors;
1013

14+
import jakarta.enterprise.inject.Instance;
15+
1116
import org.a2aproject.sdk.spec.AgentCard;
1217
import org.a2aproject.sdk.spec.AgentInterface;
1318
import org.a2aproject.sdk.spec.TransportProtocol;
@@ -25,10 +30,51 @@ public class AgentCardValidator {
2530
public static final String SKIP_GRPC_PROPERTY = "org.a2aproject.sdk.transport.grpc.skipValidation";
2631
public static final String SKIP_REST_PROPERTY = "org.a2aproject.sdk.transport.rest.skipValidation";
2732

33+
/**
34+
* Resolves an {@link AgentCard} from the given {@link Instance} and validates its transport
35+
* configuration exactly once using the default {@link #validateTransportConfiguration} check.
36+
* The {@code transportValidated} guard is reset on failure so validation can be retried on
37+
* the next call.
38+
*
39+
* @param agentCardInstance the CDI instance holding the agent card
40+
* @param transportValidated atomic guard ensuring validation runs once
41+
* @return the resolved agent card
42+
*/
43+
public static AgentCard resolveAndValidateOnce(Instance<AgentCard> agentCardInstance,
44+
AtomicBoolean transportValidated) {
45+
return resolveAndValidateOnce(agentCardInstance::get, transportValidated,
46+
AgentCardValidator::validateTransportConfiguration);
47+
}
48+
49+
/**
50+
* Obtains an {@link AgentCard} from the given supplier and applies the provided validator
51+
* exactly once. The {@code transportValidated} guard is reset on failure so validation can
52+
* be retried on the next call.
53+
*
54+
* @param agentCardSupplier supplier that produces the agent card
55+
* @param transportValidated atomic guard ensuring validation runs once
56+
* @param validator validation logic to apply on first access
57+
* @return the resolved agent card
58+
*/
59+
public static AgentCard resolveAndValidateOnce(Supplier<AgentCard> agentCardSupplier,
60+
AtomicBoolean transportValidated,
61+
Consumer<AgentCard> validator) {
62+
AgentCard card = agentCardSupplier.get();
63+
if (transportValidated.compareAndSet(false, true)) {
64+
try {
65+
validator.accept(card);
66+
} catch (RuntimeException e) {
67+
transportValidated.set(false);
68+
throw e;
69+
}
70+
}
71+
return card;
72+
}
73+
2874
/**
2975
* Validates the transport configuration of an AgentCard against available transports found on the classpath.
3076
* Logs warnings for missing transports and errors for unsupported transports.
31-
*
77+
*
3278
* @param agentCard the agent card to validate
3379
*/
3480
public static void validateTransportConfiguration(AgentCard agentCard) {
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
package org.a2aproject.sdk.server;
2+
3+
import java.lang.annotation.Annotation;
4+
import java.util.Collections;
5+
import java.util.Iterator;
6+
7+
import jakarta.enterprise.inject.Instance;
8+
import jakarta.enterprise.inject.UnsatisfiedResolutionException;
9+
import jakarta.enterprise.util.TypeLiteral;
10+
11+
import org.jspecify.annotations.Nullable;
12+
13+
/**
14+
* A static {@link Instance} wrapper holding a pre-resolved (or absent) value,
15+
* for use in non-CDI contexts such as convenience constructors and tests.
16+
* A {@code null} value represents an unsatisfied instance.
17+
*
18+
* <p>Usage example (wrapping a concrete value):
19+
* <pre>{@code
20+
* Instance<AgentCard> instance = new FixedInstance<>(myAgentCard);
21+
* }</pre>
22+
*
23+
* <p>Usage example (empty / unsatisfied):
24+
* <pre>{@code
25+
* Instance<AgentCard> empty = FixedInstance.empty();
26+
* }</pre>
27+
*
28+
* @param <T> the bean type
29+
*/
30+
public class FixedInstance<T> implements Instance<T> {
31+
32+
@SuppressWarnings("rawtypes")
33+
private static final FixedInstance EMPTY = new FixedInstance<>(null);
34+
35+
private final @Nullable T value;
36+
37+
public FixedInstance(@Nullable T value) {
38+
this.value = value;
39+
}
40+
41+
/**
42+
* Returns a {@code FixedInstance} with no value (unsatisfied).
43+
*
44+
* @param <T> the bean type
45+
* @return an empty instance
46+
*/
47+
@SuppressWarnings("unchecked")
48+
public static <T> FixedInstance<T> empty() {
49+
return (FixedInstance<T>) EMPTY;
50+
}
51+
52+
@Override
53+
public T get() {
54+
if (value == null) {
55+
throw new UnsatisfiedResolutionException("No value available");
56+
}
57+
return value;
58+
}
59+
60+
@Override
61+
public boolean isUnsatisfied() {
62+
return value == null;
63+
}
64+
65+
@Override
66+
public boolean isAmbiguous() {
67+
return false;
68+
}
69+
70+
@Override
71+
public Iterator<T> iterator() {
72+
return value != null ? Collections.singleton(value).iterator() : Collections.emptyIterator();
73+
}
74+
75+
@Override
76+
public void destroy(T instance) {
77+
}
78+
79+
@Override
80+
public Instance<T> select(Annotation... qualifiers) {
81+
throw new UnsupportedOperationException();
82+
}
83+
84+
@Override
85+
public <U extends T> Instance<U> select(Class<U> subtype, Annotation... qualifiers) {
86+
throw new UnsupportedOperationException();
87+
}
88+
89+
@Override
90+
public <U extends T> Instance<U> select(TypeLiteral<U> subtype, Annotation... qualifiers) {
91+
throw new UnsupportedOperationException();
92+
}
93+
94+
@Override
95+
public Handle<T> getHandle() {
96+
throw new UnsupportedOperationException();
97+
}
98+
99+
@Override
100+
public Iterable<? extends Handle<T>> handles() {
101+
throw new UnsupportedOperationException();
102+
}
103+
}

‎server-common/src/test/java/org/a2aproject/sdk/server/AgentCardValidatorTest.java‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
package org.a2aproject.sdk.server;
22

33
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
45
import static org.junit.jupiter.api.Assertions.assertFalse;
56
import static org.junit.jupiter.api.Assertions.assertThrows;
67
import static org.junit.jupiter.api.Assertions.assertTrue;
78

89
import java.util.Collections;
910
import java.util.List;
1011
import java.util.Set;
12+
import java.util.concurrent.atomic.AtomicBoolean;
13+
import java.util.concurrent.atomic.AtomicInteger;
1114
import java.util.logging.Handler;
1215
import java.util.logging.LogRecord;
1316
import java.util.logging.Logger;
@@ -229,6 +232,44 @@ void testSkipPropertiesFilterWarnings() {
229232
}
230233
}
231234

235+
@Test
236+
void resolveAndValidateOnceRetriesAfterFailure() {
237+
AgentCard card = createTestAgentCardBuilder().build();
238+
AtomicBoolean guard = new AtomicBoolean(false);
239+
AtomicInteger validationCount = new AtomicInteger(0);
240+
241+
assertThrows(IllegalStateException.class, () ->
242+
AgentCardValidator.resolveAndValidateOnce(
243+
() -> card, guard, c -> {
244+
validationCount.incrementAndGet();
245+
throw new IllegalStateException("transient failure");
246+
}));
247+
248+
assertFalse(guard.get(), "guard should be reset after failure");
249+
assertEquals(1, validationCount.get());
250+
251+
AgentCard result = AgentCardValidator.resolveAndValidateOnce(
252+
() -> card, guard, c -> validationCount.incrementAndGet());
253+
254+
assertTrue(guard.get(), "guard should be set after success");
255+
assertEquals(2, validationCount.get());
256+
assertEquals(card, result);
257+
}
258+
259+
@Test
260+
void resolveAndValidateOnceSkipsValidationOnSubsequentCalls() {
261+
AgentCard card = createTestAgentCardBuilder().build();
262+
AtomicBoolean guard = new AtomicBoolean(false);
263+
AtomicInteger validationCount = new AtomicInteger(0);
264+
265+
AgentCardValidator.resolveAndValidateOnce(
266+
() -> card, guard, c -> validationCount.incrementAndGet());
267+
AgentCardValidator.resolveAndValidateOnce(
268+
() -> card, guard, c -> validationCount.incrementAndGet());
269+
270+
assertEquals(1, validationCount.get(), "validation should run only once");
271+
}
272+
232273
// A simple log handler for testing
233274
private static class TestLogHandler extends Handler {
234275
private final List<String> logMessages = new java.util.ArrayList<>();

0 commit comments

Comments
 (0)