DOCUMENTATION

Build your own client

Six rules, one small implementation in six languages, and what each field buys you.

A client is an HTTP POST. There is no SDK you must adopt, no agent to run and nothing to compile. This page is what a good one does, and why.

The contract in one screen

  • POST /api/v1/ingest, X-Codesafe-Key: <api_key>, Content-Type: application/json.
  • Body: one error object, or an array of up to 50 — 256 KB maximum.
  • runtime is php, node, python, go, java, dotnet, ruby or rust (an unknown one on an error is stored as php); entry is web, cli or worker; kind is error, not_found or security.
  • 202 means queued. The row is searchable about a second later.
  • Field-by-field reference: Errors, part of the API reference.

Six rules, and why each one exists

rulewhy
Fire and forgetReporting must never be able to fail the request that reports. Swallow every exception, always.
One second, hardA codesafe instance that is unreachable would otherwise add its timeout to every page your users load.
Never retry what may have arrivedA timeout after the body went out may already be stored, and sent again it is stored twice. Drop it. Only a connection that never opened, a 429 or 503, or a 502 or 504 from a proxy in front of codesafe may go once more: a second later, off the request path.
Batch, then flushPHP collects during the request and sends once, after the response has gone out. A long-running process flushes on a short timer, every second or two, and at exit. One POST, no latency.
Redact before sendingPasswords, tokens, cookies and authorization headers never leave the box. Do it in the client, not in codesafe.
Cap everythingTruncate messages, backtraces and bodies before they are sent, and keep the whole POST under 256 KB: a 413 loses the whole batch.

Why not retry more? An incident produces thousands of errors at once. A dropped report costs you one row; a retry loop during an outage costs you the site.

Have your AI agent write it

An AI coding assistant writes a good client in any language from this page. Paste the prompt below, then attach this page and the Errors reference: the schema it has to match.

Write an error-reporting client (a "sender") for <language / runtime> that reports to a codesafe instance, following the attached pages exactly. Constraints: - A single, dependency-free file (standard library only). - Install the runtime's global error hooks (uncaught exception, unhandled rejection, fatal handler) and expose captureException and captureMessage. - Send over HTTP with a ≤ 1 s total timeout; never throw into or block the host application: swallow every transport error. - Batch queued errors into one request: at most 50 objects, 256 KB. - Gate by a configurable logLevel: send only priority <= logLevel. - Guard re-entrancy: an error raised inside the client never triggers another send. - Redact secrets before sending; send usernames and e-mail addresses as they are. - Retry only as the rules say, once, off the request path. - Match the payload schema field for field; do not invent fields. After the code, show a minimal init(...) plus one captureException and one captureMessage example.

