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+). * * */ 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> each) throws IOException, InterruptedException { String cursor = null; do { Map pageQuery = new LinkedHashMap<>(query); if (cursor != null) pageQuery.put(cursorParam, cursor); Map page = MiniJson.object(get(path, pageQuery).body()); for (Object item : MiniJson.array(page.get("data"))) { if (!each.test(MiniJson.object(item))) return; } cursor = Boolean.TRUE.equals(page.get("has_more")) ? cursorOf(page.get("next_cursor")) : null; } while (cursor != null); } /** A list's cursor is a string; the events feed's is a position, a number. Either goes back as text. */ private static String cursorOf(Object next) { if (next == null) return null; return next instanceof BigDecimal ? ((BigDecimal) next).toPlainString() : next.toString(); } private Response send(HttpRequest.Builder builder) throws IOException, InterruptedException { builder.header("Accept", "application/json").timeout(timeout); for (int attempt = 1; ; attempt++) { HttpResponse res; try { res = http.send(builder.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8)); } catch (IOException e) { // No answer: the write may or may not have happened, which is what the key is for. if (attempt >= maxAttempts) throw e; Thread.sleep(backoffMillis(attempt)); continue; } Object body = parseOrNull(res.body()); String requestId = res.headers().firstValue("X-Request-Id").orElse(null); if (res.statusCode() >= 200 && res.statusCode() < 300) { boolean replayed = "true".equals(res.headers().firstValue("Idempotent-Replayed").orElse(null)); return new Response(res.statusCode(), body, requestId, replayed); } Long retryAfter = retryAfterSeconds(res.headers().firstValue("Retry-After").orElse(null)); ApiError error = ApiError.from(res.statusCode(), body, requestId, retryAfter); boolean tooLong = retryAfter != null && retryAfter > maxRetryAfterSeconds; if (attempt >= maxAttempts || tooLong || !retryable(res.statusCode(), retryAfter)) throw error; Thread.sleep(retryAfter != null ? retryAfter * 1000 : backoffMillis(attempt)); } } /** * 429 and 5xx are worth another attempt with the same key: a 5xx saved nothing, and 503 * price_unavailable or provider_unavailable carry Retry-After. A 409 is a conflict with the state * of the loan or the application: retrying it unchanged gets the same answer, and a stored one is * replayed as it was. Borrou never answers 409 to a concurrent retry with the same key (that * request waits and replays the first one's answer), so a 409 is retried only when Borrou says when. */ static boolean retryable(int status, Long retryAfterSeconds) { if (status == 429 || status >= 500) return true; return status == 409 && retryAfterSeconds != null; } /** Exponential backoff with full jitter: up to 0.5 s, 1 s, 2 s, ... capped at 30 s. */ static long backoffMillis(int attempt) { long cap = Math.min(30_000L, 500L * (1L << Math.min(attempt - 1, 16))); return (long) (ThreadLocalRandom.current().nextDouble() * cap); } /** Retry-After as seconds, or as an HTTP date; null when absent or unreadable. */ static Long retryAfterSeconds(String value) { if (value == null || value.isBlank()) return null; String trimmed = value.trim(); if (trimmed.chars().allMatch(Character::isDigit)) return Long.valueOf(trimmed); try { ZonedDateTime at = ZonedDateTime.parse(trimmed, DateTimeFormatter.RFC_1123_DATE_TIME); return Math.max(0L, Duration.between(ZonedDateTime.now(at.getZone()), at).toSeconds() + 1); } catch (DateTimeParseException e) { return null; } } private static Object parseOrNull(String text) { if (text == null || text.isEmpty()) return null; try { return MiniJson.parse(text); } catch (IllegalArgumentException e) { return null; } } private static String form(String value) { return URLEncoder.encode(value, StandardCharsets.UTF_8); } private static String queryString(Map query) { if (query == null || query.isEmpty()) return ""; StringJoiner joined = new StringJoiner("&", "?", ""); for (Map.Entry entry : query.entrySet()) { if (entry.getValue() != null) joined.add(form(entry.getKey()) + "=" + form(entry.getValue())); } return joined.toString(); } }