Metadata-Version: 2.5
Name: mdrn-sdk
Version: 0.4.0
Summary: The MDRN SDK for Python: SQLite, Postgres, Objects, Mail and Auth from your app's backend or a Python Worker, standard library only
Project-URL: Homepage, https://mdrn.io/docs/sdk/
Project-URL: Source, https://github.com/mdrn-io/sdk-python
Project-URL: Issues, https://github.com/mdrn-io/sdk-python/issues
Project-URL: Repository, https://github.com/mdrn-io/mdrn
License-Expression: MIT
License-File: LICENSE
Keywords: database,mail,mdrn,objects,postgres,sdk,sqlite
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# MDRN SDK for Python

`mdrn-sdk` (import `mdrn_sdk`) is the client for the products a deployed MDRN app has
(SQLite, Postgres, Objects, Mail) and for who is calling it (Auth), for Python 3.10+ backends and
Python Workers. It uses only the standard library. The same surface exists for
[JavaScript, Go and Rust](https://mdrn.io/docs/sdk/).

## Install

```sh
pip install mdrn-sdk
```

## Quickstart

```python
import os
from mdrn_sdk import Mdrn

mdrn = Mdrn.from_env(os.environ)

def handle(request):                       # your framework's request: its headers and URL
    user = mdrn.auth.user(request.headers)
    if not user:
        return 401, "Sign in first"
    note = mdrn.sqlite.create("notes", {"owner": user.id, "text": "hello"})
    me = mdrn.auth.me(request.headers, request.url)
    if me and me.get("email"):
        mdrn.mail.send(me["email"], "Saved", f"Note {note['id']} saved.")
    return 200, note
```

## Where the values come from

MDRN injects everything `from_env` reads into a release's environment: `MDRN_PROJECT_ID`,
`MDRN_ENVIRONMENT` (`sandbox` or `production`), and one `MDRN_<PRODUCT>_URL` and
`MDRN_<PRODUCT>_TOKEN` per product switched on for the app (`SQLITE`, `POSTGRES`, `OBJECTS`,
`MAIL`). In a Python Worker, `AsyncMdrn.from_env(env)` also finds the `MDRN_PRODUCTS` service
binding there and sends product requests through it (a Worker cannot reach its own hostname with
a global `fetch`). Anywhere else, give the values yourself:

```python
mdrn = Mdrn(origin="https://your-app.mdrn.page", project=project, environment="sandbox",
            tokens={"sqlite": sqlite, "postgres": postgres, "objects": objects, "mail": mail})
```

The tokens are workload credentials, never for a browser. `mdrn.enabled` lists the products the
client has (`sqlite`, `postgres`, `objects`, `mail`); a call on another raises `PRODUCT_NOT_ENABLED` with the
variable that is missing. Options: `transport` (a callable taking the SDK's `Request` and
answering its `Response`, replacing the built-in `http.client` one), `transfer` (the same for
grant URLs), `timeout` (seconds, 10).

Every write takes `idempotency_key`. A key is generated when you give none; give one when you
retry a change yourself and want it to happen once.

`AsyncMdrn` has the same methods as coroutines (`await mdrn.sqlite.create(...)`); `auth.user`,
`scheduled_run` and the cache helpers make no request and stay plain calls. By default it runs the blocking transport
in the event loop's default executor; in a Worker it uses the binding and the Worker's `fetch`
(`mdrn_sdk.workers`). A task cancelled before a call sends nothing, and one cancelled while the SDK waits for a
starting database stops waiting at once.

## Database

An app has two databases, each its own product with its own data: `mdrn.sqlite` and
`mdrn.postgres`. Both have the same records API. A record is a JSON object in a named
collection, with an id MDRN assigns and a version that grows by one on every change.

```python
task = mdrn.sqlite.create("tasks", {"title": "Write docs", "done": False})
same = mdrn.sqlite.get("tasks", task["id"])                  # None when there is none
page = mdrn.sqlite.list("tasks", limit=50, cursor=cursor)    # {"items": [...], "nextCursor": ...}
done = mdrn.sqlite.update("tasks", task["id"], {"done": True})
mdrn.sqlite.delete("tasks", task["id"])

order = mdrn.postgres.create("orders", {"total": 42})        # the same calls on Postgres
```

`mdrn.postgres.get`, `mdrn.postgres.list`, `mdrn.postgres.update` and `mdrn.postgres.delete`
work as their SQLite namesakes. A Postgres database is made the first time it is used; while it
is being made MDRN answers 503 `DATABASE_STARTING` with `Retry-After`, and the SDK sends the
call again after that many seconds (5 when absent), for up to a minute in total, before the
error is yours.

`update` merges the fields you give into the record (a shallow merge). Without `version` it
reads the record first, sends the change with the version it read as `If-Match`, and if the
record changed in between (409 `CONFLICT`) it reads and tries again, up to three more times.
With `version=` the change is sent once with that `If-Match` and a `CONFLICT` is yours to
handle; that is the right choice when the user saw the version they are changing. `delete`
works the same way. Keep cursors exactly as returned. Records, pages and objects are plain dicts
with the field names of the API (`nextCursor`, `contentType`, ...).

## Objects

```python
file = mdrn.objects.upload("photo.jpg", data, type="image/jpeg")   # data: bytes
info = mdrn.objects.get(file["id"])                                 # None when there is none
page = mdrn.objects.list(limit=50, cursor=cursor)
grant = mdrn.objects.download_url(file["id"])                       # {"url", "expiresAt"}: a plain URL, 15 minutes
mdrn.objects.delete(file["id"])
```

`upload` does the whole upload: the file's SHA-256, an upload session, one part of 16 MiB after
another sent to a grant URL with the grant's own headers (through the plain transport, never the
binding and never with the token), completion, and then waits for MDRN to verify the bytes
(checked before completion answers, so usually at once; a large file still
verifying is polled after a second, then less often up to every 5 s, a minute at most) and answers the
object in state `ready`. Pass `wait=False` to get it back after one read instead (a large file may still be
`verifying`) and check `objects.get` later. Bytes that do not match raise `OBJECT_REJECTED`.

