-
Notifications
You must be signed in to change notification settings - Fork 400
Expand file tree
/
Copy pathHttpClient.java
More file actions
340 lines (288 loc) · 10.6 KB
/
HttpClient.java
File metadata and controls
340 lines (288 loc) · 10.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
package com.stripe.net;
import com.google.gson.Gson;
import com.stripe.Stripe;
import com.stripe.exception.ApiConnectionException;
import com.stripe.exception.StripeException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
/** Base abstract class for HTTP clients used to send requests to Stripe's API. */
public abstract class HttpClient {
/** Maximum sleep time between tries to send HTTP requests after network failure. */
public static final Duration maxNetworkRetriesDelay = Duration.ofSeconds(5);
/** Minimum sleep time between tries to send HTTP requests after network failure. */
public static final Duration minNetworkRetriesDelay = Duration.ofMillis(500);
/** A value indicating whether the client should sleep between automatic request retries. */
boolean networkRetriesSleep = true;
/** Initializes a new instance of the {@link HttpClient} class. */
protected HttpClient() {}
/**
* Sends the given request to Stripe's API, buffering the response body into memory.
*
* @param request the request
* @return the response
* @throws StripeException If the request fails for any reason
*/
public abstract StripeResponse request(StripeRequest request) throws StripeException;
/**
* Sends the given request to Stripe's API, streaming the response body.
*
* @param request the request
* @return the response
* @throws StripeException If the request fails for any reason
*/
public StripeResponseStream requestStream(StripeRequest request) throws StripeException {
throw new UnsupportedOperationException("requestStream is unimplemented for this HttpClient");
}
@FunctionalInterface
private interface RequestSendFunction<R> {
R apply(StripeRequest request) throws StripeException;
}
/**
* @param request the request
* @return the response
* @throws StripeException If the request fails for any reason
* @deprecated Use {@link #request(StripeRequest)} instead.
*/
@Deprecated
public StripeResponse requestWithTelemetry(StripeRequest request) throws StripeException {
return this.request(request);
}
/**
* @param request the request
* @return the response
* @throws StripeException If the request fails for any reason
* @deprecated Use {@link #requestStream(StripeRequest)} instead.
*/
@Deprecated
public StripeResponseStream requestStreamWithTelemetry(StripeRequest request)
throws StripeException {
return this.requestStream(request);
}
public <T extends AbstractStripeResponse<?>> T sendWithRetries(
StripeRequest request, RequestSendFunction<T> send) throws StripeException {
ApiConnectionException requestException = null;
T response = null;
int retry = 0;
while (true) {
requestException = null;
try {
response = send.apply(request);
} catch (ApiConnectionException e) {
requestException = e;
}
if (!this.shouldRetry(retry, requestException, request, response)) {
break;
}
retry += 1;
try {
Thread.sleep(this.sleepTime(retry).toMillis());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
if (requestException != null) {
throw requestException;
}
response.numRetries(retry);
return response;
}
/**
* Sends the given request to Stripe's API, retrying the request in cases of intermittent
* problems.
*
* @param request the request
* @return the response
* @throws StripeException If the request fails for any reason
*/
public StripeResponse requestWithRetries(StripeRequest request) throws StripeException {
return sendWithRetries(request, (r) -> this.request(r));
}
/**
* Sends the given request to Stripe's API, streaming the response, retrying the request in cases
* of intermittent problems.
*
* @param request the request
* @return the response
* @throws StripeException If the request fails for any reason
*/
public StripeResponseStream requestStreamWithRetries(StripeRequest request)
throws StripeException {
return sendWithRetries(request, (r) -> this.requestStream(r));
}
static String detectAIAgent() {
return detectAIAgent(System::getenv);
}
static String detectAIAgent(Function<String, String> getEnv) {
String[][] agents = {
// The beginning of the section generated from our OpenAPI spec
{"ANTIGRAVITY_CLI_ALIAS", "antigravity"},
{"CLAUDECODE", "claude_code"},
{"CLINE_ACTIVE", "cline"},
{"CODEX_SANDBOX", "codex_cli"},
{"CODEX_THREAD_ID", "codex_cli"},
{"CODEX_SANDBOX_NETWORK_DISABLED", "codex_cli"},
{"CODEX_CI", "codex_cli"},
{"CURSOR_AGENT", "cursor"},
{"GEMINI_CLI", "gemini_cli"},
{"OPENCODE", "open_code"},
// The end of the section generated from our OpenAPI spec
};
for (String[] agent : agents) {
String val = getEnv.apply(agent[0]);
if (val != null && !val.isEmpty()) {
return agent[1];
}
}
return "";
}
/**
* Builds the value of the {@code User-Agent} header.
*
* @return a string containing the value of the {@code User-Agent} header
*/
protected static String buildUserAgentString(StripeRequest request) {
return buildUserAgentString(request, detectAIAgent());
}
static String buildUserAgentString(StripeRequest request, String aiAgent) {
String apiMode = request.apiMode() == ApiMode.V2 ? "v2" : "v1";
String userAgent = String.format("Stripe/%s JavaBindings/%s", apiMode, Stripe.VERSION);
if (Stripe.getAppInfo() != null) {
userAgent += " " + formatAppInfo(Stripe.getAppInfo());
}
if (!aiAgent.isEmpty()) {
userAgent += " AIAgent/" + aiAgent;
}
return userAgent;
}
/**
* Builds the value of the {@code X-Stripe-Client-User-Agent} header.
*
* @return a string containing the value of the {@code X-Stripe-Client-User-Agent} header
*/
protected static String buildXStripeClientUserAgentString() {
return buildXStripeClientUserAgentString(detectAIAgent());
}
static String buildXStripeClientUserAgentString(String aiAgent) {
String[] propertyNames = {"java.version", "java.vendor", "java.vm.version", "java.vm.vendor"};
Map<String, String> propertyMap = new HashMap<>();
for (String propertyName : propertyNames) {
propertyMap.put(propertyName, System.getProperty(propertyName));
}
propertyMap.put("bindings.version", Stripe.VERSION);
propertyMap.put("lang", "Java");
if (Stripe.enableTelemetry) {
propertyMap.put(
"platform",
System.getProperty("os.name")
+ " "
+ System.getProperty("os.version")
+ " "
+ System.getProperty("os.arch"));
}
if (Stripe.getAppInfo() != null) {
propertyMap.put("application", ApiResource.INTERNAL_GSON.toJson(Stripe.getAppInfo()));
}
getGsonVersion().ifPresent(ver -> propertyMap.put("gson.version", ver));
if (!aiAgent.isEmpty()) {
propertyMap.put("ai_agent", aiAgent);
}
return ApiResource.INTERNAL_GSON.toJson(propertyMap);
}
/**
* Gets the Gson version being used at runtime.
*
* @return the Gson version string, or Optional.empty() if it cannot be determined
*/
private static Optional<String> getGsonVersion() {
try (InputStream in =
Gson.class.getResourceAsStream(
"/META-INF/maven/com.google.code.gson/gson/pom.properties")) {
if (in != null) {
Properties props = new Properties();
props.load(in);
return Optional.ofNullable(props.getProperty("version"));
}
} catch (Exception ignore) {
// Silently ignore - we'll just not include the version
}
return Optional.empty();
}
private static String formatAppInfo(Map<String, String> info) {
String str = info.get("name");
if (info.get("version") != null) {
str += String.format("/%s", info.get("version"));
}
if (info.get("url") != null) {
str += String.format(" (%s)", info.get("url"));
}
return str;
}
private <T extends AbstractStripeResponse<?>> boolean shouldRetry(
int numRetries, StripeException exception, StripeRequest request, T response) {
// Do not retry if we are out of retries.
if (numRetries >= request.options().getMaxNetworkRetries()) {
return false;
}
// Retry on connection error.
if ((exception != null)
&& (exception.getCause() != null)
&& (exception.getCause() instanceof ConnectException
|| exception.getCause() instanceof SocketTimeoutException)) {
return true;
}
// The API may ask us not to retry (eg; if doing so would be a no-op)
// or advise us to retry (eg; in cases of lock timeouts); we defer to that.
if ((response != null) && (response.headers() != null)) {
String value = response.headers().firstValue("Stripe-Should-Retry").orElse(null);
if ("true".equals(value)) {
return true;
}
if ("false".equals(value)) {
return false;
}
}
// Retry on conflict errors.
if ((response != null) && (response.code() == 409)) {
return true;
}
// Retry on 500, 503, and other internal errors.
//
// Note that we expect the Stripe-Should-Retry header to be false
// in most cases when a 500 is returned, since our idempotency framework
// would typically replay it anyway.
if ((response != null) && (response.code() >= 500)) {
return true;
}
return false;
}
private Duration sleepTime(int numRetries) {
// We disable sleeping in some cases for tests.
if (!this.networkRetriesSleep) {
return Duration.ZERO;
}
// Apply exponential backoff with MinNetworkRetriesDelay on the number of numRetries
// so far as inputs.
Duration delay =
Duration.ofNanos((long) (minNetworkRetriesDelay.toNanos() * Math.pow(2, numRetries - 1)));
// Do not allow the number to exceed MaxNetworkRetriesDelay
if (delay.compareTo(maxNetworkRetriesDelay) > 0) {
delay = maxNetworkRetriesDelay;
}
// Apply some jitter by randomizing the value in the range of 75%-100%.
double jitter = ThreadLocalRandom.current().nextDouble(0.75, 1.0);
delay = Duration.ofNanos((long) (delay.toNanos() * jitter));
// But never sleep less than the base sleep seconds.
if (delay.compareTo(minNetworkRetriesDelay) < 0) {
delay = minNetworkRetriesDelay;
}
return delay;
}
}