Skip to content
Merged
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
12 changes: 10 additions & 2 deletions src/main/java/com/controlresell/sdk/ControlResell.java
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,11 @@ public <T> T call(boolean write, HttpCall<T> call) {
return retrier.execute(write, call);
}

/** Like {@link #call} for a write the API does not deduplicate: see {@link Retrier#execute(boolean, boolean, HttpCall)}. */
private <T> T callOnce(HttpCall<T> call) {
return retrier.execute(true, false, call);
}

/** The seller the API key acts for. */
public MeResource me() { return new MeResource(); }

Expand Down Expand Up @@ -591,8 +596,11 @@ public WebhookSecret rotateSecret(UUID id, Long expiresInHours, String idempoten
return call(false, h -> api.rotateWebhookSecret(id, key, body));
}

/** Sends a {@code webhook.test} event to the endpoint now and returns how it answered. */
public WebhookTestResult test(UUID id) { return call(true, h -> api.testWebhookEndpoint(id, h)); }
/**
* Sends a {@code webhook.test} event to the endpoint now and returns how it answered. The API ignores the
* {@code Idempotency-Key} of a test, so it is never replayed after a 5xx or a network error (only on a 429): a replay would send a second event.
*/
public WebhookTestResult test(UUID id) { return callOnce(h -> api.testWebhookEndpoint(id, h)); }

/** One page of the deliveries of an endpoint over the last 7 days, the most recent first; filters may be {@code null}. */
public WebhookDeliveryPage deliveries(UUID id, Integer limit, String cursor, String status, String type) {
Expand Down
16 changes: 14 additions & 2 deletions src/main/java/com/controlresell/sdk/Retrier.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ final class Retrier {
}

<T> T execute(boolean write, ControlResell.HttpCall<T> call) {
return execute(write, true, call);
}

/**
* @param replayable false for a call that sends something real and whose {@code Idempotency-Key} the API ignores
* (the webhook test): it is retried on a 429 only, since any other failure, a network error included (the JDK
* client reports some failures after the send as a {@code ConnectException}), may come after the request
* reached the server
*/
<T> T execute(boolean write, boolean replayable, ControlResell.HttpCall<T> call) {
Map<String, String> headers = new HashMap<>();
if (write) headers.put(IDEMPOTENCY_KEY_HEADER, UUID.randomUUID().toString());
for (int attempt = 0; ; attempt++) {
Expand All @@ -35,11 +45,13 @@ <T> T execute(boolean write, ControlResell.HttpCall<T> call) {
return call.call(headers);
} catch (ApiException e) {
if (e.getCode() == 0) {
if (last) throw new ControlResellError.Connection(e.getCause() != null ? e.getCause() : e);
if (last || !replayable) {
throw new ControlResellError.Connection(e.getCause() != null ? e.getCause() : e);
}
pause(policy.backoff(attempt));
continue;
}
if (last || !shouldRetry(e)) throw Errors.of(e, mapper);
if (last || (!replayable && e.getCode() != 429) || !shouldRetry(e)) throw Errors.of(e, mapper);
Long retryAfter = Errors.retryAfter(e);
pause(retryAfter != null ? policy.capped(Duration.ofSeconds(retryAfter)) : policy.backoff(attempt));
}
Expand Down
42 changes: 42 additions & 0 deletions src/test/java/com/controlresell/sdk/ControlResellTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -505,4 +505,46 @@ void webhooksTestPostsWithAKeyAndReadsTheResult() throws Exception {
assertEquals("/api/public/v1/webhook-endpoints/" + ENDPOINT_ID + "/test", exchanges.get(0).getRequestURI().getPath());
assertFalse(keys.get(0) == null || keys.get(0).isEmpty());
}

@Test
void webhooksTestIsNeverReplayedAfterA5xxButIsAfterA429() throws Exception {
for (int status : new int[] {500, 502, 503, 504}) {
exchanges.clear();
ControlResell sdk = client(n -> new Reply(status, "{\"error\":{\"code\":\"unavailable\",\"message\":\"m\",\"params\":{},\"requestId\":\"r\"}}"));
assertThrows(ControlResellError.class, () -> sdk.webhooks().test(java.util.UUID.fromString(ENDPOINT_ID)));
assertEquals(1, exchanges.size(), "status " + status + " must not be replayed");
server.stop(0);
}
exchanges.clear();
ControlResell busy = client(n -> n == 1
? new Reply(429, "{\"error\":{\"code\":\"webhook_endpoint_busy\",\"message\":\"m\",\"params\":{},\"requestId\":\"r\"}}", "Retry-After", "0")
: new Reply(200, "{\"success\":true,\"statusCode\":200,\"durationMs\":12,\"error\":null}"));
assertTrue(busy.webhooks().test(java.util.UUID.fromString(ENDPOINT_ID)).getSuccess());
assertEquals(2, exchanges.size());
server.stop(0);
exchanges.clear();
ControlResell other = client(n -> n == 1
? new Reply(503, "{\"error\":{\"code\":\"unavailable\",\"message\":\"m\",\"params\":{},\"requestId\":\"r\"}}")
: new Reply(200, ME));
other.me().get();
assertEquals(2, exchanges.size(), "other calls keep the retry on 503");
}

@Test
void webhooksTestIsNotReplayedAfterALostConnection() throws Exception {
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
java.util.concurrent.atomic.AtomicInteger hits = new java.util.concurrent.atomic.AtomicInteger();
server.createContext("/", exchange -> {
hits.incrementAndGet();
exchange.close();
});
server.start();
ControlResell sdk = ControlResell.builder()
.apiKey(KEY)
.baseUrl("http://127.0.0.1:" + server.getAddress().getPort())
.retry(new RetryPolicy(2, Duration.ofMillis(1), Duration.ofMillis(5)))
.build();
assertThrows(ControlResellError.Connection.class, () -> sdk.webhooks().test(java.util.UUID.fromString(ENDPOINT_ID)));
assertEquals(1, hits.get());
}
}
Loading