What the prompt asks for, in detail:

  • Hooks and manual calls. The global hooks catch what nobody caught; captureException(error) and captureMessage(text, priority) report what the application handled itself.
  • Gate by priority in the client. Send only what is at or above the configured severity (priority <= logLevel). The shipped clients default to 5 (notice) in PHP and 4 (warning) in Node and the browser. It is cheaper than sending what codesafe drops: the project's own threshold applies on arrival too.
  • Guard re-entrancy. A simple "already flushing" flag: an error inside the client must not report itself in a loop.
  • Choose the priority. Syslog severities, 0 to 7:

    #nameuse for
    0emergencysystem unusable
    1alertact immediately
    2criticalfatal or unrecoverable (PHP's E_ERROR, parse and compile errors)
    3erroruncaught exceptions, the default
    4warninga recoverable warning (E_WARNING)
    5noticenotable but fine (E_NOTICE; the default for captureMessage)
    6infoinformational
    7debugdiagnostic

    An uncaught exception is 3 unless it carries a priority of its own; a language's own errors, warnings and notices map to the table; captureMessage is 5 unless the caller says otherwise. Clamp to 0–7; anything that is not a number becomes 3.

  • Which keys to redact. In the request's query, form fields and cookies, and in extra, replace the value of every key whose name matches password|passwd|pwd|token|secret|authorization|cookie|api[-_]key (case-insensitive) and keep the key. Check the key before going into its value, so a secret that is an array (password[]=…) goes whole. codesafe redacts a longer list again on arrival, and masks usernames and e-mail addresses itself.

The smallest thing that works

PHP

final class Client
{
	private array $queue = [];

	public function __construct(
		private string $url,
		private string $key,
	)
	{
		register_shutdown_function($this->flush(...));   // send after the response
	}

	public function report(Throwable $e): void
	{
		// one POST carries at most 50: a request that throws more keeps its first 50
		if(count($this->queue) >= 50)
		{
			return;
		}

		$this->queue[] = [
			'v' => 1,
			'runtime' => 'php',
			'entry' => PHP_SAPI === 'cli' ? 'cli' : 'web',
			'kind' => 'error',
			'priority' => 3,
			'message' => mb_substr($e->getMessage(), 0, 1000),
			'events' => [[
				'message' => mb_substr($e->getMessage(), 0, 1000),
				'className' => $e::class,
				'file' => $e->getFile(),
				'line' => $e->getLine(),
				'backtrace' => mb_substr($e->getTraceAsString(), 0, 8000),
			]],
		];
	}

	public function flush(): void
	{
		if($this->queue === [])
		{
			return;
		}

		// php-fpm only: hand the response to the visitor and close their
		// connection, then keep working. Everything below now costs the user
		// nothing. Call it ONLY if the application has not already — it ends
		// the response, so anything the app still wanted to echo is lost.
		if(function_exists('fastcgi_finish_request'))
		{
			fastcgi_finish_request();
		}

		// one POST holds at most 256 KB: drop from the end until it fits
		$batch = $this->queue;
		$this->queue = [];
		$body = json_encode($batch, JSON_INVALID_UTF8_SUBSTITUTE);
		while(strlen($body) > 250000 && count($batch) > 1)
		{
			array_pop($batch);
			$body = json_encode($batch, JSON_INVALID_UTF8_SUBSTITUTE);
		}

		$curl = curl_init($this->url . '/api/v1/ingest');
		curl_setopt_array($curl, [
			CURLOPT_POST => true,
			CURLOPT_POSTFIELDS => $body,
			CURLOPT_HTTPHEADER => ['Content-Type: application/json', 'X-Codesafe-Key: ' . $this->key],
			CURLOPT_CONNECTTIMEOUT_MS => 300,
			CURLOPT_TIMEOUT_MS => 1000,
			CURLOPT_RETURNTRANSFER => true,
		]);

		@curl_exec($curl);          // no retry, no exception, no log of our own
	}
}

Node.js

const queue = [];

export const report = (error, extra = {}) =>
{
	// at most 50 wait for the next flush: a storm cannot grow the queue
	if (queue.length >= 50)
	{
		return;
	}
	
	queue.push({
		v: 1,
		runtime: 'node',
		entry: 'web',
		kind: 'error',
		priority: 3,
		message: String(error.message).slice(0, 1000),
		events: [{
			message: String(error.message).slice(0, 1000),
			className: error.name,
			backtrace: String(error.stack ?? '').slice(0, 8000),
		}],
		...extra,
	});
};

export const flush = async () =>
{
	if (queue.length === 0)
	{
		return;
	}
	
	// one POST holds at most 256 KB: drop from the end until it fits
	const batch = queue.splice(0, 50);
	let body = JSON.stringify(batch);
	while (Buffer.byteLength(body) > 250_000 && batch.length > 1)
	{
		batch.pop();
		body = JSON.stringify(batch);
	}
	
	await fetch(`${process.env.CODESAFE_URL}/api/v1/ingest`, {
		method: 'POST',
		headers: {'Content-Type': 'application/json', 'X-Codesafe-Key': process.env.CODESAFE_KEY},
		body,
		signal: AbortSignal.timeout(1000),
	}).catch(() => {});        // never rejects into the caller
};

// a server never exits: flush every two seconds, and once more at exit
setInterval(flush, 2000).unref();
process.on('beforeExit', flush);

Python

import atexit, json, os, threading, urllib.request

URL = os.environ["CODESAFE_URL"]
KEY = os.environ["CODESAFE_KEY"]
QUEUE: list[dict] = []
LOCK = threading.Lock()

def report(exc: BaseException) -> None:
	with LOCK:
		if len(QUEUE) >= 50:
			return                # a storm keeps its first 50 until the next flush
		QUEUE.append({
			"v": 1,
			"runtime": "python",
			"entry": "web",
			"kind": "error",
			"priority": 3,
			"message": str(exc)[:1000],
			"events": [{"message": str(exc)[:1000], "className": type(exc).__name__}],
		})

def flush() -> None:
	with LOCK:
		batch = QUEUE[:]
		QUEUE.clear()

	if not batch:
		return

	# one POST holds at most 256 KB: drop from the end until it fits
	body = json.dumps(batch).encode()
	while len(body) > 250_000 and len(batch) > 1:
		batch.pop()
		body = json.dumps(batch).encode()

	req = urllib.request.Request(
		f"{URL}/api/v1/ingest",
		data=body,
		headers={"Content-Type": "application/json", "X-Codesafe-Key": KEY},
	)

	try:
		urllib.request.urlopen(req, timeout=1)
	except Exception:
		pass

def flush_every(seconds: float) -> None:
	flush()
	timer = threading.Timer(seconds, flush_every, [seconds])
	timer.daemon = True           # never holds the process open
	timer.start()

flush_every(2)                    # a server never exits on its own
atexit.register(flush)

Go

type Client struct {
	URL, Key string
	queue    []map[string]any
	mu       sync.Mutex
}

func (c *Client) Report(err error) {
	message := err.Error()
	if len(message) > 1000 {
		message = message[:1000]
	}

	c.mu.Lock()
	defer c.mu.Unlock()

	if len(c.queue) >= 50 {
		return // a storm keeps its first 50 until the next flush
	}

	c.queue = append(c.queue, map[string]any{
		"v":        1,
		"runtime":  "go",
		"entry":    "web",
		"kind":     "error",
		"priority": 3,
		"message":  message,
		"events":   []map[string]any{{"message": message, "className": "error"}},
	})
}

// Run flushes every two seconds: start it once with `go client.Run()`,
// and call Flush once more before the process exits
func (c *Client) Run() {
	for range time.Tick(2 * time.Second) {
		c.Flush()
	}
}

func (c *Client) Flush() {
	c.mu.Lock()
	batch := c.queue
	c.queue = nil
	c.mu.Unlock()

	if len(batch) == 0 {
		return
	}

	// one POST holds at most 256 KB: drop from the end until it fits
	body, _ := json.Marshal(batch)
	for len(body) > 250_000 && len(batch) > 1 {
		batch = batch[:len(batch)-1]
		body, _ = json.Marshal(batch)
	}

	req, _ := http.NewRequest("POST", c.URL+"/api/v1/ingest", bytes.NewReader(body))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("X-Codesafe-Key", c.Key)

	if resp, err := (&http.Client{Timeout: time.Second}).Do(req); err == nil {
		resp.Body.Close()
	}
}

Java

public final class Codesafe {
	private final String url;
	private final String key;
	private final List<String> queue = new ArrayList<>();
	private final HttpClient http = HttpClient.newHttpClient();

	public Codesafe(String url, String key) {
		this.url = url;
		this.key = key;
		// a server never exits: flush every two seconds, and once more at exit
		var timer = Executors.newSingleThreadScheduledExecutor(task -> {
			var thread = new Thread(task, "codesafe");
			thread.setDaemon(true);
			return thread;
		});
		timer.scheduleWithFixedDelay(this::flush, 2, 2, TimeUnit.SECONDS);
		Runtime.getRuntime().addShutdownHook(new Thread(this::flush));
	}

	public void report(Throwable t) {
		var text = Objects.toString(t.getMessage(), "");
		var message = json(text.substring(0, Math.min(1000, text.length())));
		var entry = """
			{"v":1,"runtime":"java","entry":"web","kind":"error","priority":3,
			 "message":%s,"events":[{"message":%s,"className":%s}]}
			""".formatted(message, message, json(t.getClass().getName()));
		synchronized (queue) {
			// a storm keeps its first 50 until the next flush
			if (queue.size() < 50) {
				queue.add(entry);
			}
		}
	}

	public void flush() {
		List<String> batch;
		synchronized (queue) {
			if (queue.isEmpty()) return;
			batch = new ArrayList<>(queue);
			queue.clear();
		}

		try {
			// one POST holds at most 256 KB: drop from the end until it fits
			var body = "[" + String.join(",", batch) + "]";
			while (body.getBytes(StandardCharsets.UTF_8).length > 250_000 && batch.size() > 1) {
				batch.remove(batch.size() - 1);
				body = "[" + String.join(",", batch) + "]";
			}

			var request = HttpRequest.newBuilder(URI.create(url + "/api/v1/ingest"))
				.header("Content-Type", "application/json")
				.header("X-Codesafe-Key", key)
				.timeout(Duration.ofSeconds(1))
				.POST(HttpRequest.BodyPublishers.ofString(body))
				.build();

			http.send(request, HttpResponse.BodyHandlers.discarding());
		} catch (Exception ignored) {
			// a monitoring client may never throw into the application
		}
	}

	// a JSON string: quotes, backslashes and control characters escaped
	private static String json(String value) {
		var out = new StringBuilder("\"");
		for (char c : value.toCharArray()) {
			if (c == '"' || c == '\\') out.append('\\').append(c);
			else if (c < 0x20) out.append("\\u%04x".formatted((int) c));
			else out.append(c);
		}
		return out.append('"').toString();
	}
}

Rust

pub struct Codesafe {
    url: String,
    key: String,
    queue: Mutex<Vec<serde_json::Value>>,
}

impl Codesafe {
    pub fn report(&self, err: &dyn std::error::Error) {
        let message: String = err.to_string().chars().take(1000).collect();
        let mut queue = self.queue.lock().unwrap();
        if queue.len() >= 50 {
            return; // a storm keeps its first 50 until the next flush
        }
        queue.push(serde_json::json!({
            "v": 1,
            "runtime": "rust",
            "entry": "web",
            "kind": "error",
            "priority": 3,
            "message": message,
            "events": [{ "message": message, "className": "Error" }],
        }));
    }

    // a server never exits on its own: spawn this once on an Arc<Codesafe>,
    // and await flush() once more before the process exits
    pub async fn run(&self) {
        let mut tick = tokio::time::interval(std::time::Duration::from_secs(2));
        loop {
            tick.tick().await;
            self.flush().await;
        }
    }

    pub async fn flush(&self) {
        let mut batch: Vec<serde_json::Value> = {
            let mut queue = self.queue.lock().unwrap();
            let n = queue.len().min(50);
            queue.drain(..n).collect()
        };
        if batch.is_empty() {
            return;
        }

        // one POST holds at most 256 KB: drop from the end until it fits
        let mut body = serde_json::to_vec(&batch).unwrap_or_default();
        while body.len() > 250_000 && batch.len() > 1 {
            batch.pop();
            body = serde_json::to_vec(&batch).unwrap_or_default();
        }

        let client = match reqwest::Client::builder()
            .timeout(std::time::Duration::from_secs(1))
            .build()
        {
            Ok(client) => client,
            Err(_) => return,
        };

        // the result is dropped on purpose: no retry, no panic, no log
        let _ = client
            .post(format!("{}/api/v1/ingest", self.url))
            .header("Content-Type", "application/json")
            .header("X-Codesafe-Key", &self.key)
            .body(body)
            .send()
            .await;
    }
}

What to send beyond the message

Each of these costs nothing and changes what codesafe can do for you.

fieldwhat it unlocks
release"born in this release", release comparison, "fixed in this release?"
environmentproduction and staging stop sharing an issue
context.traceIda browser failure and the server error behind it line up as one request; the browser client sends a traceparent header on same-origin calls for your server to read the id from
context.dirthe deploy root: stripped from file paths, so a file groups as one issue across deploys and can be checked against the mapped repository
context.host / uri / method (and request)the application column, and the request that failed, replayable where the project allows it
context.statusfilter by 500 or 5xx, group by status
priorityyour own gate: which levels become issues, per project

404s and security events

The same POST carries them; kind says which.

  • kind: "not_found" — the path as the message, query string stripped. codesafe stores it at INFO and takes it while the project's 404 switch is on.
  • kind: "security" — the event's name as events[0].className, from a closed list: auth_failure, auth_success (only a login that succeeded after recent failures), csrf_reject, permission_denied, rate_limited, validation_refused, privileged_action. The list also holds the names the Shield and the WordPress plugin send themselves. Any other name is dropped, and the request still answers 202: read accepted.

Rate-limit both in the client. A scanner sends thousands of 404s a minute, and the reporter must not become the flood.

How codesafe answers

statusmeaningwhat a client does
202queued; accepted says how many were taken, fewer than sent when the project's gates drop some on purposenothing
400the payload is wrong: malformed JSON, more than 50 objects, an object with no message, class or filefix the client; do not retry
401the key is missing or wrongstop sending; alert an operator
413body over 256 KBtruncate harder
429the project's budget is spent: 3 000 requests or 15 000 events a minute; Retry-After: 60drop the batch, or retry it once a second later
503codesafe cannot take it now: its queue or project registry is down, or intake is paused near the event store's memory ceiling; usually Retry-After: 30drop the batch, or retry it once a second later

Every one of them is "drop it and move on", except that a 429 or 503 may get one more try, off the request path, as may a 502 or 504 from a proxy in front of codesafe. That is the whole error-handling strategy, and it is deliberate.

Before you ship it

  • Kill codesafe and confirm your app is unaffected — same response time, no errors of its own.
  • Send 10 000 errors in a loop and confirm a handful of POSTs of at most 50 go out, not 10 000, and none answers 400 or 413.
  • Put a password in a request body and confirm it never reaches codesafe.
  • Restart the app mid-request and confirm nothing is lost that matters.

Next: Errors for the field reference, Browser client for the front end, or OpenTelemetry if you already run a collector.