Metadata-Version: 2.5
Name: sdk-garden-python
Version: 0.1.1
Summary: Lightweight SDK observability client for Python — stdlib only, non-blocking
Project-URL: Homepage, https://sdkgarden.com
Project-URL: Repository, https://github.com/tjb/SDKGarden
License: MIT
Requires-Python: >=3.8
Description-Content-Type: text/markdown

# sdk-garden-python
*Lightweight SDK observability client for Python — stdlib only, non-blocking*

Add SDK Garden telemetry to your Python SDK in minutes. Events are sent on a background daemon thread — your users never see a delay or an exception from the instrumentation layer.

## Install

```bash
pip install sdk-garden-python
```

## Quick Start

```python
from sdk_garden import SdkGarden

sg = SdkGarden(api_key="YOUR_API_KEY", sdk_name="my-sdk", sdk_version="1.0.0").start()

@sg.track_method("process_payment")
def process_payment(amount):
    ...
```

Track arbitrary events:

```python
sg.track("feature_used", properties={"feature": "streaming"})
```

Track errors with automatic PII scrubbing:

```python
try:
    process_payment(100)
except Exception as e:
    sg.track_error(e)
```

## Configuration

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | `str` | required | Your SDK Garden API key (`sgk_...`) |
| `sdk_name` | `str` | required | Name of your SDK (e.g. `"my-payments-sdk"`) |
| `sdk_version` | `str` | required | Version of your SDK (e.g. `"1.2.3"`) |
| `endpoint` | `str` | `https://ingest.sdkgarden.com/track` | Ingest endpoint URL (for self-hosted SDK Garden, `https://<your-host>/track`) |
| `debug` | `bool` | `False` | Print `[SDK Garden]` debug lines to stdout |
| `disabled` | `bool` | `False` | Disable all tracking (no thread spawned, no network calls) |
| `batch_size` | `int` | `10` | Maximum events per HTTP POST, from 1 to 100 |
| `flush_interval` | `float` | `5.0` | Seconds between flush cycles, from 0.1 to 86400 (a full batch is sent sooner) |
| `started_at` | `float` | import time | `time.time()` when your SDK began initializing; reported as `time_to_init_ms` for the dashboard's init timing |

## What gets sent

Each event carries your SDK's name and version, an event type, a random session ID created per client instance, and a timestamp. Depending on the event:

- **`sdk_initialized`** (sent by `start()`): Python implementation and version, and `time_to_init_ms`.
- **`method_called` / `method_success`**: method name, duration, and the *number* of positional arguments.
- **`sdk_error`**: error type and message (email addresses are redacted) plus the method and duration.

Never sent: argument or return values, request or response bodies, stack traces or environment variables. Error messages go out as they are apart from email addresses, so anything your SDK puts in an exception message, such as a hostname, a URL or an ID, goes with it. Nothing is sent when `disabled=True`.

### Telling your users

Copy this into your SDK's README or privacy docs so your users know what's collected (edit the names to match):

> **Telemetry.** This SDK reports anonymous usage data to its maintainers through [SDK Garden](https://github.com/tjb/SDKGarden): the SDK version, runtime version, which SDK methods are called, how long they take, and the type and message of the errors they raise (with email addresses removed). It never sends arguments, return values or request contents. To opt out, set `YOUR_SDK_TELEMETRY_DISABLED=1` *(wire this environment variable to `disabled=True` in your SDK)*.

## Behaviour Guarantees

**All network errors are caught and discarded. Your program will never see an exception from sdk-garden-python.**

**Runs on a daemon thread — your program exits normally even if events are queued.** Only that thread makes requests. When the interpreter exits, the events still queued are sent first, for at most 2 seconds; anything left after that is dropped. sdk-garden-python prioritises zero impact on your SDK over delivery guarantees. The automatic send does not run when the process is killed by a signal or ends through `os._exit()`, which is how `multiprocessing` workers started with `fork` or `forkserver` (the default on Linux) end: call `flush()` at the end of their work.

**Pass `disabled=True` in test environments to suppress all network calls.** When disabled, `start()` returns immediately without spawning a thread, and `track()` / `track_method()` / `track_error()` are all no-ops.

**Each connect and read waits at most 2 seconds.** A slow endpoint, such as one that trickles its response, can hold the background thread longer, but your code never waits for it: `flush()`, `shutdown()` and the send at exit keep their own time limits.

**Queue overflow is silent.** The internal queue holds a maximum of 100 events. If your SDK generates events faster than the flush thread can drain them, new events are discarded without raising an exception. With `debug=True`, each one is logged.

## Sending and shutting down

The background thread sends queued events every `flush_interval` seconds, sooner once `batch_size` events are waiting, and once more when the interpreter exits. Two methods let you control this yourself. Both ask the background thread to send and wait for it for a bounded time, even if a request hangs, and never raise:

```python
# Send everything queued now, waiting at most 2 seconds by default
# (e.g. at the end of a serverless handler or a short script).
sg.flush()

# Send everything queued (at most 2 seconds by default), then stop the client for good:
# the thread exits, tracking calls do nothing, and start() cannot restart it.
sg.shutdown()
```

`sg.shutdown(timeout=0)` stops the client and drops queued events without sending them. `flush()` and `shutdown()` are safe to call from a signal handler, such as a SIGTERM handler that closes your SDK. (On older Pythons such as 3.8, don't track the first event of a forked child from a signal handler: that starts the background thread, which can deadlock there.) A child process created with `os.fork()` (for example a prefork server worker) starts with an empty queue and its own background thread, which starts on its first event; the parent keeps sending what it had queued.

## Notes

- `start()` must be called before events are flushed. Calling `track()` before `start()` is safe — events are queued and will be flushed once `start()` is called.
- Events are serialized when they are tracked, so later changes to `properties` are not sent. Values JSON cannot encode (`datetime`, `Decimal`, ...) are sent as strings. An event that cannot be serialized at all (a circular reference), holds `nan` or `inf`, or is over 64 KiB serialized is dropped on its own, so it never costs the rest of its batch. For the same reason NUL characters and unpaired surrogates (say, from a `surrogateescape`-decoded path), which the server cannot store, are sent as U+FFFD, and an event whose name is not a string of at most 100 characters is dropped.
- `track_method()` returns a decorator. The decorated function behaves identically to the original; timing and error telemetry are captured transparently. An `async def` function stays a coroutine function and is timed until its coroutine finishes; a generator function's call is recorded when the generator is created.
- Error messages passed to `track_error()` are PII-scrubbed: email addresses matching the standard `user@example.com` pattern are replaced with `[REDACTED]` before the event is enqueued, and only the start of the message is sent: its first 1000 characters, cut to 1000 UTF-8 bytes, as much as the server keeps.

## License

MIT