The session itself is there too, for resuming an upload or for letting a browser PUT the
bytes: `mdrn.objects.uploads.create`, `mdrn.objects.uploads.get`, `mdrn.objects.uploads.list`,
`mdrn.objects.uploads.parts`, `mdrn.objects.uploads.part`, `mdrn.objects.uploads.complete`,
`mdrn.objects.uploads.abort` and `mdrn.objects.operation(id)`. Ask for a part grant in your
backend (`mdrn.objects.uploads.part(upload_id, part_number, size)`) and hand the browser the
grant's `url`, `method` and `headers`.

## Mail

```python
mdrn.mail.send("ada@example.com", "Welcome", "Hello Ada", html="<p>Hello Ada</p>")
mdrn.mail.send("ada@example.com", template="welcome")
```

A message is either your own content (`subject` and `text`, `html` if wanted) or a `template`
of the project and environment, which supplies all three; giving a template together with any
of them raises `ValueError` before anything is sent. `attachments` (up to four,
`{"filename", "type", "content"}` with base64 content) and `sender_id` (a verified sender
domain; omit it when the workspace has one) go with either. The answer is
`{"id": ..., "state": "queued"}`: accepted, not yet delivered. A Sandbox environment delivers
like Production: to anyone, from a verified sender.

## Auth

MDRN's Proxy deletes every `x-mdrn-*` header a client sent and, for a signed-in visitor, adds
`x-mdrn-user-id` and `x-mdrn-identity-token`. Your backend is reachable only through the Proxy,
so these can be trusted there (not on a local development server, where anyone can send them).
The SDK takes the request's headers (any mapping, header names in any case) and, for `me`, its
URL:

```python
user = mdrn.auth.user(request.headers)             # User(id, token) or None
me = mdrn.auth.me(request.headers, request.url)    # {"id", "email"?, "name"?, "metadataState", ...} or None
```

`me` asks MDRN Identity (`GET /v1/auth/me` at the request's origin, with the visitor's
short-lived token) and answers `None` when nobody is signed in or the session has ended. Unless
requests go through the `MDRN_PRODUCTS` binding (`AsyncMdrn.from_env` in a Python Worker), the
token goes to that origin, so the URL must be https, or plain http to `localhost`, `127.0.0.1`
or `[::1]`; any other is a `ValueError`.

## Schedules

A schedule declared in `mdrn.jsonc` arrives as a `POST` to its path. `scheduled_run(headers)`
returns the run (`schedule`, `run_id`, `scheduled_time`, `attempt`), or `None` for any other
request. The run id is the same on every attempt of one run, so use it as the idempotency key of
the work.

```python
from mdrn_sdk import scheduled_run
run = scheduled_run(request.headers)
if request.path == "/tasks/digest" and run:
    send_digest(run.run_id)
```

## Caching

