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
53 changes: 32 additions & 21 deletions .github/workflows/maven-publish.yml
Original file line number Diff line number Diff line change
@@ -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 }}
64 changes: 58 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -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)
Expand Down Expand Up @@ -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
<repositories>
<repository>
<id>github</id>
<url>https://maven.pkg.github.com/ararahq/arara-java-sdk</url>
</repository>
</repositories>

<dependency>
<groupId>com.ararahq</groupId>
<artifactId>arara-java-sdk</artifactId>
<version>1.8.0</version>
<version>1.8.1</version>
</dependency>
```

E as credenciais no `~/.m2/settings.xml`:

```xml
<servers>
<server>
<id>github</id>
<username>SEU_USUARIO_GITHUB</username>
<password>SEU_TOKEN_COM_READ_PACKAGES</password>
</server>
</servers>
```

## Início Rápido

### 1. Inicializar o SDK
Expand All @@ -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
Expand Down Expand Up @@ -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());
Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# SDK Versioning
araraSdkVersion=1.8.0
araraSdkVersion=1.8.1
araraSdkGroup=com.ararahq

# Dependency Versions
Expand Down
27 changes: 27 additions & 0 deletions src/main/java/com/ararahq/arara/sdk/Arara.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
*/
Expand Down
8 changes: 7 additions & 1 deletion src/main/java/com/ararahq/arara/sdk/config/AraraConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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;
}
Original file line number Diff line number Diff line change
@@ -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;
}
}
50 changes: 41 additions & 9 deletions src/main/java/com/ararahq/arara/sdk/http/AraraHttpClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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.
Expand All @@ -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();
}

Expand Down Expand Up @@ -115,21 +123,45 @@ private <T> T execute(Request request, Class<T> 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<Map<String, Object>>() {
})
: 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;
}
}
}
Loading
Loading