Metadata-Version: 2.4
Name: relayt
Version: 0.5.0
Summary: Connect a running app to its Relayt control plane: self-registration, heartbeat, per-deployment config, entitlements/licensing, signed named commands, error reports that become issues, and the app's own data (resources, dashboard, settings) in the studio over one outbound WebSocket. Standard library only.
Author: Relayt Studio
License-Expression: MIT
Project-URL: Homepage, https://relayt.studio
Keywords: relayt,licensing,entitlements,heartbeat,feature-flags,remote-config,control-plane,error-reporting
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# relayt (Python)

Connect a running app to its Relayt control plane: self-registration, heartbeat, per-deployment
config, entitlements and licensing, signed named commands, and error reports that become issues.
Standard library only, Python 3.8+. Same wire contract and behaviour as the TypeScript SDK
([`@relayt/sdk`](https://www.npmjs.com/package/@relayt/sdk) on npm).

```bash
pip install relayt
```

```python
from relayt import Runtime, CapabilitySpec, CapabilityField

rt = Runtime(
    "https://api.relayt.space",
    register={"deployment_id": DEPLOYMENT_ID, "enroll_key": os.environ["RUNTIMECORE_ENROLL_KEY"], "name": "Acme API"},
    credentials_path=".relayt.json",  # or on_credentials=lambda key, secret: save(key, secret)
    version="1.4.0",
    on_error=lambda e: print("[relayt]", e),
)

rt.handle("user.get", lambda c: {"id": c.payload["userId"]},  # a dict comes back to the panel as JSON
          CapabilitySpec(type="data", fields=[CapabilityField(name="userId", required=True)]))

rt.start()
# ... on shutdown:
rt.stop(timeout=10)  # waits for a running command to finish and ack
```

- Handler exceptions (`Exception`) are caught and acked as failures; `KeyboardInterrupt` and
  `SystemExit` are not swallowed.
- A 401 on heartbeat (key rotated) or a changed `signingKeyId` (secret rotated) re-registers when
  `register` is given, and the new pair is written to `credentials_path` / passed to `on_credentials`.
- `credentials_path=".relayt.json"` also reads a `.runtimecore.json` beside it (the file name used
  before the package was renamed) when `.relayt.json` does not exist yet; the next save writes
  `.relayt.json`.
- Failed beats retry with exponential backoff from `retry_base_s` (1s), ±10% jitter, capped at
  `interval_s` (30s).
- Results: a `str`, or any JSON-serialisable value (JSON-encoded, capped at 8000 characters).
- Recently seen command ids and nonces are remembered, so a replayed command runs at most once.

## Resources, dashboard and settings

Declare the app's own data and the studio renders a full admin for it on the app's page (lists with
search, filters, sorting and cursor paging, a detail sheet, create / edit / delete, typed actions,
dashboard cards, a typed settings form). The studio can only call what is declared; every handler
runs here, in your own validation. The full contract is docs/integrations.md §13.

```python
from relayt import Runtime, ResourceError

rt.resource(
    "orders",
    label="Orders",
    title_field="number",
    fields={
        "number": {"type": "text", "read_only": True},
        "customer": {"ref": "customers"},            # a row of another declared resource
        "total": {"money": "UZS", "required": True},   # integer minor units
        "status": {"select": ["new", "paid", "refunded"]},
        "created_at": {"type": "datetime", "read_only": True},
        "token": {"type": "text", "secret": True},     # never written to the audit trail
    },
    views={"filters": ["status"], "sortable": ["created_at", "total"], "default_sort": {"field": "created_at", "dir": "desc"}},
    list=lambda p, ctx: {"data": rows(p["limit"], p["cursor"], p["q"], p["filters"], p["sort"]), "next_cursor": nxt, "total": n},
    get=lambda id, ctx: find(id),                      # None = not found
    update=lambda id, patch, ctx: save(id, patch),     # create(input, ctx) and delete(id, ctx) too
    actions={
        "refund": {"label": "Refund", "danger": True, "fields": {"amount": {"money": "UZS"}},
                   "run": lambda id, data, ctx: {"message": refund(id, data.get("amount"), by=ctx.actor)}},
        "resync": {"row": False, "business": True, "run": lambda id, data, ctx: "Queued"},
    },
)
rt.dashboard(lambda ctx: [{"label": "Orders today", "value": 42, "trend": 0.12},
                          {"label": "Revenue", "value": 125000000, "format": "money", "currency": "UZS"}])
rt.settings({"shop_name": {"type": "text", "required": True}, "sms_key": {"type": "text", "secret": True}},
            get=lambda ctx: load_settings(), set=lambda values, ctx: save_settings(values))
rt.start()  # opens the bridge because something was declared
```

- **Field types:** `text`, `longtext`, `number`, `money` (`currency` or `currency_field`),
  `boolean`, `date`, `datetime`, `select`, `multiselect`, `email`, `url`, `image`, `json`, `ref`.
  A field is a type name, a shorthand (`{"select": [...]}`, `{"multiselect": [...]}`,
  `{"ref": "x"}`, `{"money": "UZS"}`) or the full dict. snake_case and camelCase options both work.
- **Handlers** take `ctx` last (`ctx.request_id`, `ctx.actor` = the studio person, `{"id", "name"}`)
  and may be plain functions or coroutines. They run on a pool of 8 threads.
- **Errors:** raise `ResourceError("not_found" | "invalid" | "conflict" | "forbidden", message,
  fields={"name": "reason"})`; anything else is answered as `failed` with its message.
- **Limits** (checked when you declare; a broken one raises `DeclarationError` at boot): 50
  resources, 60 fields each, 20 actions each, 30 fields an action, 60 settings fields, 200 options,
  labels 80 characters, 256 KB in all. `list` gets `limit` already clamped to 1..100.
- **Transport:** one outbound WebSocket to `/api/public/bridge` (no public URL needed), proven with
  the signing secret, pinged every 20 s, reconnected with backoff (1 s doubling to 60 s, ±20%). A
  declaration the platform refuses is reported once through `on_error` and retried only after it
  changes. `bridge=False` turns it off; `bridge={"max_delay_s": 30}` tunes it; `bridge_key=` uses an
  API key with `admin:*` instead of the ingest key. `stop()` closes it.

## Connect an app made in the studio

An app created in the Relayt studio shows **Not connected** and a one-time **connect code**
(`rlc_...`). Start the app with that code and its deployment binds to that app: no enroll key needed.

```bash
RELAYT_CONNECT_CODE=rlc_... python app.py
```

```python
rt = Runtime(
    "https://api.relayt.space",
    # connect_code defaults to the RELAYT_CONNECT_CODE env var; pass it here to set it in code instead.
    register={"deployment_id": DEPLOYMENT_ID, "version": "1.4.0", "environment": "production"},
    credentials_path=".relayt.json",
)
```

- The name and owners set in the studio stay; the SDK fills in version, environment and verbs.
- `register` needs a `connect_code` (or `RELAYT_CONNECT_CODE`) or an `enroll_key`, else `Runtime(...)`
  raises `ValueError`.
- The code is one-time and must be used within 7 days. A restart of the same deployment with the
  same code just resumes. Lost it, or it expired? Make a new one on the app page.
- A refused code (`connect_code_invalid`, `connect_code_expired`, `connect_code_used`) or a
  `deployment_taken` is reported once through `on_error` as a `relayt.RegisterError` (`status`,
  `code`, `permanent`), and the SDK stops calling register until the app restarts with a new code.

## Errors

`report_error` sends an error to the panel, which keeps ONE issue per distinct error and counts every
repeat. It never raises and never blocks: the event is scrubbed and queued, and a daemon thread sends
it with this deployment's key.

```python
try:
    charge_card(order)
except Exception as exc:
    rt.report_error(exc, {"order_id": order.id, "route": "/checkout"})
    # inside an except block the exception may be omitted: rt.report_error(context={...})
    # a level or your own grouping key when you want them:
    # rt.report_error(exc, ctx, level="fatal", fingerprint="checkout-timeout")
```

Global capture is opt-in, because a process-level hook changes what a crash does:

```python
rt = Runtime(..., errors={"capture_global": True})   # installed on start()
# or at any time, with an uninstaller back:
stop = rt.capture_errors(excepthook=True, threads=True, loop=None)
```

| Hook | Reported as | Then |
|---|---|---|
| `sys.excepthook` | `fatal` (KeyboardInterrupt is skipped) | the previous hook runs (the traceback still prints), the queue is flushed for up to `exit_timeout_s`, and the process exits as it would have. |
| `threading.excepthook` | `error`, with the thread's name | the previous hook runs. |
| asyncio loop exception handler | `error` (exceptions never retrieved from a task or future) | the previous handler, or the loop's default one, runs. |

`loop=None` means the running loop when `capture_errors` is called inside one; pass a loop to hook a
specific one. Uninstalling restores each previous hook, unless something else replaced ours since.

What happens before anything leaves the process (the same rules as the TypeScript SDK):

- **Scrubbed.** Passwords, tokens, API keys, bearer/basic credentials, JWTs, long hex/base64 runs and
  email addresses are taken out of the message, the stack and the context; context keys that look
  secret (`password`, `token`, `auth`, `cookie`, `session`, `api_key`, `card`, ...) are redacted
  whole. Context is capped at depth 4, 40 keys per level, 500-character strings and 8 KB overall
  (bigger becomes a note); the type at 120 characters, the message at 2000, the stack at 8000 (and
  50 frames). `errors["before_send"](event)` can change or drop (`None`) an event after that.
- **Folded.** The same error repeating within `errors["flush_interval_s"]` (default 2s) goes out
  once with a `count`; the latest context wins.
- **Limited.** At most `errors["max_per_minute"]` (default 30) distinct events a minute and 50
  waiting; extra ones are dropped and counted. A request carries at most 20 events and stays under
  480 KB (the server refuses 512 KB). A `429` pauses sending until its `Retry-After` (seconds or an
  HTTP date), including a per-event 429 inside a batch reply; network errors, 401 and 5xx back off
  (doubling from the flush interval, up to 60s) and keep the events; a 400 drops them.
- **Held for a key.** Reports made before registration finishes wait and go out once there is one.
- **Flushed on the way out.** `stop()` flushes (within its timeout), `flush_errors(timeout)` does it
  on demand, and an `atexit` hook sends what is left for up to `exit_timeout_s` (default 2s).

Without the runtime (a worker that does not heartbeat), use the reporter on its own:

```python
from relayt import ErrorReporter

errors = ErrorReporter("https://api.relayt.space", key=os.environ["RELAYT_KEY"], release="1.4.0", environment="production")
errors.capture_errors()                                   # opt-in, as above
errors.report_error(ValueError("boom"), {"job": "nightly-sync"})
errors.flush(timeout=5)                                   # or let atexit do it
```

### Stacks and fingerprints

A Python traceback is sent innermost frame first, one line per frame and no source lines:

```
Traceback (most recent call first):
  File "/srv/app/billing/invoices.py", line 41, in compute_total
  File "/srv/app/billing/views.py", line 12, in checkout
```

The server fingerprints every event (`fingerprint_of` reproduces it exactly, and is what the SDK uses
to fold repeats):

```
basis = "custom|" + fingerprint[:200]                                       if one is given
      = type + "|" + normalize_message(message) + "|" + "|".join(top_frames(stack))   otherwise
fingerprint = sha256(basis).hexdigest()[:40]
```

`normalize_message` replaces emails, URLs, UUIDs, hex, quoted strings and numbers with placeholders;
`top_frames` takes the first three frames as `function@dir/file` (last two path segments, no line
numbers, no build hashes). A V8 frame `at computeTotal (/srv/app/invoices.ts:41:17)` and a Python
frame `File "/srv/app/invoices.py", line 41, in compute_total` reduce the same way, so in both
languages an issue is keyed on the three frames nearest the raise, and a redeploy that moves lines
keeps it the same issue. The type is the class name (`ValueError`), module-qualified outside
builtins (`requests.exceptions.ConnectionError`). The server skips only JavaScript runtime frames
(`node_modules`, `node:internal`), so an error raised inside a library groups on the library's
frames; pass `fingerprint=` where that matters.

## Invoices

An app linked to a customer in the panel can raise an invoice for that customer (never anyone else:
the invoice belongs to the app's own space, client and project). Money is in integer minor units.

```python
r = rt.create_invoice(
    items=[{"description": "Oylik obuna", "unit_price_cents": 9_900_000, "description_i18n": {"en": "Monthly plan"}}],
    due_date="2026-10-05",
    pdf_enabled=False,  # the "PDF document" switch, see below
    providers=["rahmat"],  # optional: offer only these payment methods (default: every one the studio has on)
)
if r["ok"]:
    send_to_customer(r["invoice"]["payUrl"])
```

The invoice records your app, so the studio sees where it came from; when the app's "Pay page
brand" in the panel is the app, the pay page, the receipt and the PDF are headed by the app's name and
logo (the payment is still processed by Relayt Studio, and the page says so). The language defaults
to the client's, else the space's, else Uzbek.

`providers` (optional): a subset of the payment methods the studio has switched on. An unknown or
disabled one is refused with status 400 and `validProviders` listing the ones you can use. `None` or
empty: all of them. `subscription_id` (optional): one of THIS app's subscriptions, when the invoice
renews it; paying it then extends that subscription. Any other id is refused.

`pdf_enabled` (default on): once paid, the payer can open the receipt as a document on the pay domain
(`receiptUrl`) and download the PDF; before that the invoice's page is its checkout (`payUrl`).
`False`: payment only, no document anywhere, `receiptUrl` is `None`. It must be a real `bool`.

`create_invoice` never raises. It returns `{"ok": True, "invoice": {...}}` or
`{"ok": False, "status": int, "error": str}` (plus `validProviders` on a refused method; status 0 =
nothing was sent), and is not retried on a
network failure because the invoice may already exist. Same HTTP contract as the TypeScript SDK
(`POST /api/public/invoices`, see its README).

## Environment variable names

The panel keeps a backup of each app's `.env` in its vault and compares it with what the app
actually reads. For that the runtime sends the NAMES of the variables in `os.environ`, never a
value: on register, and on a heartbeat only when the set changed (in practice once per boot).
System variables (`PATH`, `HOME`, `LANG`, `LC_*`, `PYTHON*` image variables, the Windows set, ...)
are left out. The panel flags names the app has that the vault item lacks, and the reverse.

```python
Runtime(..., report_env_names=False)                                         # off
Runtime(..., report_env_names={"exclude": ["DEBUG", re.compile(r"^INTERNAL_")]})  # drop more names
relayt.env_names()                                                           # what would be sent
```

## The REST API: everything the app manages

Products, customers (your own end users as billing identities), subscriptions, invoices, payments,
business events and webhook endpoints, over `/api/v1/app`. With just a key (from the app's technical
settings in the studio, each with its own scopes) and the URL, or from a running app with its own key:

```python
from relayt import Client
relayt = Client(os.environ["RELAYT_API_KEY"], "https://api.relayt.space")
# or, inside an app on the runtime: rt.customers, rt.subscriptions, rt.invoices, ... (also rt.api)

customer = relayt.customers.create(external_id=user.id, email=user.email, phone=user.phone)
term = relayt.products.list()["data"][0]["variants"][0]["terms"][0]
sub = relayt.subscriptions.create(term_id=term["id"], customer_id=customer["id"])
pay_here = sub["openInvoice"]["payUrl"]  # pending until paid, then active

relayt.subscriptions.change_plan(sub["id"], pro_term_id)   # at the next renewal, no proration
relayt.subscriptions.cancel(sub["id"])                     # at period end; immediately=True for now
relayt.invoices.create(customer_id=customer["id"], items=[{"description": "Top-up", "unit_price_cents": 5_000_000}])
for inv in relayt.invoices.iter(status="open"):
    print(inv["number"])
relayt.events.create(type="order.shipped", title="Order #42 shipped", data={"order": 42})
```

Keyword arguments are snake_case and go out as the API's camelCase (`metadata` and `data` exactly as
given); answers are the API's JSON (camelCase dicts). Lists are `{"data", "next_cursor", "has_more"}`
and `.iter(**filters)` walks every page. Errors raise: `ValidationError` (400),
`AuthenticationError` (401), `PermissionDeniedError` (403: `insufficient_scope`, or `studio_only` for
refunds, discounts, custom prices and payment credentials), `NotFoundError` (404), `ConflictError`
(409), `RateLimitError` (429), `APIConnectionError`; each has `code`, `status`, `field`. Every POST
sends an `Idempotency-Key` (pass `idempotency_key=` to choose it), so network errors, 5xx and 429 are
retried safely.

### Webhooks

```python
from relayt import construct_webhook_event, WebhookSignatureError

@app.post("/relayt/webhooks")
async def relayt_webhook(request: Request):
    raw = await request.body()  # the RAW body, before any JSON parsing
    try:
        event = construct_webhook_event(raw, request.headers.get("Relayt-Signature"), os.environ["RELAYT_WEBHOOK_SECRET"])
    except WebhookSignatureError:
        return Response(status_code=400)
    if event["type"] == "invoice.paid":
        mark_paid(event["data"]["object"]["id"])
    return Response(status_code=200)
```

`verify_webhook(payload, header, secret)` is the boolean form. Dedupe on `event["id"]`: failed
deliveries are retried for about a day with the same id.

## Tests

`python -m unittest discover -s tests` (pytest runs them too). The error tests stand a real HTTP
server up on 127.0.0.1 in place of the panel, and check the fingerprint port against values produced
by the server's own `fingerprintOf`. The bridge tests run a real WebSocket server on 127.0.0.1 in
place of the platform (handshake and proof, round trips, pings, reconnects). No outside network.