MDRN's edge caches a response that carries `MDRN-Cache-Control` (`CACHE_HEADER`): `max-age=N`
keeps it fresh N seconds, `stale-while-revalidate=N` lets it be served stale N seconds more
while it is refreshed, `no-store` never caches it. MDRN removes the header before the browser
sees it, and it takes precedence over `Cache-Control`. The header works without the SDK; these
only write it. `cache_headers(max_age, stale_while_revalidate=None)` is the header as a dict to
add to your response, `no_cache_headers()` the `no-store` one, and `cache_control(max_age,
stale_while_revalidate=None)` the value. `max_age` is an integer from 1 to 31536000 and
`stale_while_revalidate` one from 0 to 31536000; one that is not an integer is a `TypeError`,
one out of range a `ValueError`.

```python
from mdrn_sdk import cache_headers, no_cache_headers
return JSONResponse(prices, headers=cache_headers(60, stale_while_revalidate=300))
return JSONResponse(account, headers=no_cache_headers())
```

## Errors

Every failed call raises `MdrnError` with `status` (the HTTP status, 0 when no response was
received), `code`, its message as `str(error)` (MDRN's, for your logs) and `details` (the
response body).

| `code` | `status` | When |
| --- | --- | --- |
| `PRODUCT_NOT_ENABLED` | 0 | The product has no URL or token in this environment |
| `TIMEOUT` | 0 | No whole answer within 10 seconds (`timeout`), however slowly it arrives |
| `NETWORK_ERROR` | 0 | The request could not be sent, or the answer was cut short or larger than 32 MiB |
| `UNEXPECTED_REDIRECT` | 3xx | MDRN answered with a redirect, which is never followed |
| `HTTP_ERROR` | 4xx, 5xx | A failure without MDRN's error envelope |
| `INVALID_REQUEST`, `CONFLICT`, `NOT_FOUND`, `TEMPLATE_NOT_FOUND`, ... | 4xx, 5xx | The code from MDRN's envelope |
| `UPLOAD_FAILED`, `OBJECT_REJECTED` | 0 | An upload did not accept parts, or MDRN rejected the bytes |

`get` methods answer `None` for a 404 instead of raising. `code` comes from MDRN's envelope
(`{"error": {"code", "message"}}`), or is `HTTP_ERROR` when the body is not one. A redirect is
`UNEXPECTED_REDIRECT`: never followed, so the token cannot reach another origin. Nothing is
retried except the conflict loop of `update` and `delete` and a database that is still
starting (`DATABASE_STARTING`, up to a minute). The product URLs must be https;
plain http is accepted only to `localhost`, `127.0.0.1` or `[::1]`. Bad arguments (a
`version` that is not a positive integer, a file without a name or bytes, a template with
content) raise `TypeError` or `ValueError` before any request.

```python
try:
    mdrn.sqlite.update("tasks", id, patch, version=version)
except MdrnError as error:
    if error.code == "CONFLICT":
        ...  # reload
    else:
        raise
```

## Testing

The SDK has no fake of its own in Python; the conformance server, the JavaScript SDK's in-memory
MDRN behind `node:http`, serves any language on this machine: the 24 operations with the real
response shapes, status codes and error codes, idempotent replay, upload sessions with grants, a
mail queue with the template rule, `/v1/auth/me` for a signed-in user, and a log of every
request. `node sdk/conformance/server.mjs` prints its port; `GET /_fake/log` shows the requests,
`POST /_fake/reset` starts over.

```python
mdrn = Mdrn(origin=f"http://127.0.0.1:{port}", project="project_one", environment="sandbox",
            tokens={"sqlite": "sqlite-token", "postgres": "postgres-token", "objects": "objects-token", "mail": "mail-token"})
headers = {"x-mdrn-user-id": "user_1", "x-mdrn-identity-token": "identity-token-1"}  # the signed-in user
```

Without a server, give `transport=` a callable that answers `mdrn_sdk._core.Response` objects
for the `Request` it receives, as `tests/test_client.py` does. Some collection names reach error
paths, in either database: `broken` (502 without an envelope), `redirected` (307), `contended`
(every read bumps the version), `starting` (its first request is 503 `DATABASE_STARTING` with
`Retry-After: 0`) and `starting-long` (always that 503, with a `Retry-After` past the minute). [`examples/round_trip.py`](examples/round_trip.py) uses most of the SDK;
`PYTHONPATH=src python -m unittest discover -s tests` runs it and the conformance scenarios
against the server (node is needed for those two suites; they are skipped without it).

## Versions

`0.4.0`, shared with the other languages (`sdk/VERSION`, `sdk/CHANGELOG.md`). All four SDKs
produce the same transcript against the same scenarios: `sdk/conformance/`
(`tests/conformance.py` is the Python runner).

## Contributing

This repository is a mirror: the code is published here from MDRN's main repository on every
release, where it is tested against the API contract together with the other SDKs. Issues are
welcome here. Pull requests are reviewed here and merged in the main repository, from where the
next release brings them back.
