diff --git a/.github/workflows/maven-publish.yml b/.github/workflows/maven-publish.yml index 64b848b..e71b2f9 100644 --- a/.github/workflows/maven-publish.yml +++ b/.github/workflows/maven-publish.yml @@ -1,34 +1,45 @@ -# This workflow will build a package using Maven and then publish it to GitHub packages when a release is created -# For more information see: https://github.com/actions/setup-java/blob/main/docs/advanced-usage.md#apache-maven-with-a-settings-path - -name: Maven Package +name: Build and Publish on: + push: + branches: [main] + pull_request: release: types: [created] jobs: build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + - name: Build and test + run: ./gradlew build + publish: + if: github.event_name == 'release' + needs: build runs-on: ubuntu-latest permissions: contents: read packages: write - steps: - - uses: actions/checkout@v4 - - name: Set up JDK 11 - uses: actions/setup-java@v4 - with: - java-version: '11' - distribution: 'temurin' - server-id: github # Value of the distributionManagement/repository/id field of the pom.xml - settings-path: ${{ github.workspace }} # location for the settings.xml file - - - name: Build with Maven - run: mvn -B package --file pom.xml - - - name: Publish to GitHub Packages Apache Maven - run: mvn deploy -s $GITHUB_WORKSPACE/settings.xml - env: - GITHUB_TOKEN: ${{ github.token }} + - uses: actions/checkout@v4 + - name: Set up JDK 17 + uses: actions/setup-java@v4 + with: + java-version: '17' + distribution: 'temurin' + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4 + - name: Publish to GitHub Packages + run: ./gradlew publishMavenJavaPublicationToGitHubPackagesRepository + env: + GITHUB_ACTOR: ${{ github.actor }} + GITHUB_TOKEN: ${{ github.token }} diff --git a/README.md b/README.md index e8bcf3d..9d06f2f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,5 @@ # Arara Java SDK -[![Maven Central](https://img.shields.io/maven-central/v/com.ararahq/arara-java-sdk)](https://central.sonatype.com/artifact/com.ararahq/arara-java-sdk) [![Java](https://img.shields.io/badge/Java-17%2B-orange)](https://www.java.com/) [![License](https://img.shields.io/badge/License-MIT-green)](LICENSE) [![Docs](https://img.shields.io/badge/Docs-docs.ararahq.com-orange)](https://docs.ararahq.com) @@ -31,28 +30,63 @@ O Arara Java SDK é uma biblioteca leve e type-safe para integração perfeita c ## Instalação +O SDK é distribuído via **GitHub Packages** (não está publicado no Maven Central). O GitHub Packages exige autenticação mesmo para leitura: use seu usuário do GitHub e um personal access token com escopo `read:packages`. + ### Usando Gradle -Adicione a dependência ao seu `build.gradle`: +Adicione o repositório e a dependência ao seu `build.gradle`: ```gradle +repositories { + mavenCentral() + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/ararahq/arara-java-sdk") + credentials { + username = System.getenv("GITHUB_ACTOR") ?: project.findProperty("gpr.user") + password = System.getenv("GITHUB_TOKEN") ?: project.findProperty("gpr.key") + } + } +} + dependencies { - implementation 'com.ararahq:arara-java-sdk:1.8.0' + implementation 'com.ararahq:arara-java-sdk:1.8.1' } ``` +Defina as credenciais em `~/.gradle/gradle.properties` (`gpr.user` e `gpr.key`) ou nas variáveis de ambiente `GITHUB_ACTOR` e `GITHUB_TOKEN`. + ### Usando Maven -Adicione ao seu `pom.xml`: +Adicione o repositório ao seu `pom.xml`: ```xml + + + github + https://maven.pkg.github.com/ararahq/arara-java-sdk + + + com.ararahq arara-java-sdk - 1.8.0 + 1.8.1 ``` +E as credenciais no `~/.m2/settings.xml`: + +```xml + + + github + SEU_USUARIO_GITHUB + SEU_TOKEN_COM_READ_PACKAGES + + +``` + ## Início Rápido ### 1. Inicializar o SDK @@ -63,10 +97,25 @@ import com.ararahq.arara.sdk.Arara; // Criar o cliente Arara arara = Arara.builder() .apiKey("sua-chave-api-aqui") - .baseUrl("https://api.ararahq.com/api") + .baseUrl("https://api.ararahq.com") .build(); ``` +Timeouts e retries são configuráveis no builder (valores abaixo são os defaults): + +```java +Arara arara = Arara.builder() + .apiKey("sua-chave-api-aqui") + .connectTimeout(Duration.ofSeconds(10)) + .readTimeout(Duration.ofSeconds(30)) + .writeTimeout(Duration.ofSeconds(30)) + .callTimeout(Duration.ofMinutes(2)) + .maxRetries(3) + .build(); +``` + +Falhas de rede, respostas 5xx e 429 são reenviadas automaticamente com backoff exponencial até `maxRetries`, honrando o header `Retry-After` quando presente. + ### 2. Enviar uma Mensagem ```java @@ -248,6 +297,9 @@ try { } catch (AraraAuthException e) { // Tratar erros de autenticação (401, 403) System.err.println("Autenticação falhou: " + e.getMessage()); +} catch (AraraRateLimitException e) { + // Tratar rate limit (429) após esgotar os retries automáticos + System.err.println("Rate limit atingido. Aguarde: " + e.getRetryAfter()); } catch (AraraApiException e) { // Tratar erros da API com código de status e detalhes System.err.println("Erro da API " + e.getStatusCode() + ": " + e.getMessage()); diff --git a/gradle.properties b/gradle.properties index 6f0dc1a..96adf3c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,5 +1,5 @@ # SDK Versioning -araraSdkVersion=1.8.0 +araraSdkVersion=1.8.1 araraSdkGroup=com.ararahq # Dependency Versions diff --git a/src/main/java/com/ararahq/arara/sdk/Arara.java b/src/main/java/com/ararahq/arara/sdk/Arara.java index 8470cfb..b0a700a 100644 --- a/src/main/java/com/ararahq/arara/sdk/Arara.java +++ b/src/main/java/com/ararahq/arara/sdk/Arara.java @@ -8,6 +8,8 @@ import com.ararahq.arara.sdk.services.UserService; import lombok.Getter; +import java.time.Duration; + /** * Main entry point for the Arara Java SDK. * Use the Builder to configure and instantiate the client. @@ -54,6 +56,31 @@ public AraraBuilder baseUrl(String baseUrl) { return this; } + public AraraBuilder connectTimeout(Duration connectTimeout) { + configBuilder.connectTimeout(connectTimeout); + return this; + } + + public AraraBuilder readTimeout(Duration readTimeout) { + configBuilder.readTimeout(readTimeout); + return this; + } + + public AraraBuilder writeTimeout(Duration writeTimeout) { + configBuilder.writeTimeout(writeTimeout); + return this; + } + + public AraraBuilder callTimeout(Duration callTimeout) { + configBuilder.callTimeout(callTimeout); + return this; + } + + public AraraBuilder maxRetries(int maxRetries) { + configBuilder.maxRetries(maxRetries); + return this; + } + /** * Builds and initializes the Arara client. */ diff --git a/src/main/java/com/ararahq/arara/sdk/config/AraraConfig.java b/src/main/java/com/ararahq/arara/sdk/config/AraraConfig.java index b24e885..19a17fe 100644 --- a/src/main/java/com/ararahq/arara/sdk/config/AraraConfig.java +++ b/src/main/java/com/ararahq/arara/sdk/config/AraraConfig.java @@ -11,7 +11,7 @@ @Builder public class AraraConfig { @Builder.Default - String baseUrl = "https://api.ararahq.com/api"; + String baseUrl = "https://api.ararahq.com"; String apiKey; @@ -21,6 +21,12 @@ public class AraraConfig { @Builder.Default Duration readTimeout = Duration.ofSeconds(30); + @Builder.Default + Duration writeTimeout = Duration.ofSeconds(30); + + @Builder.Default + Duration callTimeout = Duration.ofMinutes(2); + @Builder.Default int maxRetries = 3; } diff --git a/src/main/java/com/ararahq/arara/sdk/exceptions/AraraRateLimitException.java b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraRateLimitException.java new file mode 100644 index 0000000..116ef03 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/exceptions/AraraRateLimitException.java @@ -0,0 +1,22 @@ +package com.ararahq.arara.sdk.exceptions; + +import com.ararahq.arara.sdk.models.AraraError; +import lombok.Getter; + +import java.time.Duration; + +/** + * Thrown when the API returns 429 Too Many Requests. + * Exposes the Retry-After hint returned by the server, when present. + */ +@Getter +public class AraraRateLimitException extends AraraApiException { + private static final int HTTP_TOO_MANY_REQUESTS = 429; + + private final Duration retryAfter; + + public AraraRateLimitException(AraraError errorDetails, Duration retryAfter) { + super(HTTP_TOO_MANY_REQUESTS, errorDetails); + this.retryAfter = retryAfter; + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java b/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java index 96380af..ea8de77 100644 --- a/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java +++ b/src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java @@ -5,9 +5,13 @@ import com.ararahq.arara.sdk.exceptions.AraraAuthException; import com.ararahq.arara.sdk.exceptions.AraraException; import com.ararahq.arara.sdk.exceptions.AraraNetworkException; +import com.ararahq.arara.sdk.exceptions.AraraRateLimitException; import com.ararahq.arara.sdk.interceptors.AuthInterceptor; +import com.ararahq.arara.sdk.interceptors.RetryInterceptor; import com.ararahq.arara.sdk.models.AraraError; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import okhttp3.MediaType; @@ -19,6 +23,7 @@ import org.slf4j.LoggerFactory; import java.io.IOException; +import java.util.Map; /** * Internal HTTP client based on OkHttp for making calls to the Arara API. @@ -40,7 +45,10 @@ public AraraHttpClient(AraraConfig config) { this.httpClient = new OkHttpClient.Builder() .connectTimeout(config.getConnectTimeout()) .readTimeout(config.getReadTimeout()) + .writeTimeout(config.getWriteTimeout()) + .callTimeout(config.getCallTimeout()) .addInterceptor(new AuthInterceptor(config.getApiKey())) + .addInterceptor(new RetryInterceptor(config.getMaxRetries())) .build(); } @@ -115,21 +123,45 @@ private T execute(Request request, Class responseType) { private void handleErrorResponse(Response response) throws IOException { String body = response.body() != null ? response.body().string() : ""; - AraraError errorDetails = null; - - try { - if (!body.isEmpty()) { - errorDetails = objectMapper.readValue(body, AraraError.class); - } - } catch (Exception e) { - log.warn("Could not parse API error: {}", body); - } + AraraError errorDetails = parseError(body); int code = response.code(); if (code == 401 || code == 403) { throw new AraraAuthException(errorDetails != null ? errorDetails.getMessage() : "Unauthorized"); } + if (code == 429) { + throw new AraraRateLimitException(errorDetails, + RetryInterceptor.parseRetryAfter(response.header("Retry-After"))); + } throw new AraraApiException(code, errorDetails); } + + private AraraError parseError(String body) { + if (body == null || body.isEmpty()) { + return null; + } + try { + JsonNode root = objectMapper.readTree(body); + JsonNode error = root.path("error"); + if (error.isObject()) { + return AraraError.builder() + .code(error.path("code").asText(null)) + .message(error.path("message").asText(null)) + .details(error.path("details").isObject() + ? objectMapper.convertValue(error.path("details"), + new TypeReference>() { + }) + : null) + .build(); + } + return AraraError.builder() + .code(error.isTextual() ? error.asText() : null) + .message(root.path("message").asText(null)) + .build(); + } catch (Exception e) { + log.warn("Could not parse API error: {}", body); + return null; + } + } } diff --git a/src/main/java/com/ararahq/arara/sdk/interceptors/RetryInterceptor.java b/src/main/java/com/ararahq/arara/sdk/interceptors/RetryInterceptor.java new file mode 100644 index 0000000..4fd1373 --- /dev/null +++ b/src/main/java/com/ararahq/arara/sdk/interceptors/RetryInterceptor.java @@ -0,0 +1,119 @@ +package com.ararahq.arara.sdk.interceptors; + +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.io.InterruptedIOException; +import java.time.Duration; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Interceptor that retries failed requests with exponential backoff. + * Retries on network failures, 5xx responses and 429 responses, + * honoring the Retry-After header when present. + */ +public class RetryInterceptor implements Interceptor { + private static final Logger log = LoggerFactory.getLogger(RetryInterceptor.class); + private static final long INITIAL_BACKOFF_MILLIS = 500L; + private static final long MAX_BACKOFF_MILLIS = 8_000L; + private static final int HTTP_TOO_MANY_REQUESTS = 429; + private static final int HTTP_INTERNAL_SERVER_ERROR = 500; + + private final int maxRetries; + + public RetryInterceptor(int maxRetries) { + this.maxRetries = maxRetries; + } + + @NotNull + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + for (int attempt = 0; ; attempt++) { + Response response; + try { + response = chain.proceed(request); + } catch (IOException e) { + if (attempt >= maxRetries) { + throw e; + } + log.warn("Request failed, retrying. [url={}, attempt={}, reason={}]", + request.url(), attempt + 1, e.getMessage()); + sleep(backoffMillis(attempt)); + continue; + } + + if (!isRetryable(response.code()) || attempt >= maxRetries) { + return response; + } + + long waitMillis = retryDelayMillis(response, attempt); + log.warn("Received retryable status, retrying. [url={}, status={}, attempt={}, waitMillis={}]", + request.url(), response.code(), attempt + 1, waitMillis); + response.close(); + sleep(waitMillis); + } + } + + /** + * Parses a Retry-After header value in seconds or HTTP-date format. + * + * @param headerValue Raw header value, possibly null. + * @return The wait duration, or null when absent or unparseable. + */ + public static Duration parseRetryAfter(String headerValue) { + if (headerValue == null || headerValue.isBlank()) { + return null; + } + try { + long seconds = Long.parseLong(headerValue.trim()); + return seconds >= 0 ? Duration.ofSeconds(seconds) : null; + } catch (NumberFormatException e) { + return parseHttpDate(headerValue.trim()); + } + } + + private static Duration parseHttpDate(String headerValue) { + try { + ZonedDateTime date = ZonedDateTime.parse(headerValue, DateTimeFormatter.RFC_1123_DATE_TIME); + Duration untilDate = Duration.between(ZonedDateTime.now(ZoneOffset.UTC), date); + return untilDate.isNegative() ? Duration.ZERO : untilDate; + } catch (DateTimeParseException e) { + return null; + } + } + + private boolean isRetryable(int statusCode) { + return statusCode == HTTP_TOO_MANY_REQUESTS || statusCode >= HTTP_INTERNAL_SERVER_ERROR; + } + + private long retryDelayMillis(Response response, int attempt) { + Duration retryAfter = parseRetryAfter(response.header("Retry-After")); + return retryAfter != null ? retryAfter.toMillis() : backoffMillis(attempt); + } + + private long backoffMillis(int attempt) { + return Math.min(INITIAL_BACKOFF_MILLIS << attempt, MAX_BACKOFF_MILLIS); + } + + private void sleep(long millis) throws IOException { + if (millis <= 0) { + return; + } + try { + Thread.sleep(millis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new InterruptedIOException("Retry wait interrupted"); + } + } +} diff --git a/src/main/java/com/ararahq/arara/sdk/models/AraraError.java b/src/main/java/com/ararahq/arara/sdk/models/AraraError.java index 6bf68ad..4df8f47 100644 --- a/src/main/java/com/ararahq/arara/sdk/models/AraraError.java +++ b/src/main/java/com/ararahq/arara/sdk/models/AraraError.java @@ -4,13 +4,17 @@ import lombok.Value; import lombok.extern.jackson.Jacksonized; +import java.util.Map; + /** * Internal model to map errors returned by the API. + * The API responds with a nested envelope: {"error": {"code": "...", "message": "...", "details": {}}}. */ @Value @Builder @Jacksonized public class AraraError { - String error; + String code; String message; + Map details; } diff --git a/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java b/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java index f67c0e1..e7fc1a9 100644 --- a/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java +++ b/src/main/java/com/ararahq/arara/sdk/services/CampaignService.java @@ -3,6 +3,7 @@ import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.CampaignRequest; import com.ararahq.arara.sdk.models.CampaignResponse; +import com.ararahq.arara.sdk.utils.ValidationUtils; import java.util.UUID; @@ -23,6 +24,9 @@ public CampaignService(AraraHttpClient httpClient) { * @return Summary of the created campaign. */ public CampaignResponse create(CampaignRequest request) { + ValidationUtils.checkNotNull(request, "request"); + ValidationUtils.checkNotNull(request.getContacts(), "contacts"); + request.getContacts().forEach(contact -> ValidationUtils.validateWhatsAppNumber(contact.getTo())); return httpClient.post("/v1/campaigns", request, CampaignResponse.class); } diff --git a/src/test/java/com/ararahq/arara/sdk/AraraTest.java b/src/test/java/com/ararahq/arara/sdk/AraraTest.java index b53ae4b..e923bac 100644 --- a/src/test/java/com/ararahq/arara/sdk/AraraTest.java +++ b/src/test/java/com/ararahq/arara/sdk/AraraTest.java @@ -3,6 +3,8 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import java.time.Duration; + import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -27,4 +29,21 @@ void shouldInitializeServices() { void shouldThrowExceptionWithoutApiKey() { assertThrows(RuntimeException.class, () -> Arara.builder().build()); } + + @Test + @DisplayName("should build with timeouts and retries configured") + void shouldBuildWithTimeoutsAndRetries() { + Arara arara = Arara.builder() + .apiKey("test-key") + .baseUrl("https://api.example.com") + .connectTimeout(Duration.ofSeconds(5)) + .readTimeout(Duration.ofSeconds(15)) + .writeTimeout(Duration.ofSeconds(15)) + .callTimeout(Duration.ofSeconds(60)) + .maxRetries(1) + .build(); + + assertNotNull(arara.getMessages()); + assertNotNull(arara.getCampaigns()); + } } diff --git a/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java b/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java index f8002f5..4ffa836 100644 --- a/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java +++ b/src/test/java/com/ararahq/arara/sdk/http/AraraHttpClientTest.java @@ -4,7 +4,7 @@ import com.ararahq.arara.sdk.exceptions.AraraApiException; import com.ararahq.arara.sdk.exceptions.AraraAuthException; import com.ararahq.arara.sdk.exceptions.AraraNetworkException; -import com.ararahq.arara.sdk.models.AraraError; +import com.ararahq.arara.sdk.exceptions.AraraRateLimitException; import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterEach; @@ -13,8 +13,11 @@ import org.junit.jupiter.api.Test; import java.io.IOException; +import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @DisplayName("AraraHttpClient Tests") @@ -27,12 +30,7 @@ class AraraHttpClientTest { void setUp() throws IOException { mockWebServer = new MockWebServer(); mockWebServer.start(); - - AraraConfig config = AraraConfig.builder() - .baseUrl(mockWebServer.url("/").toString()) - .apiKey("test-key") - .build(); - client = new AraraHttpClient(config); + client = clientWithRetries(0); } @AfterEach @@ -40,6 +38,15 @@ void tearDown() throws IOException { mockWebServer.shutdown(); } + private AraraHttpClient clientWithRetries(int maxRetries) { + AraraConfig config = AraraConfig.builder() + .baseUrl(mockWebServer.url("/").toString()) + .apiKey("test-key") + .maxRetries(maxRetries) + .build(); + return new AraraHttpClient(config); + } + @Test @DisplayName("should handle successful GET") void shouldHandleSuccessfulGet() { @@ -85,6 +92,146 @@ void shouldHandleNetworkFailure() throws IOException { assertThrows(AraraNetworkException.class, () -> client.get("test", TestResponse.class)); } + @Test + @DisplayName("should throw AraraRateLimitException with retry after on 429") + void shouldThrowRateLimitExceptionOn429() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(429) + .setHeader("Retry-After", "7") + .setBody("{\"error\":{\"code\":\"RATE_LIMITED\",\"message\":\"Too many requests\"}}")); + + AraraRateLimitException exception = assertThrows(AraraRateLimitException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals(429, exception.getStatusCode()); + assertEquals(Duration.ofSeconds(7), exception.getRetryAfter()); + assertEquals("RATE_LIMITED", exception.getErrorDetails().getCode()); + assertEquals("Too many requests", exception.getErrorDetails().getMessage()); + } + + @Test + @DisplayName("should throw AraraRateLimitException without retry after when header is absent") + void shouldThrowRateLimitExceptionWithoutRetryAfter() { + mockWebServer.enqueue(new MockResponse().setResponseCode(429)); + + AraraRateLimitException exception = assertThrows(AraraRateLimitException.class, + () -> client.get("test", TestResponse.class)); + + assertNull(exception.getRetryAfter()); + } + + @Test + @DisplayName("should parse nested error envelope with details") + void shouldParseNestedErrorEnvelope() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(400) + .setBody("{\"error\":{\"code\":\"INSUFFICIENT_CREDITS\"," + + "\"message\":\"Not enough credits\"," + + "\"details\":{\"balance\":0}}}")); + + AraraApiException exception = assertThrows(AraraApiException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals("INSUFFICIENT_CREDITS", exception.getErrorDetails().getCode()); + assertEquals("Not enough credits", exception.getErrorDetails().getMessage()); + assertEquals(0, exception.getErrorDetails().getDetails().get("balance")); + } + + @Test + @DisplayName("should fall back to flat error format") + void shouldFallBackToFlatErrorFormat() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(400) + .setBody("{\"error\":\"INVALID_INPUT\",\"message\":\"Invalid payload\"}")); + + AraraApiException exception = assertThrows(AraraApiException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals("INVALID_INPUT", exception.getErrorDetails().getCode()); + assertEquals("Invalid payload", exception.getErrorDetails().getMessage()); + } + + @Test + @DisplayName("should keep exception when error body is not valid JSON") + void shouldHandleUnparseableErrorBody() { + mockWebServer.enqueue(new MockResponse() + .setResponseCode(500) + .setBody("upstream exploded")); + + AraraApiException exception = assertThrows(AraraApiException.class, + () -> client.get("test", TestResponse.class)); + + assertEquals(500, exception.getStatusCode()); + assertNull(exception.getErrorDetails()); + } + + @Test + @DisplayName("should retry on 500 and succeed on next attempt") + void shouldRetryOn500AndSucceed() throws InterruptedException { + AraraHttpClient retryingClient = clientWithRetries(2); + mockWebServer.enqueue(new MockResponse().setResponseCode(500)); + mockWebServer.enqueue(new MockResponse() + .setBody("{\"name\":\"Recovered\"}") + .setResponseCode(200)); + + TestResponse response = retryingClient.get("test", TestResponse.class); + + assertEquals("Recovered", response.name); + assertEquals(2, mockWebServer.getRequestCount()); + assertNotNull(mockWebServer.takeRequest()); + assertNotNull(mockWebServer.takeRequest()); + } + + @Test + @DisplayName("should retry on 429 honoring Retry-After header") + void shouldRetryOn429HonoringRetryAfter() { + AraraHttpClient retryingClient = clientWithRetries(1); + mockWebServer.enqueue(new MockResponse() + .setResponseCode(429) + .setHeader("Retry-After", "0")); + mockWebServer.enqueue(new MockResponse() + .setBody("{\"name\":\"AfterLimit\"}") + .setResponseCode(200)); + + TestResponse response = retryingClient.get("test", TestResponse.class); + + assertEquals("AfterLimit", response.name); + assertEquals(2, mockWebServer.getRequestCount()); + } + + @Test + @DisplayName("should not retry when max retries is zero") + void shouldNotRetryWhenMaxRetriesIsZero() { + mockWebServer.enqueue(new MockResponse().setResponseCode(500)); + + assertThrows(AraraApiException.class, () -> client.get("test", TestResponse.class)); + assertEquals(1, mockWebServer.getRequestCount()); + } + + @Test + @DisplayName("should throw after exhausting retries") + void shouldThrowAfterExhaustingRetries() { + AraraHttpClient retryingClient = clientWithRetries(1); + mockWebServer.enqueue(new MockResponse().setResponseCode(503)); + mockWebServer.enqueue(new MockResponse().setResponseCode(503)); + + AraraApiException exception = assertThrows(AraraApiException.class, + () -> retryingClient.get("test", TestResponse.class)); + + assertEquals(503, exception.getStatusCode()); + assertEquals(2, mockWebServer.getRequestCount()); + } + + @Test + @DisplayName("should not retry on 4xx other than 429") + void shouldNotRetryOnClientError() { + AraraHttpClient retryingClient = clientWithRetries(2); + mockWebServer.enqueue(new MockResponse().setResponseCode(404)); + + assertThrows(AraraApiException.class, () -> retryingClient.get("test", TestResponse.class)); + assertEquals(1, mockWebServer.getRequestCount()); + } + static class TestResponse { public String name; diff --git a/src/test/java/com/ararahq/arara/sdk/interceptors/RetryInterceptorTest.java b/src/test/java/com/ararahq/arara/sdk/interceptors/RetryInterceptorTest.java new file mode 100644 index 0000000..79e5649 --- /dev/null +++ b/src/test/java/com/ararahq/arara/sdk/interceptors/RetryInterceptorTest.java @@ -0,0 +1,69 @@ +package com.ararahq.arara.sdk.interceptors; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@DisplayName("RetryInterceptor Tests") +class RetryInterceptorTest { + + @Test + @DisplayName("should parse Retry-After in seconds") + void shouldParseRetryAfterSeconds() { + assertEquals(Duration.ofSeconds(30), RetryInterceptor.parseRetryAfter("30")); + } + + @Test + @DisplayName("should parse Retry-After with surrounding whitespace") + void shouldParseRetryAfterWithWhitespace() { + assertEquals(Duration.ofSeconds(5), RetryInterceptor.parseRetryAfter(" 5 ")); + } + + @Test + @DisplayName("should return null for negative Retry-After") + void shouldReturnNullForNegativeRetryAfter() { + assertNull(RetryInterceptor.parseRetryAfter("-1")); + } + + @Test + @DisplayName("should return null for null or blank header") + void shouldReturnNullForNullOrBlankHeader() { + assertNull(RetryInterceptor.parseRetryAfter(null)); + assertNull(RetryInterceptor.parseRetryAfter("")); + assertNull(RetryInterceptor.parseRetryAfter(" ")); + } + + @Test + @DisplayName("should return null for unparseable header") + void shouldReturnNullForUnparseableHeader() { + assertNull(RetryInterceptor.parseRetryAfter("soon")); + } + + @Test + @DisplayName("should parse Retry-After in HTTP-date format") + void shouldParseRetryAfterHttpDate() { + String futureDate = DateTimeFormatter.RFC_1123_DATE_TIME + .format(ZonedDateTime.now(ZoneOffset.UTC).plusSeconds(60)); + + Duration parsed = RetryInterceptor.parseRetryAfter(futureDate); + + assertTrue(parsed.getSeconds() > 50 && parsed.getSeconds() <= 60); + } + + @Test + @DisplayName("should clamp past HTTP-date to zero") + void shouldClampPastHttpDateToZero() { + String pastDate = DateTimeFormatter.RFC_1123_DATE_TIME + .format(ZonedDateTime.now(ZoneOffset.UTC).minusSeconds(60)); + + assertEquals(Duration.ZERO, RetryInterceptor.parseRetryAfter(pastDate)); + } +} diff --git a/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java b/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java index 375e50a..0509d90 100644 --- a/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java +++ b/src/test/java/com/ararahq/arara/sdk/services/CampaignServiceTest.java @@ -1,5 +1,6 @@ package com.ararahq.arara.sdk.services; +import com.ararahq.arara.sdk.exceptions.AraraException; import com.ararahq.arara.sdk.http.AraraHttpClient; import com.ararahq.arara.sdk.models.CampaignContactRequest; import com.ararahq.arara.sdk.models.CampaignRequest; @@ -15,8 +16,10 @@ import java.util.UUID; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; /** @@ -145,6 +148,63 @@ void shouldCallCorrectEndpointWithUUID() { verify(httpClient, times(1)).get("/v1/campaigns/" + campaignId.toString(), CampaignResponse.class); } + @Test + @DisplayName("should reject null campaign request") + void shouldRejectNullCampaignRequest() { + assertThrows(AraraException.class, () -> campaignService.create(null)); + verifyNoInteractions(httpClient); + } + + @Test + @DisplayName("should reject campaign without contacts") + void shouldRejectCampaignWithoutContacts() { + CampaignRequest request = CampaignRequest.builder() + .name("No Contacts Campaign") + .templateName("template") + .sender("whatsapp:+551140001000") + .build(); + + assertThrows(AraraException.class, () -> campaignService.create(request)); + verifyNoInteractions(httpClient); + } + + @Test + @DisplayName("should reject contact without whatsapp prefix") + void shouldRejectContactWithoutWhatsappPrefix() { + CampaignContactRequest invalidContact = CampaignContactRequest.builder() + .to("+5511999998888") + .build(); + CampaignRequest request = CampaignRequest.builder() + .name("Invalid Contact Campaign") + .templateName("template") + .sender("whatsapp:+551140001000") + .contacts(Arrays.asList(invalidContact)) + .build(); + + assertThrows(AraraException.class, () -> campaignService.create(request)); + verifyNoInteractions(httpClient); + } + + @Test + @DisplayName("should reject campaign when any contact is invalid") + void shouldRejectCampaignWhenAnyContactIsInvalid() { + CampaignContactRequest validContact = CampaignContactRequest.builder() + .to("whatsapp:+5511999998888") + .build(); + CampaignContactRequest invalidContact = CampaignContactRequest.builder() + .to("5511988887777") + .build(); + CampaignRequest request = CampaignRequest.builder() + .name("Mixed Contacts Campaign") + .templateName("template") + .sender("whatsapp:+551140001000") + .contacts(Arrays.asList(validContact, invalidContact)) + .build(); + + assertThrows(AraraException.class, () -> campaignService.create(request)); + verifyNoInteractions(httpClient); + } + @Test @DisplayName("should create then retrieve campaign") void shouldCreateThenRetrieveCampaign() {