Repository navigation
Expand file tree
/
Copy pathJdkA2AHttpClient.java
More file actions
342 lines (296 loc) · 12.6 KB
/
Copy pathJdkA2AHttpClient.java
File metadata and controls
342 lines (296 loc) · 12.6 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
package io.a2a.client.http;
import static java.net.HttpURLConnection.HTTP_FORBIDDEN;
import static java.net.HttpURLConnection.HTTP_MULT_CHOICE;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandler;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.http.HttpResponse.BodySubscribers;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Flow;
import java.util.function.Consumer;
import org.jspecify.annotations.Nullable;
import io.a2a.common.A2AErrorMessages;
/**
* Default HTTP client implementation using JDK 11+ {@link HttpClient}.
*
* <p>This is the fallback implementation used when no higher-priority
* {@link A2AHttpClientProvider} is available. It provides full support for:
* <ul>
* <li>HTTP/2 with automatic fallback to HTTP/1.1</li>
* <li>Synchronous GET, POST, and DELETE requests</li>
* <li>Asynchronous Server-Sent Events (SSE) streaming</li>
* <li>Automatic redirect following</li>
* </ul>
*
* <p><b>Provider Priority:</b> 0 (lowest - used as fallback)
*
* <p>This implementation is registered via {@link JdkA2AHttpClientProvider}
* in the ServiceLoader system and is automatically used by {@link A2AHttpClientFactory}
* when no other provider is available.
*
* @see A2AHttpClient
* @see A2AHttpClientFactory
* @see JdkA2AHttpClientProvider
*/
public class JdkA2AHttpClient implements A2AHttpClient {
private final HttpClient httpClient;
/**
* Creates a new JDK-based HTTP client.
*
* <p>Configures the client with:
* <ul>
* <li>HTTP/2 preferred (with HTTP/1.1 fallback)</li>
* <li>Normal redirect following</li>
* </ul>
*/
public JdkA2AHttpClient() {
httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
}
@Override
public GetBuilder createGet() {
return new JdkGetBuilder();
}
@Override
public PostBuilder createPost() {
return new JdkPostBuilder();
}
@Override
public DeleteBuilder createDelete() {
return new JdkDeleteBuilder();
}
private abstract class JdkBuilder<T extends Builder<T>> implements Builder<T> {
private String url = "";
private Map<String, String> headers = new HashMap<>();
@Override
public T url(String url) {
this.url = url;
return self();
}
@Override
public T addHeader(String name, String value) {
headers.put(name, value);
return self();
}
@Override
public T addHeaders(Map<String, String> headers) {
if(headers != null && ! headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
addHeader(entry.getKey(), entry.getValue());
}
}
return self();
}
@SuppressWarnings("unchecked")
T self() {
return (T) this;
}
protected HttpRequest.Builder createRequestBuilder() throws IOException {
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(url));
for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
builder.header(headerEntry.getKey(), headerEntry.getValue());
}
return builder;
}
protected CompletableFuture<Void> asyncRequest(
HttpRequest request,
Consumer<String> messageConsumer,
Consumer<Throwable> errorConsumer,
Runnable completeRunnable
) {
Flow.Subscriber<String> subscriber = new Flow.Subscriber<String>() {
private Flow.@Nullable Subscription subscription;
private volatile boolean errorRaised = false;
@Override
public void onSubscribe(Flow.Subscription subscription) {
this.subscription = subscription;
this.subscription.request(1);
}
@Override
public void onNext(String item) {
// SSE messages sometimes start with "data:". Strip that off
if (item != null && item.startsWith("data:")) {
item = item.substring(5).trim();
if (!item.isEmpty()) {
messageConsumer.accept(item);
}
}
if (subscription != null) {
subscription.request(1);
}
}
@Override
public void onError(Throwable throwable) {
if (!errorRaised) {
errorRaised = true;
errorConsumer.accept(throwable);
}
if (subscription != null) {
subscription.cancel();
}
}
@Override
public void onComplete() {
if (!errorRaised) {
completeRunnable.run();
}
if (subscription != null) {
subscription.cancel();
}
}
};
// Create a custom body handler that checks status before processing body
BodyHandler<Void> bodyHandler = responseInfo -> {
// Check for authentication/authorization errors only
if (responseInfo.statusCode() == HTTP_UNAUTHORIZED || responseInfo.statusCode() == HTTP_FORBIDDEN) {
final String errorMessage;
if (responseInfo.statusCode() == HTTP_UNAUTHORIZED) {
errorMessage = A2AErrorMessages.AUTHENTICATION_FAILED;
} else {
errorMessage = A2AErrorMessages.AUTHORIZATION_FAILED;
}
// Return a body subscriber that immediately signals error
return BodySubscribers.fromSubscriber(new Flow.Subscriber<List<ByteBuffer>>() {
@Override
public void onSubscribe(Flow.Subscription subscription) {
subscriber.onError(new IOException(errorMessage));
}
@Override
public void onNext(List<ByteBuffer> item) {
// Should not be called
}
@Override
public void onError(Throwable throwable) {
// Should not be called
}
@Override
public void onComplete() {
// Should not be called
}
});
} else {
// For all other status codes (including other errors), proceed with normal line subscriber
return BodyHandlers.fromLineSubscriber(subscriber).apply(responseInfo);
}
};
// Send the response async, and let the subscriber handle the lines.
return httpClient.sendAsync(request, bodyHandler)
.thenAccept(response -> {
// Handle non-authentication/non-authorization errors here
if (!isSuccessStatus(response.statusCode()) &&
response.statusCode() != HTTP_UNAUTHORIZED &&
response.statusCode() != HTTP_FORBIDDEN) {
subscriber.onError(new IOException("Request failed with status " + response.statusCode() + ":" + response.body()));
}
});
}
}
private class JdkGetBuilder extends JdkBuilder<GetBuilder> implements A2AHttpClient.GetBuilder {
private HttpRequest.Builder createRequestBuilder(boolean SSE) throws IOException {
HttpRequest.Builder builder = super.createRequestBuilder().GET();
if (SSE) {
builder.header(ACCEPT, EVENT_STREAM);
}
return builder;
}
@Override
public A2AHttpResponse get() throws IOException, InterruptedException {
HttpRequest request = createRequestBuilder(false)
.build();
HttpResponse<String> response =
httpClient.send(request, BodyHandlers.ofString(StandardCharsets.UTF_8));
return new JdkHttpResponse(response);
}
@Override
public CompletableFuture<Void> getAsyncSSE(
Consumer<String> messageConsumer,
Consumer<Throwable> errorConsumer,
Runnable completeRunnable) throws IOException, InterruptedException {
HttpRequest request = createRequestBuilder(true)
.build();
return super.asyncRequest(request, messageConsumer, errorConsumer, completeRunnable);
}
}
private class JdkDeleteBuilder extends JdkBuilder<DeleteBuilder> implements A2AHttpClient.DeleteBuilder {
@Override
public A2AHttpResponse delete() throws IOException, InterruptedException {
HttpRequest request = super.createRequestBuilder().DELETE().build();
HttpResponse<String> response =
httpClient.send(request, BodyHandlers.ofString(StandardCharsets.UTF_8));
return new JdkHttpResponse(response);
}
}
private class JdkPostBuilder extends JdkBuilder<PostBuilder> implements A2AHttpClient.PostBuilder {
String body = "";
@Override
public PostBuilder body(String body) {
this.body = body;
return self();
}
private HttpRequest.Builder createRequestBuilder(boolean SSE) throws IOException {
HttpRequest.Builder builder = super.createRequestBuilder()
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8));
if (SSE) {
builder.header(ACCEPT, EVENT_STREAM);
}
return builder;
}
@Override
public A2AHttpResponse post() throws IOException, InterruptedException {
HttpRequest request = createRequestBuilder(false)
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
.build();
HttpResponse<String> response =
httpClient.send(request, BodyHandlers.ofString(StandardCharsets.UTF_8));
if (response.statusCode() == HTTP_UNAUTHORIZED) {
throw new IOException(A2AErrorMessages.AUTHENTICATION_FAILED);
} else if (response.statusCode() == HTTP_FORBIDDEN) {
throw new IOException(A2AErrorMessages.AUTHORIZATION_FAILED);
}
return new JdkHttpResponse(response);
}
@Override
public CompletableFuture<Void> postAsyncSSE(
Consumer<String> messageConsumer,
Consumer<Throwable> errorConsumer,
Runnable completeRunnable) throws IOException, InterruptedException {
HttpRequest request = createRequestBuilder(true)
.build();
return super.asyncRequest(request, messageConsumer, errorConsumer, completeRunnable);
}
}
private record JdkHttpResponse(HttpResponse<String> response) implements A2AHttpResponse {
@Override
public int status() {
return response.statusCode();
}
@Override
public boolean success() {// Send the request and get the response
return success(response);
}
static boolean success(HttpResponse<?> response) {
return response.statusCode() >= HTTP_OK && response.statusCode() < HTTP_MULT_CHOICE;
}
@Override
public String body() {
return response.body();
}
}
private static boolean isSuccessStatus(int statusCode) {
return statusCode >= HTTP_OK && statusCode < HTTP_MULT_CHOICE;
}
}