import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Predicate;
/**
* v0.1 DRAFT. A minimal Borrou Partner API client on java.net.http (Java 17+).
*
*
* - OAuth 2.0 client credentials, the access token cached until a minute before it expires.
*
- Every POST and DELETE carries an Idempotency-Key. One key per request: every retry of that
* request sends the same key, and a new request gets a new one.
*
- Retries on no answer (a timeout or a dropped connection), 429 and 5xx, honouring
* Retry-After; a 409 only when Borrou sends Retry-After with it (see {@link #retryable}).
*
- Cursor pagination.
*
*/
public final class BorrouClient {
/** A refusal. Branch on {@code code} (docs/api/ERRORS.md); the message is for people and may change. */
public static final class ApiError extends RuntimeException {
public final int status;
public final String code;
/** Quote it to TFG when asking about a request. */
public final String requestId;
public final Long retryAfterSeconds;
public final Object body;
ApiError(int status, String code, String message, String requestId, Long retryAfterSeconds, Object body) {
super(status + " " + code + ": " + message);
this.status = status;
this.code = code;
this.requestId = requestId;
this.retryAfterSeconds = retryAfterSeconds;
this.body = body;
}
static ApiError from(int status, Object body, String requestId, Long retryAfterSeconds) {
String code = "unknown";
String message = "HTTP " + status;
String id = requestId;
if (body instanceof Map, ?> map && map.get("error") instanceof Map, ?> error) {
if (error.get("code") instanceof String errorCode) code = errorCode;
if (error.get("message") instanceof String errorMessage) message = errorMessage;
if (error.get("request_id") instanceof String errorRequestId) id = errorRequestId;
}
return new ApiError(status, code, message, id, retryAfterSeconds, body);
}
}
/** {@code replayed}: Borrou answered with the stored response of an earlier request with this key. */
public record Response(int status, Object body, String requestId, boolean replayed) {}
private static final long TOKEN_RENEWAL_MARGIN_MILLIS = 60_000;
private final String baseUrl;
private final String clientId;
private final String clientSecret;
private final int maxAttempts;
private final long maxRetryAfterSeconds;
private final Duration timeout;
private final HttpClient http;
private String token;
private long tokenExpiresAtMillis;
/** {@code baseUrl}: https://api.borrou.capital for the sandbox. */
public BorrouClient(String baseUrl, String clientId, String clientSecret) {
this(baseUrl, clientId, clientSecret, 5, 60, Duration.ofSeconds(30));
}
public BorrouClient(String baseUrl, String clientId, String clientSecret, int maxAttempts, long maxRetryAfterSeconds, Duration timeout) {
this.baseUrl = baseUrl.replaceAll("/+$", "");
this.clientId = clientId;
this.clientSecret = clientSecret;
this.maxAttempts = maxAttempts;
this.maxRetryAfterSeconds = maxRetryAfterSeconds;
this.timeout = timeout;
this.http = HttpClient.newBuilder().connectTimeout(timeout).build();
}
/** The cached access token, renewed a minute before it expires; one renewal at a time. */
public synchronized String accessToken() throws IOException, InterruptedException {
if (token == null || System.currentTimeMillis() >= tokenExpiresAtMillis - TOKEN_RENEWAL_MARGIN_MILLIS) {
// RFC 6749 section 2.3.1: the id and the secret form-encoded, then base64 in HTTP Basic.
String pair = form(clientId) + ":" + form(clientSecret);
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(baseUrl + "/v1/oauth/token"))
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString(pair.getBytes(StandardCharsets.UTF_8)))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString("grant_type=client_credentials"));
Map body = MiniJson.object(send(request).body());
token = (String) body.get("access_token");
tokenExpiresAtMillis = System.currentTimeMillis() + ((Number) body.get("expires_in")).longValue() * 1000;
}
return token;
}
public Response get(String path, Map query) throws IOException, InterruptedException {
return request("GET", path, query, null, null);
}
/** An idempotent write. Pass {@code idempotencyKey} only to retry a request your process lost track of; null makes a new one. */
public Response post(String path, Object body, String idempotencyKey) throws IOException, InterruptedException {
return request("POST", path, null, body, idempotencyKey);
}
public Response delete(String path, String idempotencyKey) throws IOException, InterruptedException {
return request("DELETE", path, null, null, idempotencyKey);
}
public Response request(String method, String path, Map query, Object body, String idempotencyKey)
throws IOException, InterruptedException {
// One key for every attempt of this request, never shared with another request.
String key = method.equals("GET") ? null : (idempotencyKey != null ? idempotencyKey : UUID.randomUUID().toString());
boolean renewed = false;
while (true) {
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(baseUrl + path + queryString(query)))
.header("Authorization", "Bearer " + accessToken());
if (key != null) builder.header("Idempotency-Key", key);
if (body != null) {
builder.header("Content-Type", "application/json").method(method, HttpRequest.BodyPublishers.ofString(MiniJson.write(body)));
} else {
builder.method(method, HttpRequest.BodyPublishers.noBody());
}
try {
return send(builder);
} catch (ApiError e) {
// A token cut off by a credential rotation is refused before anything runs: renew it once.
if (e.status == 401 && "invalid_token".equals(e.code) && !renewed) {
synchronized (this) {
token = null;
}
renewed = true;
continue;
}
throw e;
}
}
}
/**
* Every item of a cursor-paginated list, until {@code each} returns false. Lists take
* {@code starting_after} (applications, clients, loans); the events feed takes {@code after}.
*/
public void paginate(String path, Map query, String cursorParam, Predicate