Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .fern/metadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"cliVersion": "0.0.0",
"generatorName": "fernapi/fern-java-sdk",
"generatorVersion": "99.99.99",
"generatorConfig": {
"client-class-name": "Lattice",
"package-prefix": "com.anduril"
}
}
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -186,4 +186,4 @@ of any court action, you agree to submit to the exclusive jurisdiction of the co
Notwithstanding this, you agree that Anduril shall still be allowed to apply for injunctive remedies (or an equivalent type of urgent legal
relief) in any jurisdiction.

**April 14, 2025**
**April 14, 2025**
27 changes: 21 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ Add the dependency in your `pom.xml` file:
<dependency>
<groupId>com.anduril</groupId>
<artifactId>lattice-sdk</artifactId>
<version>2.4.0</version>
<version>0.0.3405</version>
</dependency>
```

Expand Down Expand Up @@ -103,9 +103,9 @@ When the API returns a non-success status code (4xx or 5xx response), an API exc
```java
import com.anduril.core.AndurilApiApiException;

try {
try{
client.entities().longPollEntityEvents(...);
} catch (AndurilApiApiException e) {
} catch (AndurilApiApiException e){
// Do something with the API exception...
}
```
Expand All @@ -114,7 +114,7 @@ try {

### Custom Client

This SDK is built to work with any instance of `OkHttpClient`. By default, if no client is provided, the SDK will construct one.
This SDK is built to work with any instance of `OkHttpClient`. By default, if no client is provided, the SDK will construct one.
However, you can pass your own client like so:

```java
Expand All @@ -133,7 +133,9 @@ Lattice client = Lattice

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long
as the request is deemed retryable and the number of retry attempts has not grown larger than the configured
retry limit (default: 2).
retry limit (default: 2). Before defaulting to exponential backoff, the SDK will first attempt to respect
the `Retry-After` header (as either in seconds or as an HTTP date), and then the `X-RateLimit-Reset` header
(as a Unix timestamp in epoch seconds); failing both of those, it will fall back to exponential backoff.

A request is deemed retryable when any of the following HTTP status codes is returned:

Expand Down Expand Up @@ -202,6 +204,19 @@ client.entities().longPollEntityEvents(
);
```

### Access Raw Response Data

The SDK provides access to raw response data, including headers, through the `withRawResponse()` method.
The `withRawResponse()` method returns a raw client that wraps all responses with `body()` and `headers()` methods.
(A normal client's `response` is identical to a raw client's `response.body()`.)

```java
LongPollEntityEventsHttpResponse response = client.entities().withRawResponse().longPollEntityEvents(...);

System.out.println(response.body());
System.out.println(response.headers().get("X-My-Header"));
```

## Reference

A full reference for this library is available [here](https://github.com/anduril/lattice-sdk-java/blob/HEAD/./reference.md).
A full reference for this library is available [here](https://github.com/fern-api/lattice-sdk-java/blob/HEAD/./reference.md).
22 changes: 11 additions & 11 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ java {

group = 'com.anduril'

version = '2.4.0'
version = '0.0.3405'

jar {
dependsOn(":generatePomFileForMavenPublication")
Expand Down Expand Up @@ -78,27 +78,27 @@ publishing {
maven(MavenPublication) {
groupId = 'com.anduril'
artifactId = 'lattice-sdk'
version = '2.4.0'
version = '0.0.3405'
from components.java
pom {
name = 'Anduril Industries, Inc.'
description = 'Anduril Lattice SDK for Java'
url = 'https://developer.anduril.com'
name = 'anduril'
description = 'The official SDK of anduril'
url = 'https://buildwithfern.com'
licenses {
license {
name = 'Anduril Lattice Software Development Kit License Agreement'
name = 'Custom License (LICENSE)'
}
}
developers {
developer {
name = 'Anduril Industries, Inc.'
email = 'lattice-developers@anduril.com'
name = 'anduril'
email = 'developers@anduril.com'
}
}
scm {
connection = 'scm:git:git://github.com/anduril/lattice-sdk-java.git'
developerConnection = 'scm:git:git://github.com/anduril/lattice-sdk-java.git'
url = 'https://github.com/anduril/lattice-sdk-java'
connection = 'scm:git:git://github.com/fern-api/lattice-sdk-java.git'
developerConnection = 'scm:git:git://github.com/fern-api/lattice-sdk-java.git'
url = 'https://github.com/fern-api/lattice-sdk-java'
}
}
}
Expand Down
16 changes: 11 additions & 5 deletions src/main/java/com/anduril/core/ClientOptions.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,27 @@ public final class ClientOptions {

private final int timeout;

private final int maxRetries;

private ClientOptions(
Environment environment,
Map<String, String> headers,
Map<String, Supplier<String>> headerSuppliers,
OkHttpClient httpClient,
int timeout) {
int timeout,
int maxRetries) {
this.environment = environment;
this.headers = new HashMap<>();
this.headers.putAll(headers);
this.headers.putAll(new HashMap<String, String>() {
{
put("User-Agent", "com.anduril:lattice-sdk/2.4.0");
put("X-Fern-Language", "JAVA");
put("X-Fern-SDK-Name", "com.anduril.fern:api-sdk");
put("X-Fern-SDK-Version", "2.4.0");
}
});
this.headerSuppliers = headerSuppliers;
this.httpClient = httpClient;
this.timeout = timeout;
this.maxRetries = maxRetries;
}

public Environment environment() {
Expand Down Expand Up @@ -82,6 +83,10 @@ public OkHttpClient httpClientWithTimeout(RequestOptions requestOptions) {
.build();
}

public int maxRetries() {
return this.maxRetries;
}

public static Builder builder() {
return new Builder();
}
Expand Down Expand Up @@ -165,7 +170,8 @@ public ClientOptions build() {
this.httpClient = httpClientBuilder.build();
this.timeout = Optional.of(httpClient.callTimeoutMillis() / 1000);

return new ClientOptions(environment, headers, headerSuppliers, httpClient, this.timeout.get());
return new ClientOptions(
environment, headers, headerSuppliers, httpClient, this.timeout.get(), this.maxRetries);
}

/**
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/com/anduril/core/LatticeApiException.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,9 @@ public Map<String, List<String>> headers() {
return this.headers;
}

@java.lang.Override
@Override
public String toString() {
return "LatticeApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: " + body
+ "}";
return "LatticeApiException{" + "message: " + getMessage() + ", statusCode: " + statusCode + ", body: "
+ ObjectMappers.stringify(body) + "}";
}
}
5 changes: 4 additions & 1 deletion src/main/java/com/anduril/core/NullableNonemptyFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ public boolean equals(Object o) {
}

private boolean isOptionalEmpty(Object o) {
return o instanceof Optional && !((Optional<?>) o).isPresent();
if (o instanceof Optional) {
return !((Optional<?>) o).isPresent();
}
return false;
}
}
9 changes: 9 additions & 0 deletions src/main/java/com/anduril/core/ObjectMappers.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package com.anduril.core;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
Expand Down Expand Up @@ -33,4 +34,12 @@ public static String stringify(Object o) {
return o.getClass().getName() + "@" + Integer.toHexString(o.hashCode());
}
}

public static Object parseErrorBody(String responseBodyString) {
try {
return JSON_MAPPER.readValue(responseBodyString, Object.class);
} catch (JsonProcessingException ignored) {
return responseBodyString;
}
}
}
118 changes: 110 additions & 8 deletions src/main/java/com/anduril/core/RetryInterceptor.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,20 @@

import java.io.IOException;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.Random;
import okhttp3.Interceptor;
import okhttp3.Response;

public class RetryInterceptor implements Interceptor {

private static final Duration ONE_SECOND = Duration.ofSeconds(1);
private static final Duration INITIAL_RETRY_DELAY = Duration.ofMillis(1000);
private static final Duration MAX_RETRY_DELAY = Duration.ofMillis(60000);
private static final double JITTER_FACTOR = 0.2;

private final ExponentialBackoff backoff;
private final Random random = new Random();

Expand All @@ -32,7 +38,7 @@ public Response intercept(Chain chain) throws IOException {
}

private Response retryChain(Response response, Chain chain) throws IOException {
Optional<Duration> nextBackoff = this.backoff.nextBackoff();
Optional<Duration> nextBackoff = this.backoff.nextBackoff(response);
while (nextBackoff.isPresent()) {
try {
Thread.sleep(nextBackoff.get().toMillis());
Expand All @@ -42,7 +48,7 @@ private Response retryChain(Response response, Chain chain) throws IOException {
response.close();
response = chain.proceed(chain.request());
if (shouldRetry(response.code())) {
nextBackoff = this.backoff.nextBackoff();
nextBackoff = this.backoff.nextBackoff(response);
} else {
return response;
}
Expand All @@ -51,6 +57,102 @@ private Response retryChain(Response response, Chain chain) throws IOException {
return response;
}

/**
* Calculates the retry delay from response headers, with fallback to exponential backoff.
* Priority: Retry-After > X-RateLimit-Reset > Exponential Backoff
*/
private Duration getRetryDelayFromHeaders(Response response, int retryAttempt) {
// Check for Retry-After header first (RFC 7231), with no jitter
String retryAfter = response.header("Retry-After");
if (retryAfter != null) {
// Parse as number of seconds...
Optional<Duration> secondsDelay = tryParseLong(retryAfter)
.map(seconds -> seconds * 1000)
.filter(delayMs -> delayMs > 0)
.map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis()))
.map(Duration::ofMillis);
if (secondsDelay.isPresent()) {
return secondsDelay.get();
}

// ...or as an HTTP date; both are valid
Optional<Duration> dateDelay = tryParseHttpDate(retryAfter)
.map(resetTime -> resetTime.toInstant().toEpochMilli() - System.currentTimeMillis())
.filter(delayMs -> delayMs > 0)
.map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis()))
.map(Duration::ofMillis);
if (dateDelay.isPresent()) {
return dateDelay.get();
}
}

// Then check for industry-standard X-RateLimit-Reset header, with positive jitter
String rateLimitReset = response.header("X-RateLimit-Reset");
if (rateLimitReset != null) {
// Assume Unix timestamp in epoch seconds
Optional<Duration> rateLimitDelay = tryParseLong(rateLimitReset)
.map(resetTimeSeconds -> (resetTimeSeconds * 1000) - System.currentTimeMillis())
.filter(delayMs -> delayMs > 0)
.map(delayMs -> Math.min(delayMs, MAX_RETRY_DELAY.toMillis()))
.map(this::addPositiveJitter)
.map(Duration::ofMillis);
if (rateLimitDelay.isPresent()) {
return rateLimitDelay.get();
}
}

// Fall back to exponential backoff, with symmetric jitter
long baseDelay = INITIAL_RETRY_DELAY.toMillis() * (1L << retryAttempt); // 2^retryAttempt
long cappedDelay = Math.min(baseDelay, MAX_RETRY_DELAY.toMillis());
return Duration.ofMillis(addSymmetricJitter(cappedDelay));
}

/**
* Attempts to parse a string as a long, returning empty Optional on failure.
*/
private Optional<Long> tryParseLong(String value) {
if (value == null) {
return Optional.empty();
}
try {
return Optional.of(Long.parseLong(value));
} catch (NumberFormatException e) {
return Optional.empty();
}
}

/**
* Attempts to parse a string as an HTTP date (RFC 1123), returning empty Optional on failure.
*/
private Optional<ZonedDateTime> tryParseHttpDate(String value) {
if (value == null) {
return Optional.empty();
}
try {
return Optional.of(ZonedDateTime.parse(value, DateTimeFormatter.RFC_1123_DATE_TIME));
} catch (DateTimeParseException e) {
return Optional.empty();
}
}

/**
* Adds positive jitter (100-120% of original value) to prevent thundering herd.
* Used for X-RateLimit-Reset header delays.
*/
private long addPositiveJitter(long delayMs) {
double jitterMultiplier = 1.0 + (random.nextDouble() * JITTER_FACTOR);
return (long) (delayMs * jitterMultiplier);
}

/**
* Adds symmetric jitter (90-110% of original value) to prevent thundering herd.
* Used for exponential backoff delays.
*/
private long addSymmetricJitter(long delayMs) {
double jitterMultiplier = 1.0 + ((random.nextDouble() - 0.5) * JITTER_FACTOR);
return (long) (delayMs * jitterMultiplier);
}

private static boolean shouldRetry(int statusCode) {
return statusCode == 408 || statusCode == 429 || statusCode >= 500;
}
Expand All @@ -65,14 +167,14 @@ private final class ExponentialBackoff {
this.maxNumRetries = maxNumRetries;
}

public Optional<Duration> nextBackoff() {
retryNumber += 1;
if (retryNumber > maxNumRetries) {
public Optional<Duration> nextBackoff(Response response) {
if (retryNumber >= maxNumRetries) {
return Optional.empty();
}

int upperBound = (int) Math.pow(2, retryNumber);
return Optional.of(ONE_SECOND.multipliedBy(random.nextInt(upperBound)));
Duration delay = getRetryDelayFromHeaders(response, retryNumber);
retryNumber += 1;
return Optional.of(delay);
}
}
}
Loading