# Teracron SDK — Complete Reference for AI Agents > This file contains the full SDK documentation so AI coding assistants can > help developers integrate Teracron without requiring web browsing. --- ## What is Teracron? Teracron is an observability platform for software teams. It collects: 1. **Memory metrics** — RSS, VMS, USS, CPU usage per process 2. **Distributed traces** — Function-level spans with timing, errors, metadata 3. **Application events** — Custom structured events with metadata All telemetry is encrypted end-to-end (RSA-4096 + AES-256-GCM) before leaving the application. The API key contains only the public key — no secrets. --- ## Installation ```bash pip install teracron-sdk ``` **Requirements**: Python >= 3.9, psutil >= 5.9, cryptography >= 42.0.4, requests >= 2.32.0 --- ## Quick Start ### 1. Get your API key Go to https://www.teracron.com/dashboard → Project Settings → SDK Setup. Copy the API key (starts with `tcn_`). ### 2. Set the environment variable ```bash export TERACRON_API_KEY="tcn_dml2aWQta3VkdS02NTU6LS0t..." ``` ### 3. Start the agent ```python import teracron teracron.up() ``` That's it. Metrics flow in a background daemon thread. Shutdown is automatic via `atexit`. --- ## Workflow Tracing ### @trace decorator ```python from teracron import trace @trace("payment") def create_order(cart): ... @trace("payment") async def charge_card(order_id, amount): ... ``` - Each decorated function produces a **span** - Exceptions are captured (`error_type`, `error_message`) but **never swallowed** - Nested `@trace` calls build parent-child span trees automatically - All spans in the same call chain share a `trace_id` ### Parameter capture (opt-in) By default, NO parameter values are sent. Whitelist explicitly: ```python @trace("payment", capture=["order_id", "amount"]) def charge_card(order_id, amount, card_number): # order_id and amount captured — card_number is NOT ... ``` ### Context manager ```python from teracron import trace_context, async_trace_context with trace_context("payment", operation="validate") as span: span.set_metadata({"order_id": "ORD-123"}) validate_order(order) async with async_trace_context("payment", operation="verify") as span: span.set_metadata({"txn_id": "T-001"}) await verify_payment(txn) ``` ### Cross-process propagation ```python from teracron import get_trace_header, set_trace_header # Service A — outbound headers["X-Teracron-Trace"] = get_trace_header() # Service B — inbound set_trace_header(request.headers.get("X-Teracron-Trace")) ``` ### Sampling ```python teracron.up(trace_sample_rate=0.1) # Record 10% of traces ``` Deterministic per `trace_id`. Non-sampled functions still execute normally. ### PII scrubber ```python def my_scrubber(data: dict) -> dict: data.pop("email", None) data.pop("ssn", None) return data teracron.up(tracing_scrubber=my_scrubber) ``` Receives a shallow copy. If the scrubber raises, data is dropped entirely. --- ## Framework Auto-Instrumentation ### FastAPI / Starlette ```python from fastapi import FastAPI from teracron.tracing.middleware.fastapi import TeracronTracingMiddleware app = FastAPI() app.add_middleware(TeracronTracingMiddleware, workflow="api") ``` Auto-traces every HTTP request with `http.method`, `http.path`, `http.status_code`. ### Django ```python # settings.py MIDDLEWARE = [ "teracron.tracing.middleware.django.TeracronTracingMiddleware", # ... ] TERACRON_WORKFLOW = "api" # optional, default: "http" ``` ### Celery ```python from celery import Celery from teracron.tracing.middleware.celery import setup_celery_tracing app = Celery("tasks") setup_celery_tracing(app, workflow="tasks") ``` Propagates trace context through task headers automatically. --- ## Standalone Agent (Sidecar) Monitor an external process without modifying its code: ```bash export TERACRON_API_KEY="tcn_..." export TERACRON_TARGET_PID=$(pgrep -f "gunicorn") teracron-agent ``` --- ## Configuration Reference ### teracron.up() parameters | Parameter | Env Variable | Default | Description | |---|---|---|---| | `api_key` | `TERACRON_API_KEY` | *required* | API key from dashboard | | `domain` | `TERACRON_DOMAIN` | `www.teracron.com` | Ingest endpoint domain | | `interval_s` | `TERACRON_INTERVAL` | `10` | Collection interval (5–300s) | | `max_buffer_size` | `TERACRON_MAX_BUFFER` | `10` | Snapshots before flush | | `flush_deadline_s` | `TERACRON_FLUSH_DEADLINE` | `60` | Max seconds before forced flush | | `timeout_s` | `TERACRON_TIMEOUT` | `10` | HTTP timeout (2–30s) | | `debug` | `TERACRON_DEBUG` | `false` | Debug logging to stderr | | `target_pid` | `TERACRON_TARGET_PID` | self | PID to monitor | | `tracing_enabled` | `TERACRON_TRACING_ENABLED` | `true` | Master tracing switch | | `trace_batch_size` | `TERACRON_TRACE_BATCH_SIZE` | `100` | Spans before flush (1–10000) | | `trace_flush_interval` | `TERACRON_TRACE_FLUSH_INTERVAL` | `10` | Trace flush interval (1–300s) | | `trace_sample_rate` | `TERACRON_TRACE_SAMPLE_RATE` | `1.0` | Sampling rate (0.0–1.0) | | `tracing_scrubber` | — | `None` | PII scrubber callable | --- ## API Reference ### `teracron.up(**kwargs) → TeracronClient` Start telemetry. Reads `TERACRON_API_KEY` from env. Idempotent — calling again returns the same instance. ### `teracron.down()` Stop the agent. Performs a final flush. Safe to call if `up()` was never called. ### `TeracronClient` (advanced) ```python from teracron import TeracronClient client = TeracronClient(api_key=os.environ["TERACRON_API_KEY"]) client.start() # ... client.stop() ``` --- ## Security Model - **RSA-4096 OAEP + AES-256-GCM** hybrid envelope encryption - API key contains ONLY the public key — no secrets leave the server - Ephemeral AES key + IV per flush — no key reuse - AES key material zeroed immediately after encryption - All traffic over HTTPS (TLS 1.2+) - SDK never logs PII, keys, or metric payloads - Parameter capture is opt-in only - PII scrubber runs before data enters the buffer --- ## Memory Mapping (Python → Teracron) | Teracron Field | Python Source | Description | |---|---|---| | `heapTotal` | `psutil.Process.memory_info().vms` | Virtual memory | | `heapUsed` | `psutil.Process.memory_full_info().uss` | Unique set size | | `rss` | `psutil.Process.memory_info().rss` | Resident set size | | `external` | `0` | N/A in Python | | `arrayBuffers` | `0` | N/A in Python | | `cpuUsagePct` | `psutil.Process.cpu_percent()` | CPU usage (0–100%) | --- ## Wire Format (for API integrators) ### Trace payload — POST /api/v1/traces ``` Header: X-Project-Slug: Content-Type: application/octet-stream Body: RSA-OAEP encrypted envelope → decrypts to JSON ``` ```json { "type": "trace", "project_slug": "vivid-kudu-655", "spans": [ { "trace_id": "32-char hex", "span_id": "32-char hex", "parent_span_id": "32-char hex | null", "workflow": "payment", "operation": "PaymentService.charge_card", "status": "succeeded | failed | started", "started_at": 1721500000000, "duration_ms": 142.5, "error_type": "ValueError | null", "error_message": "max 1024 chars | null", "metadata": {}, "captured_params": {} } ] } ``` ### Event payload — POST /api/v1/events ```json { "type": "event", "project_slug": "vivid-kudu-655", "events": [ { "trace_id": "32-char hex", "span_id": "32-char hex", "workflow": "payment", "event_type": "info | warning | error | metric | custom", "name": "payment.completed", "message": "optional description", "timestamp": 1721500000000, "metadata": {} } ] } ``` --- ## Links - **Website**: https://www.teracron.com - **PyPI**: https://pypi.org/project/teracron-sdk/ - **GitHub**: https://github.com/teracron/teracron-sdk-python - **Docs**: https://docs.teracron.com/sdk/python - **Changelog**: https://github.com/teracron/teracron-sdk-python/blob/main/CHANGELOG.md - **License**: Apache-2.0 - **Contact**: sdk@teracron.com