diff --git a/src/main/java/com/controlresell/sdk/ControlResell.java b/src/main/java/com/controlresell/sdk/ControlResell.java index f74aa7a..a4e058c 100644 --- a/src/main/java/com/controlresell/sdk/ControlResell.java +++ b/src/main/java/com/controlresell/sdk/ControlResell.java @@ -160,6 +160,11 @@ public T call(boolean write, HttpCall 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 callOnce(HttpCall call) { + return retrier.execute(true, false, call); + } + /** The seller the API key acts for. */ public MeResource me() { return new MeResource(); } @@ -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) { diff --git a/src/main/java/com/controlresell/sdk/Retrier.java b/src/main/java/com/controlresell/sdk/Retrier.java index 1a85a5a..8ded611 100644 --- a/src/main/java/com/controlresell/sdk/Retrier.java +++ b/src/main/java/com/controlresell/sdk/Retrier.java @@ -27,6 +27,16 @@ final class Retrier { } T execute(boolean write, ControlResell.HttpCall 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 execute(boolean write, boolean replayable, ControlResell.HttpCall call) { Map headers = new HashMap<>(); if (write) headers.put(IDEMPOTENCY_KEY_HEADER, UUID.randomUUID().toString()); for (int attempt = 0; ; attempt++) { @@ -35,11 +45,13 @@ T execute(boolean write, ControlResell.HttpCall 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)); } diff --git a/src/test/java/com/controlresell/sdk/ControlResellTest.java b/src/test/java/com/controlresell/sdk/ControlResellTest.java index e27449e..1e1eaf6 100644 --- a/src/test/java/com/controlresell/sdk/ControlResellTest.java +++ b/src/test/java/com/controlresell/sdk/ControlResellTest.java @@ -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()); + } }