feat(clients): add Python, Go, and Java client libraries (BIT-14250)

Zero-dependency clients for errors.bitreport.pt following the same
patterns as clients/node and clients/php: batch size 25, 5 s flush
interval, 8 s HTTP timeout, fire-and-forget, env-var config.

Each client ships with unit tests backed by an embedded HTTP server
(no mocks), an example file, and a build manifest (pyproject.toml,
go.mod, pom.xml).

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
David SantosandClaude Sonnet 4.6 committed 2026-04-27 10:08:11 +00:00
1 parent 8bb49ce32b
commit da57d2a444
12 files changed
+1653

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
import pt.bitreport.errors.ErrorReporter;
import java.util.Map;
/**
* Basic usage example for the BitReport Java error reporter.
*
* Compile and run:
* javac -cp path/to/bitreport-errors-1.0.0.jar BasicUsage.java
* ERROR_REPORTING_TOKEN=your_token java -cp .:path/to/bitreport-errors-1.0.0.jar BasicUsage
*/
public class BasicUsage {
public static void main(String[] args) {
ErrorReporter.init(ErrorReporter.Config.builder()
.token(System.getenv("ERROR_REPORTING_TOKEN"))
.projectName("My Java App")
.projectSlug("my-java-app")
.build());
// Always flush before the JVM exits
Runtime.getRuntime().addShutdownHook(new Thread(ErrorReporter::flush));
// Report a plain message
ErrorReporter.reportMessage("Application started", "info", null);
// Report a warning with context
ErrorReporter.reportMessage("Cache miss", "warning", Map.of("cache_key", "user:42"));
// Report a caught exception
try {
int result = Integer.parseInt("not-a-number");
} catch (NumberFormatException e) {
ErrorReporter.reportError(e, Map.of("input", "not-a-number"));
}
// Flush synchronously so the example does not exit with pending events
ErrorReporter.flush();
System.out.println("Events sent. Check your errors.bitreport.pt dashboard.");
}
}
+46
View File
@@ -0,0 +1,46 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>pt.bitreport</groupId>
<artifactId>bitreport-errors</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<name>BitReport Error Reporter</name>
<description>Lightweight Java client for errors.bitreport.pt</description>
<url>https://errors.bitreport.pt</url>
<properties>
<java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>5.10.2</junit.version>
</properties>
<dependencies>
<!-- No runtime dependencies — zero external deps is a design constraint -->
<!-- Test-only -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,366 @@
package pt.bitreport.errors;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* BitReport Error Reporter — Java client for errors.bitreport.pt ingest API.
*
* <p>Drop this file into any Java 11+ project. Zero external dependencies.
*
* <p>Usage:
* <pre>{@code
* ErrorReporter.init(ErrorReporter.Config.builder()
* .token(System.getenv("ERROR_REPORTING_TOKEN"))
* .projectSlug("my-java-app")
* .build());
*
* try {
* riskyOperation();
* } catch (Exception e) {
* ErrorReporter.reportError(e, Map.of("operation", "riskyOperation"));
* }
*
* // Before shutdown:
* ErrorReporter.flush();
* }</pre>
*
* <p>Environment variables:
* <ul>
* <li>{@code ERROR_REPORTING_TOKEN} — ingest API key (required)</li>
* <li>{@code ERROR_REPORTING_ENDPOINT} — base URL (default: https://errors.bitreport.pt)</li>
* <li>{@code ERROR_REPORTING_DISABLED} — set to "1" to disable</li>
* <li>{@code ERROR_REPORTING_PROJECT_NAME} — display name (optional)</li>
* <li>{@code ERROR_REPORTING_PROJECT_SLUG} — stable product slug (optional)</li>
* <li>{@code ERROR_REPORTING_GITEA_REPO} — canonical owner/repo on Gitea (optional)</li>
* </ul>
*/
public final class ErrorReporter {
private static final String DEFAULT_ENDPOINT = "https://errors.bitreport.pt";
private static final int BATCH_SIZE = 25;
private static final long FLUSH_MS = 5_000L;
private static final int TIMEOUT_MS = 8_000;
private static final DateTimeFormatter ISO_FMT =
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
// --- Config ---
public static final class Config {
final String token;
final String endpoint;
final boolean disabled;
final String projectName;
final String projectSlug;
final String giteaRepo;
private Config(Builder b) {
this.token = coalesce(b.token, env("ERROR_REPORTING_TOKEN"));
this.endpoint = stripTrailingSlash(
coalesce(b.endpoint, env("ERROR_REPORTING_ENDPOINT"), DEFAULT_ENDPOINT));
this.disabled = b.disabled || "1".equals(env("ERROR_REPORTING_DISABLED"));
this.projectName = coalesce(b.projectName, env("ERROR_REPORTING_PROJECT_NAME"));
this.projectSlug = coalesce(b.projectSlug, env("ERROR_REPORTING_PROJECT_SLUG"));
this.giteaRepo = coalesce(b.giteaRepo, env("ERROR_REPORTING_GITEA_REPO"));
}
public static Builder builder() { return new Builder(); }
public static final class Builder {
private String token = "";
private String endpoint = "";
private boolean disabled = false;
private String projectName = "";
private String projectSlug = "";
private String giteaRepo = "";
public Builder token(String v) { this.token = v != null ? v : ""; return this; }
public Builder endpoint(String v) { this.endpoint = v != null ? v : ""; return this; }
public Builder disabled(boolean v) { this.disabled = v; return this; }
public Builder projectName(String v) { this.projectName = v != null ? v : ""; return this; }
public Builder projectSlug(String v) { this.projectSlug = v != null ? v : ""; return this; }
public Builder giteaRepo(String v) { this.giteaRepo = v != null ? v : ""; return this; }
public Config build() { return new Config(this); }
}
}
// --- Shared state ---
private static final AtomicReference<Config> CONFIG = new AtomicReference<>(
Config.builder().build());
private static final List<Map<String, Object>> QUEUE =
Collections.synchronizedList(new ArrayList<>());
private static final ScheduledExecutorService SCHEDULER =
Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "bitreport-flush");
t.setDaemon(true);
return t;
});
private static final AtomicBoolean TIMER_RUNNING = new AtomicBoolean(false);
private static volatile ScheduledFuture<?> FLUSH_TASK = null;
// prevent instantiation
private ErrorReporter() {}
// --- Public API ---
/** Initialise the reporter. Call once at startup. */
public static void init(Config config) {
CONFIG.set(config);
}
/** Report a {@link Throwable} with optional extra context. */
public static void reportError(Throwable t, Map<String, Object> extraContext) {
Config c = CONFIG.get();
if (c.disabled || c.token.isEmpty() || t == null) return;
Map<String, Object> ctx = new LinkedHashMap<>();
ctx.put("error_type", t.getClass().getSimpleName());
// Extract deepest stack frame outside this class
StackTraceElement caller = findCaller(t.getStackTrace());
if (caller != null) {
ctx.put("file_path", caller.getFileName() != null ? caller.getFileName() : "");
ctx.put("line_number", caller.getLineNumber());
}
addProjectFields(ctx, c);
if (extraContext != null) ctx.putAll(extraContext);
String stack = stackTraceString(t);
Map<String, Object> event = new LinkedHashMap<>();
event.put("schema_version", 1);
event.put("occurred_at", nowISO());
event.put("level", "error");
event.put("message", t.getMessage() != null ? t.getMessage() : t.toString());
event.put("stacktrace", stack);
event.put("context", ctx);
enqueue(event);
}
/**
* Report a plain message.
*
* @param message the message text
* @param level one of: "error", "warning", "info", "critical"
* @param context optional key-value pairs (may be null)
*/
public static void reportMessage(String message, String level, Map<String, Object> context) {
Config c = CONFIG.get();
if (c.disabled || c.token.isEmpty()) return;
Map<String, Object> ctx = new LinkedHashMap<>();
addProjectFields(ctx, c);
if (context != null) ctx.putAll(context);
Map<String, Object> event = new LinkedHashMap<>();
event.put("schema_version", 1);
event.put("occurred_at", nowISO());
event.put("level", level != null && !level.isEmpty() ? level : "error");
event.put("message", message);
if (!ctx.isEmpty()) event.put("context", ctx);
enqueue(event);
}
/** Flush all queued events synchronously. Call before JVM shutdown. */
public static void flush() {
cancelTimer();
List<Map<String, Object>> snapshot;
synchronized (QUEUE) {
snapshot = new ArrayList<>(QUEUE);
QUEUE.clear();
}
sendInBatches(snapshot);
}
// --- internals ---
private static void enqueue(Map<String, Object> event) {
List<Map<String, Object>> batch = null;
synchronized (QUEUE) {
QUEUE.add(event);
if (QUEUE.size() >= BATCH_SIZE) {
batch = new ArrayList<>(QUEUE);
QUEUE.clear();
}
}
if (batch != null) {
final List<Map<String, Object>> toSend = batch;
SCHEDULER.submit(() -> sendInBatches(toSend));
} else {
scheduleFlushTimer();
}
}
private static synchronized void scheduleFlushTimer() {
if (FLUSH_TASK == null || FLUSH_TASK.isDone()) {
FLUSH_TASK = SCHEDULER.schedule(() -> {
List<Map<String, Object>> batch;
synchronized (QUEUE) {
batch = new ArrayList<>(QUEUE);
QUEUE.clear();
}
sendInBatches(batch);
}, FLUSH_MS, TimeUnit.MILLISECONDS);
}
}
private static synchronized void cancelTimer() {
if (FLUSH_TASK != null) {
FLUSH_TASK.cancel(false);
FLUSH_TASK = null;
}
}
private static void sendInBatches(List<Map<String, Object>> events) {
if (events.isEmpty()) return;
for (int i = 0; i < events.size(); i += BATCH_SIZE) {
int end = Math.min(i + BATCH_SIZE, events.size());
sendBatch(events.subList(i, end));
}
}
private static void sendBatch(List<Map<String, Object>> events) {
if (events.isEmpty()) return;
Config c = CONFIG.get();
try {
String body = toJson(Map.of("events", events));
byte[] payload = body.getBytes(StandardCharsets.UTF_8);
URL url = new URL(c.endpoint + "/v1/ingest/events");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Authorization", "Bearer " + c.token);
conn.setConnectTimeout(TIMEOUT_MS);
conn.setReadTimeout(TIMEOUT_MS);
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(payload);
}
conn.getResponseCode(); // consume response so the connection is reusable
conn.disconnect();
} catch (Exception ignored) {
// fire-and-forget: never crash the host app
}
}
// --- helpers ---
private static void addProjectFields(Map<String, Object> ctx, Config c) {
if (!c.projectName.isEmpty()) ctx.put("project_name", c.projectName);
if (!c.projectSlug.isEmpty()) ctx.put("project_slug", c.projectSlug);
if (!c.giteaRepo.isEmpty()) ctx.put("gitea_repo", c.giteaRepo);
}
private static StackTraceElement findCaller(StackTraceElement[] frames) {
String thisClass = ErrorReporter.class.getName();
for (StackTraceElement f : frames) {
if (!f.getClassName().equals(thisClass)) return f;
}
return frames.length > 0 ? frames[0] : null;
}
private static String stackTraceString(Throwable t) {
StringBuilder sb = new StringBuilder();
sb.append(t.toString()).append('\n');
for (StackTraceElement e : t.getStackTrace()) {
sb.append("\tat ").append(e).append('\n');
}
Throwable cause = t.getCause();
if (cause != null) {
sb.append("Caused by: ").append(stackTraceString(cause));
}
return sb.toString().trim();
}
private static String nowISO() {
return ISO_FMT.format(Instant.now());
}
private static String env(String key) {
String v = System.getenv(key);
return v != null ? v.trim() : "";
}
private static String coalesce(String... vals) {
for (String v : vals) {
if (v != null && !v.isEmpty()) return v;
}
return "";
}
private static String stripTrailingSlash(String s) {
return s.endsWith("/") ? s.substring(0, s.length() - 1) : s;
}
// Minimal JSON serialiser — supports: String, Number, Boolean, null, Map, List
@SuppressWarnings("unchecked")
static String toJson(Object value) {
if (value == null) return "null";
if (value instanceof Boolean) return value.toString();
if (value instanceof Number) return value.toString();
if (value instanceof String) return jsonString((String) value);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (!first) sb.append(',');
sb.append(jsonString(entry.getKey())).append(':').append(toJson(entry.getValue()));
first = false;
}
return sb.append('}').toString();
}
if (value instanceof List) {
List<Object> list = (List<Object>) value;
StringBuilder sb = new StringBuilder("[");
for (int i = 0; i < list.size(); i++) {
if (i > 0) sb.append(',');
sb.append(toJson(list.get(i)));
}
return sb.append(']').toString();
}
return jsonString(value.toString());
}
private static String jsonString(String s) {
StringBuilder sb = new StringBuilder("\"");
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch == '"') {
sb.append("\\\"");
} else if (ch == '\\') {
sb.append("\\\\");
} else if (ch == '\n') {
sb.append("\\n");
} else if (ch == '\r') {
sb.append("\\r");
} else if (ch == '\t') {
sb.append("\\t");
} else if (ch < 0x20) {
sb.append(String.format("\\u%04x", (int) ch));
} else {
sb.append(ch);
}
}
return sb.append('"').toString();
}
}
@@ -0,0 +1,184 @@
package pt.bitreport.errors;
import com.sun.net.httpserver.HttpServer;
import org.junit.jupiter.api.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import static org.junit.jupiter.api.Assertions.*;
class ErrorReporterTest {
/** Minimal embedded HTTP server that records raw request bodies. */
static HttpServer httpServer;
static int port;
static final List<String> RECEIVED = new CopyOnWriteArrayList<>();
@BeforeAll
static void startServer() throws IOException {
httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
port = httpServer.getAddress().getPort();
httpServer.createContext("/v1/ingest/events", exchange -> {
try (InputStream is = exchange.getRequestBody()) {
RECEIVED.add(new String(is.readAllBytes(), StandardCharsets.UTF_8));
}
exchange.sendResponseHeaders(200, 0);
exchange.close();
});
httpServer.start();
}
@AfterAll
static void stopServer() {
httpServer.stop(0);
}
@BeforeEach
void reset() {
RECEIVED.clear();
ErrorReporter.init(ErrorReporter.Config.builder()
.token("test-token")
.endpoint("http://127.0.0.1:" + port)
.build());
}
// --- reportError ---
@Test
void reportError_sendsOneEvent() throws Exception {
ErrorReporter.reportError(new IllegalArgumentException("bad arg"), null);
ErrorReporter.flush();
assertEquals(1, RECEIVED.size());
String body = RECEIVED.get(0);
assertTrue(body.contains("\"level\":\"error\""), "level should be error");
assertTrue(body.contains("\"message\":\"bad arg\""), "message should be present");
assertTrue(body.contains("\"schema_version\":1"), "schema_version should be 1");
assertTrue(body.contains("\"stacktrace\""), "stacktrace should be present");
assertTrue(body.contains("IllegalArgumentException"), "error_type should be in context");
}
@Test
void reportError_includesFileAndLine() throws Exception {
ErrorReporter.reportError(new RuntimeException("loc"), null);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"file_path\""), "file_path should be in context");
assertTrue(body.contains("\"line_number\""), "line_number should be in context");
}
@Test
void reportError_mergesExtraContext() throws Exception {
Map<String, Object> ctx = new LinkedHashMap<>();
ctx.put("request_id", "req-abc");
ctx.put("user_id", 42);
ErrorReporter.reportError(new RuntimeException("ctx test"), ctx);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"request_id\":\"req-abc\""), "request_id should be present");
assertTrue(body.contains("\"user_id\":42"), "user_id should be present");
}
// --- reportMessage ---
@Test
void reportMessage_defaultLevel() throws Exception {
ErrorReporter.reportMessage("something happened", null, null);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"level\":\"error\""), "default level should be error");
assertTrue(body.contains("\"message\":\"something happened\""));
}
@Test
void reportMessage_customLevel() throws Exception {
ErrorReporter.reportMessage("disk usage high", "warning", Map.of("used_pct", 91));
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"level\":\"warning\""));
assertTrue(body.contains("\"used_pct\":91"));
}
// --- project context ---
@Test
void projectFields_addedToContext() throws Exception {
ErrorReporter.init(ErrorReporter.Config.builder()
.token("test-token")
.endpoint("http://127.0.0.1:" + port)
.projectName("Test App")
.projectSlug("test-app")
.giteaRepo("org/test-app")
.build());
ErrorReporter.reportMessage("test", "info", null);
ErrorReporter.flush();
String body = RECEIVED.get(0);
assertTrue(body.contains("\"project_name\":\"Test App\""));
assertTrue(body.contains("\"project_slug\":\"test-app\""));
assertTrue(body.contains("\"gitea_repo\":\"org/test-app\""));
}
// --- disabled / no token ---
@Test
void disabled_skipsRequests() throws Exception {
ErrorReporter.init(ErrorReporter.Config.builder()
.token("test-token")
.endpoint("http://127.0.0.1:" + port)
.disabled(true)
.build());
ErrorReporter.reportMessage("nope", "error", null);
ErrorReporter.flush();
assertEquals(0, RECEIVED.size());
}
@Test
void noToken_skipsRequests() throws Exception {
ErrorReporter.init(ErrorReporter.Config.builder()
.token("")
.endpoint("http://127.0.0.1:" + port)
.build());
ErrorReporter.reportMessage("nope", "error", null);
ErrorReporter.flush();
assertEquals(0, RECEIVED.size());
}
// --- JSON serialiser ---
@Test
void toJson_escapesSpecialCharacters() {
String result = ErrorReporter.toJson("hello\nworld\t\"quotes\"");
assertEquals("\"hello\\nworld\\t\\\"quotes\\\"\"", result);
}
@Test
void toJson_handlesNestedMap() {
Map<String, Object> inner = new LinkedHashMap<>();
inner.put("a", 1);
inner.put("b", true);
Map<String, Object> outer = new LinkedHashMap<>();
outer.put("key", inner);
String json = ErrorReporter.toJson(outer);
assertEquals("{\"key\":{\"a\":1,\"b\":true}}", json);
}
@Test
void toJson_handlesNullValue() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("x", null);
assertEquals("{\"x\":null}", ErrorReporter.toJson(m));
}
}