Metadata-Version: 2.3
Name: encore-dev
Version: 2.0.0b17
Summary: Encore SDK for Python — infrastructure resources
Author: Encore
License: MPL-2.0
Classifier: Programming Language :: Python :: 3
Requires-Dist: opentelemetry-api>=1.27
Requires-Dist: typing-extensions>=4.13
Requires-Dist: aiohttp>=3.14.4 ; python_full_version >= '3.10' and extra == 'aiohttp'
Requires-Dist: connectrpc>=0.13.0,<0.14 ; python_full_version >= '3.11' and extra == 'grpc'
Requires-Dist: protobuf-py==0.7.0 ; python_full_version >= '3.11' and extra == 'grpc'
Requires-Dist: pyqwest>=0.14 ; python_full_version >= '3.11' and extra == 'grpc'
Requires-Dist: httpx>=0.27 ; extra == 'httpx'
Requires-Dist: niquests>=3.19 ; extra == 'niquests'
Requires-Dist: requests>=2.34 ; python_full_version >= '3.10' and extra == 'requests'
Requires-Python: >=3.9
Provides-Extra: aiohttp
Provides-Extra: grpc
Provides-Extra: httpx
Provides-Extra: niquests
Provides-Extra: requests
Description-Content-Type: text/markdown

# Encore SDK for Python

The Python SDK for [Encore](https://encore.dev) — **infrastructure resources only**.

Declare infrastructure (SQL databases, Pub/Sub topics and subscriptions, object
storage buckets, Redis databases, cron jobs, metrics, and secrets) as
module-level variables. Encore discovers these declarations, provisions the
resources, and connects your application to them at runtime.

Services are declared in language-agnostic `encore.service.json` files, not in
Python. Use the SDK with your preferred Python web framework.

## Installation

Requires Python 3.9 or later. Install from PyPI with pip:

```sh
python -m pip install encore-dev
```

Or add it to a uv project:

```sh
uv add encore-dev
```

## Declare resources

```python
from encore import pubsub, secrets
from encore.storage import postgres

db = postgres.Database("orders", migrations="./migrations")
events = pubsub.Topic("order-events", exactly_once=True)
api_key = secrets.Secret[str]("ApiKey")


async def place_order(order):
    await db.exec("INSERT INTO orders (id) VALUES ($1)", order.id)
    await events.publish({"id": order.id})
```

## Secrets

`secrets.Secret[str]("Name")` belongs to the service that declares it.
`secrets.Secret[str]("Name", scope="shared")` defines a single secret for the
whole app that is granted to services that read it, and `scope="global"` defines
a secret that is granted to every service. `value` reads the secret as a string.
Locally (`encore run`, `encore test`), an unset secret returns `""` because
secrets have no default value until configured; in all other environments,
reading an unset secret raises `KeyError`. A secret's value is resolved once per
process, so a new value takes effect when the service restarts.

A shared secret is declared once in the app. Because another Python service
cannot import the declaring service's modules, it references the secret by name
instead:

```python
from encore.secrets import Secret

support_email = Secret[str].named("SupportEmail")
```

Reading `value` grants the calling service access to that secret. The original
declaration can be in any language. Encore reports an error if a service
references a name that is not declared as a shared secret.

## Service URLs

Use `base_url` to look up a service's configured base URL:

```python
from encore.services import base_url

order = f"{base_url('orders')}/orders/123"
```

The returned string has no trailing slash, so you can append request paths
directly. Unknown service names raise `ValueError`. Lookup reads the runtime
configuration and makes no network request.

Looking up a service's URL creates a dependency on that service. Because Encore
detects these dependencies statically, pass the service name as a string
literal, call `base_url` directly rather than passing the function around, and
call it from inside a service.

### Calling services

To call a service, use the adapter for your HTTP client. Each adapter re-exports
`encore.services` and adds `client(service)`, which returns a client configured
with that service's base URL. For libraries that provide both async and sync
clients, `client(service)` returns the async client and `sync_client(service)`
returns the sync client:

```python
from encore.services import httpx as services

billing = services.client("billing")


async def invoices():
    response = await billing.get("/invoices")
    return response.json()
```

| Adapter | Install | `client` returns | `sync_client` returns |
|---|---|---|---|
| `encore.services.httpx` | `encore-dev[httpx]` | `httpx.AsyncClient` | `httpx.Client` |
| `encore.services.requests` | `encore-dev[requests]` | `requests.Session` | |
| `encore.services.aiohttp` | `encore-dev[aiohttp]` | `aiohttp.ClientSession` | |
| `encore.services.niquests` | `encore-dev[niquests]` | `niquests.AsyncSession` | `niquests.Session` |

The `requests` and `aiohttp` extras require Python 3.10 or later. On Python 3.9
they install nothing because their 3.9-compatible releases have known
vulnerabilities; the adapters instead use whichever version your app installs.

`client` and `sync_client` forward additional keyword arguments to the client's
constructor. Because `requests.Session` takes no constructor arguments, the
`requests` adapter sets those keyword arguments as attributes on the session
instead (for example, `client("billing", headers={"x-tenant": "a"}, verify=False)`)
and accepts a default `timeout` for requests that do not specify one. The same
static-analysis rules as `base_url` apply to the service name. Note that
`aiohttp` resolves relative URLs like browser links, so omit the leading slash
(`get("invoices")`); it also requires a running event loop to create a session,
so call `client()` inside a coroutine such as a lifespan handler.

Adapter clients propagate the current Request Context to services in your Encore
app and never to external hosts, including across redirects. If you build an
HTTP client yourself, you can get the same behavior using the adapter's hook:
`Transport` and `AsyncTransport` for `httpx`, `Adapter` for `requests`,
`middleware` for `aiohttp`, or `pre_request` for `niquests`.

### Generated clients

When a service lists another service under `clients` in its
`encore.service.json`, Encore generates typed clients under
`encore_gen/clients/`. Each target service gets a package containing one module
per entry in that service's `api` configuration, named after the entry's `name`
(defaulting to `openapi`, `graphql`, or `grpc` when `name` is omitted). Each
operation is an async function on its module and requires no upfront setup:

```python
from encore_gen.clients import catalog

product = await catalog.openapi.get_product("xyz")
products = await catalog.storefront.products(skus=["xyz"])
stuff = await catalog.grpc.stuff_service.do_stuff(catalog.grpc.DoStuffMessage())
```

Calls resolve the service's base URL on first use and automatically propagate
the current trace and Request Context. Calls have no timeout by default; every
call accepts `timeout` (in seconds, for the entire call) and `headers`:

```python
product = await catalog.openapi.get_product("xyz", timeout=2.0)
stuff = await catalog.grpc.stuff_service.do_stuff(
    catalog.grpc.DoStuffMessage(), headers={"x-tenant": "a"}
)
```

To share settings across multiple calls, instantiate the module's
`AsyncClient(base_url=None, *, timeout=None, headers=None, http_client=None)` —
for example, at module scope. A per-call `timeout` overrides the client's
default (`None` disables the timeout, which can be useful for long-lived
streams), and per-call `headers` override client headers. Clients share
underlying connections, so creating one for a single call is inexpensive:

```python
catalog_api = catalog.openapi.AsyncClient(timeout=10.0)

product = await catalog_api.get_product("xyz")
report = await catalog_api.export_products(timeout=120.0)

async with catalog.storefront.AsyncClient(headers={"x-tenant": "a"}) as client:
    products = await client.products(skus=["xyz"])
```

If an API schema defines a parameter named `timeout` or `headers`, the generated
parameter is renamed to `timeout2` or `headers2`.

Closing a client (including via `async with`) does not close shared connections
or an externally supplied `http_client`, which remains your responsibility to
close. If you pass a custom `httpx.AsyncClient`, configure it with
`transport=services.AsyncTransport()` so calls propagate Request Context. If you
pass a custom `transport` (such as a retrying or instrumented transport) to an
OpenAPI or GraphQL client instead, the SDK wraps it so calls still propagate
Request Context, and closing the client closes any connections it opened.

Failed calls raise `encore.services.CallError` regardless of API protocol:
- `code` is the `ErrCode` returned by the service (or derived from its HTTP
  status), `UNAVAILABLE` if no response was received, or `DEADLINE_EXCEEDED` if
  the call timed out.
- `message` describes what went wrong.
- `status` is the HTTP status code of the response, or `0` when no response was
  received.

GraphQL responses containing errors raise `GraphQLRequestError` (a subclass of
`CallError`), with the response's errors exposed on `errors`. For gRPC errors,
`details` contains the decoded `protobuf-py` status details (or the raw
`protobuf.wkt.Any` value for types not present in the client's proto files).

```python
from encore.errs import ErrCode
from encore.services import CallError

try:
    product = await catalog.openapi.get_product("xyz")
except CallError as error:
    if error.code is not ErrCode.NOT_FOUND:
        raise
    product = None
```

Generated gRPC modules speak gRPC over HTTP/2 using `connectrpc`, so they can
call any gRPC server: `h2c` for `http://` URLs and TLS for `https://` URLs,
trusting the system certificate store as well as `SSL_CERT_FILE` and
`SSL_CERT_DIR`. Server-streaming and bidirectional-streaming RPCs return an
async iterator; client-streaming and bidirectional-streaming RPCs accept an
async iterable of requests. Messages use `protobuf-py` types generated by
`protoc-gen-py` into `encore_gen/protos/` (one module per `.proto` file, shared
across all clients of the service). Each gRPC module re-exports the service's
top-level messages and enums along with any well-known types used by its RPCs:

```python
async for update in catalog.grpc.stuff_service.watch_stuff(
    catalog.grpc.WatchRequest(), timeout=30.0
):
    print(update)
```

gRPC calls follow `connectrpc` semantics, with `CallError` exposing the mapped
`ErrCode`. The `timeout` is sent to the server as the RPC deadline and applied
to each network read, so a stream raises `DEADLINE_EXCEEDED` on the next read
after the deadline (messages already buffered in an earlier read may still be
yielded first). Cancelling the calling task fails the RPC with
`ErrCode.CANCELED` (which an `except CallError` block will catch unless you
re-raise it). An exception raised by a client-stream request iterator fails the
RPC with `ErrCode.UNAVAILABLE` and sets that exception as `__cause__`.

OpenAPI and GraphQL modules require `httpx` (`encore-dev[httpx]`), and gRPC
modules require `connectrpc` and `protobuf-py` (`encore-dev[grpc]`, Python 3.11
or later). Modules are imported lazily on first use, so a service only needs the
extras for the clients it actually uses.

## Request Context

Request Context fields are typed values that travel with a request to every
service it reaches, such as the authenticated user. Declare a field once at
module scope with its name and value type:

```python
from dataclasses import dataclass

from encore import reqctx


@dataclass
class User:
    id: str
    admin: bool = False


current_user = reqctx.Field[User]("user")
tenant = reqctx.Field[str]("tenant", trace=True)
```

Read a field while handling a request, and set or clear it for outbound calls
made within a block:

```python
user = current_user.get()  # None when not set

with current_user.set(User(id="system")):
    await billing.get("/invoices")

with tenant.unset():
    ...
```

To reference a field declared in another service (in any language), look it up
by name and value type: `current_user = reqctx.Field[User].named("user")`.
Encore validates that the declared types match.

- `pubsub=True` also propagates the field on Pub/Sub messages published while
  the field is set, making it available in receiving subscription handlers.
- `trace=True` records the value on the request's spans as
  `encore.ctx.<name>`. Use it for identifiers useful for searching traces, never
  for secrets.

A request preserves every field it receives — including fields the service does
not declare — and forwards them on outbound calls made through `encore.services`
clients. Fields are never sent to external hosts. Each field's encoded value may
be at most 4 KiB (1 KiB when `pubsub=True`), and all fields on a request may
total at most 8 KiB; setting a larger value raises `ValueError`.

## Running the service

`encore.run(app)` runs your service. It serves an ASGI app (FastAPI, Starlette,
and others) using Encore's built-in HTTP server (built on Rust's `hyper`) and
manages the service lifecycle:

```python
import encore
from fastapi import FastAPI

app = FastAPI()

if __name__ == "__main__":
    encore.run(app)
```

- **Startup**: Binds the address Encore assigns to the service, runs the app's
  lifespan startup, starts accepting HTTP traffic, and starts Encore's Pub/Sub
  subscriptions. Exits with status `1` if startup fails.
- **Requests**: Supports HTTP/1.1 and HTTP/2 (`h2c`). Each request runs with its
  Request Context and a trace span continuing the incoming trace. The server
  records the span from request arrival to response completion, named using the
  deployed route when available; application code can access it via
  `trace.get_current_span()`.
- **Shutdown**: On `SIGTERM` or `SIGINT`, stops accepting new connections and
  Pub/Sub deliveries, waits for in-flight requests to finish, runs the app's
  lifespan shutdown, and cleans up Encore resources within Encore's shutdown
  deadline. Requests waiting for client disconnect (such as event streams) are
  notified that the client disconnected. A second Ctrl-C stops waiting.

For a service without an HTTP API (for example, a Pub/Sub worker), call
`encore.run()` with no arguments to get the same lifecycle management without
starting an HTTP server.

- `threads=N` runs `N` independent event loops on separate threads sharing the
  same app. This requires free-threaded Python with the GIL disabled
  (`python3.14t`), where the loops execute in parallel. Each loop runs the app's
  lifespan with its own `state`, keeping loop-bound resources isolated.
- `max_concurrency` limits the number of requests handled simultaneously.
- `read_timeout` (default 30 seconds) limits how long a client may take to send
  request headers, a small body up to 64 KiB (returning `408` on timeout), or
  each chunk of a larger body (signaling client disconnect on timeout).
- `tracing=False` disables server tracing while still propagating Request
  Context.
- WebSockets are not supported yet.

To run a WSGI app (Flask, Django's WSGI application), wrap it in a WSGI-to-ASGI
adapter such as `a2wsgi`. The adapter executes the WSGI app on a thread pool
within the request's context, so Request Context is available and propagated on
outbound calls:

```python
import encore
from a2wsgi import WSGIMiddleware
from flask import Flask

app = Flask(__name__)

if __name__ == "__main__":
    encore.run(WSGIMiddleware(app))
```

The generic WSGI-to-ASGI adapter does not provide a route template.

FastAPI can record its own server, dependency, endpoint, and serialization spans
when configured with a tracer provider. `encore.run` disables FastAPI's built-in
server spans by default so each request produces a single server span. To let
FastAPI record its own spans instead, pass `server_spans=False` and configure
its tracer provider explicitly:

```python
from encore.tracing import tracer_provider

app = FastAPI(telemetry={"tracer_provider": tracer_provider()})
encore.run(app, server_spans=False)
```

`encore.run` and server middleware leave global OpenTelemetry trace, meter, and
logger providers unchanged.

If you run your app on your own HTTP server, add Encore's middleware instead to
get the same Request Context and tracing integration:

```python
from encore.server import asgi, wsgi

app.add_middleware(asgi.Middleware)  # FastAPI, Starlette
app = wsgi.Middleware(app)  # Flask, Django's WSGI application
```

The middleware works alongside OpenTelemetry instrumentation: when placed inside
OpenTelemetry's middleware (as `FastAPIInstrumentor` configures), Encore attaches
to OpenTelemetry's server span; when placed outside it, OpenTelemetry records an
internal span under Encore's server span.

### Server span names

Encore names server spans `METHOD /route/{param}` when a deployed policy
matches. Otherwise, it uses the registered template from framework dispatch, or
just `METHOD` when no template is available. Unrecognized HTTP methods use
`HTTP` in the span name, `_OTHER` in `http.request.method`, and the original
method in `http.request.method_original`. A framework template does not
authorize recording the request URL or headers.

For framework-aware route names without a deployed policy, use the framework's
OpenTelemetry instrumentation with Encore's tracer provider. Disable Encore's
server spans (`encore.run(app, server_spans=False)`) or pass `tracing=False` to
the middleware to avoid recording a second server span.

## Postgres queries and handles

Declare `postgres.Database("orders", migrations="./migrations")` at module scope.
`migrations` is optional and keyword-only. Use `Database.named("orders")` to
reference a database declared elsewhere.

`query(sql, *params)` returns a `Cursor`. Use `async for` to stream rows,
`await query.one()` to fetch exactly one row (raising `EncoreError` on no rows or
more than one), `await query.first()` to fetch the first row or `None`, or
`await query.all()` to collect all rows in a list. Each query can be consumed
once. Reusing it or mixing helpers with iteration raises `EncoreError`, including
after partial iteration or an error. Helpers close their cursors automatically.
For an early exit from streaming, use `async with db.query(...) as query:`.
Entering the context does not execute SQL. Exiting it closes the query.

`exec(sql, *params)` returns an `ExecResult` with `rows_affected`. Rows are
dictionaries keyed by column name. Values are bound with `$1`, `$2`, etc.

Column values use the same Python types as `asyncpg` and `psycopg`. `numeric` is
a `decimal.Decimal` that preserves the column's scale (for example, a
`numeric(10,2)` holding `7` returns `Decimal('7.00')`), and `NaN` and
`±Infinity` map to `Decimal('NaN')` and `Decimal('Infinity')`. `timestamptz` is
a timezone-aware `datetime.datetime` in UTC, `timestamp` is a naive
`datetime.datetime`, and `date` and `time` are `datetime.date` and
`datetime.time`. `bytea` is `bytes`, arrays are lists of their element types,
JSON is decoded, and `uuid`, `inet`, and `cidr` are strings. Parameters accept
the same types; a naive `datetime` bound to a `timestamptz` is treated as UTC,
and an aware `datetime` may use any `tzinfo`, including `zoneinfo.ZoneInfo`.

```python
async def find_order(database: postgres.Queryable, order_id: int):
    return await database.query("SELECT * FROM orders WHERE id = $1", order_id).first()


async def handle_order(order_id: int):
    return await find_order(db.read(), order_id)
```

`DatabaseRef`, `Connection`, and `Transaction` implement the nominal `Queryable`
interface. `Database` exposes the same query methods but deliberately does not
implement `Queryable`. Encore rejects passing or aliasing the declaration;
select `read()`, `write()`, or `admin()` before handing it to another function.
Direct database operations infer writer permissions. Reference creation records
reader, writer, or admin permissions at that call site.

Handles share the database's pool. A `read()` handle runs on
read-only connections, so its writes fail with SQLSTATE 25006 and its
transactions are read-only; it reads from the database's read-only pool on a
replica if the runtime config has one, unless `primary=True` is set.

```python
async def rename_order(order_id: int, name: str):
    async with db.acquire() as conn:
        async with conn.begin() as tx:
            result = await tx.exec(
                "UPDATE orders SET name = $1 WHERE id = $2", name, order_id
            )
        return result.rows_affected
```

Both `begin()` and `acquire()` can be awaited or used as async context managers.
Transaction contexts commit on a clean exit and roll back on exceptions;
connection contexts return the connection to its pool. A connection cannot be
used or closed while its transaction is active. Closed handles reject queries.

Streaming queries borrow their connection or transaction until exhausted or
closed. If you stop early, close the stream explicitly before reusing its owner:

```python
async def first_order():
    async with db.acquire() as conn:
        async with conn.query("SELECT * FROM orders ORDER BY id") as rows:
            async for row in rows:
                return row
```

## Pub/Sub payloads

Use `pubsub.Subscription[T]` to choose how payloads are decoded. Encore validates
the type argument when subscriptions start. Omitting it selects ordinary JSON
decoding. Handler annotations guide type checking but do not select the decoder.

```python
from pydantic import BaseModel


class Order(BaseModel):
    id: str


async def process_order(message: pubsub.Message[Order]) -> None:
    print(message.data.id)


processed = pubsub.Subscription[Order](events, "process-order", handler=process_order)
```

Supported payloads are JSON values, bytes, and top-level Pydantic v2 models
(when Pydantic is installed). `pubsub.JSON` and `pubsub.Payload` describe these
public types. Use `Subscription[pubsub.JSON]` for plain JSON: decoding returns ordinary
Python values without validating or constructing nested types. Use a Pydantic
model when fields need validation or nested models need construction.

`Subscription[bytes]` returns the payload unchanged. Unparameterized `Subscription`
decodes ordinary JSON. Dataclasses, model unions, models nested in plain JSON
containers, and string forward references are not supported; wrap nested models
in a top-level Pydantic model and pass that class directly. Original bytes remain
available as `message.raw_data`. Payloads are decoded once before the handler is
called; decoding errors propagate for normal retry handling.

## Gateway Middleware

A service with a `gateway` section in its `encore.service.json` hosts the app's
gateway and serves it using `Middleware` — code that authenticates, rate-limits,
logs, or meters public requests passing through the gateway. Encore runs this
service on the gateway variant of the native runtime.

```python
import asyncio
from dataclasses import dataclass

import encore
from encore import gateway, reqctx
from encore.errs import ErrCode
from encore.gateway import match


@dataclass
class User:
    id: str


current_user = reqctx.Field[User]("user")


class Authenticate(gateway.Middleware):
    match = match.path_prefix("/api")

    async def on_request(self, req: gateway.Request) -> None:
        user = await verify(req.header("authorization"))
        if user is None:
            raise gateway.reject(ErrCode.UNAUTHENTICATED, "missing token")
        req.set(current_user, user)


async def main() -> None:
    await encore.start()
    await gateway.serve(Authenticate())


asyncio.run(main())
```

Each `Middleware` runs only for the hooks it defines (`on_request`,
`on_request_body`, `on_response`, `on_response_body`, `on_complete`) and only
for requests matching its `match` rule. Encore evaluates `match` before a
request reaches Python. Hooks can read any header, query parameter, or cookie;
each value is fetched lazily into Python only when read. Encore validates
subclasses at class definition time, so misspelled hook names raise immediately.

`on_request` sets Request Context fields with `req.set(field, value)`. Downstream
services read these fields with `field.get()`, and external clients cannot spoof
them. Every hook runs inside the request's trace and Request Context, so hooks
can read fields with `field.get()` or `req.get(field)`, and outbound service
calls made from hooks automatically propagate both.

`gateway.serve` handles `SIGTERM` while running so active hooks can finish
during gateway draining, and returns once shutdown completes.

## Application-owned shutdown

Without a shutdown hook, Encore shuts down non-cooperatively when the
interpreter exits: after the server drains, it drains Pub/Sub and flushes
telemetry. On import, the SDK also installs a `SIGTERM` handler (unless one is
already set or the process is running tests) that exits with `0` if shutdown
completes in time, or `1` otherwise.

Use cooperative shutdown when application tasks may still use Encore resources.
The following hook accepts a framework-specific callback that stops new
application work and waits for existing work to finish:

```python
from typing import Awaitable, Callable

from encore import shutdown


async def on_shutdown(
    stop_and_drain_application: Callable[[], Awaitable[None]],
) -> int:
    shutdown.begin(cooperative=True)

    await stop_and_drain_application()
    shutdown.mark_application_drained()

    result = await shutdown.completed()
    return result.code()
```

Connect this hook to the host's shutdown lifecycle. Keep its event loop and the
Encore runtime alive until cleanup completes. The host should enforce its own
overall shutdown deadline and decide when to terminate the process.

Call `begin()` before awaiting phase helpers. With cooperative shutdown, signal
application draining before awaiting `cleanup()` or `completed()`; otherwise
Encore waits for that signal until its deadline expires.

If application work has already drained, use non-cooperative shutdown:

```python
from encore import shutdown


async def stop_encore() -> int:
    shutdown.begin()  # cooperative=False
    result = await shutdown.completed()
    return result.code()
```

`begin()` returns immediately. All callers share the same shutdown process, and
the first call chooses the cooperative mode. Repeated calls do not restart
cleanup, change the mode, or reset the deadline. Cancelling an individual waiter
does not cancel background cleanup.

## Phases and observation

| Phase | Meaning |
| --- | --- |
| `NOT_STARTED` | Shutdown has not started. |
| `STARTED` | Pub/Sub intake has been signalled to stop. Encore is waiting for message handlers and, in cooperative mode, application draining. |
| `CLEANUP` | Encore has stopped waiting for draining and is performing resource cleanup. |
| `COMPLETED` | The cleanup task has finished, including if it failed. Check the result or exception. |

`phase()` reads the current phase synchronously. `await started()` and
`await cleanup()` wait until shutdown has reached **or passed** their respective
phases. They return immediately if the phase has already passed.

`await completed()` waits for actual cleanup completion, including after the
deadline. These waits are independent: callers do not need to await every phase
in sequence. Reading `phase()` is valid before `begin()`; waiting for a phase
before `begin()` raises `ShutdownError`.

`CLEANUP` closes SQL, Redis, and object-storage resources concurrently, then
exports final metrics and flushes tracing. Retaining a database, cache client,
bucket, or object handle does not keep its connections usable after cleanup.
New operations fail; interrupted object downloads report an error rather than
returning a partial body as success, and Redis subscriptions end.

Drain application work before signalling `mark_application_drained()`. Forced
cleanup cancels Encore-owned resource I/O even if application tasks are still
running. External clients created from connection URLs are owned by your
application. Cloud SDKs release their HTTP pools when their clients are dropped;
best-effort S3 multipart abort requests may outlive `completed()` and require a
running executor to finish.

## Deadline and forced cleanup

The core deadline defaults to five seconds, configured by
`deployment.graceful_shutdown.total` in the runtime configuration. It starts
when shutdown is first begun and covers both draining and cleanup.

When the deadline expires:

1. Encore records `Timeout` in the shared state.
2. If draining is still in progress, Encore stops waiting for it and enters
   `CLEANUP`, even without an application-drained signal.
3. Cleanup continues. `completed()` returns only after the cleanup task finishes.

The timeout is sticky: finishing later does not change it to success. It is not
a hard upper bound on how long `completed()` can wait. The controller does not
exit the process when its deadline expires.

To skip draining before the deadline, request forced cleanup:

```python
from encore import shutdown


async def force_remaining_cleanup() -> int:
    # Shutdown must already have been started with begin().
    shutdown.force_cleanup()
    await shutdown.cleanup()  # Observe the transition; cleanup is not done yet.
    result = await shutdown.completed()
    return result.code()
```

`force_cleanup()` returns immediately and is idempotent. It raises
`ShutdownError` before `begin()`. Once resource cleanup has started, forcing it
again has no effect. Forcing alone does not record `Timeout`: successful cleanup
before the deadline still returns `SUCCESS`.

Both the deadline and explicit forcing abandon the drain wait; they do not kill
active handlers. Those handlers may continue using resources while cleanup runs.
The host must account for this when choosing when to force cleanup.

## Results and errors

| Python outcome | Meaning |
| --- | --- |
| `ShutdownResult.SUCCESS` | Cleanup finished before the deadline. Explicit forcing may have skipped draining. `code()` returns `0`. |
| `ShutdownResult.TIMEOUT` | The deadline expired before cleanup finished. The returned result still means the cleanup task has now finished. `code()` returns `1`. |
| `ShutdownError` | The core reported cleanup failure or progress could not be observed, including waiting before `begin()`. |

The SDK maps native `Failed` to `ShutdownError`; it does not return the public
`FAILED` enum member from `completed()`. Native progress errors are translated
to `ShutdownError` with the original `EncoreError` retained as their cause.
An unrecognized native enum value raises `ValueError`.

If cleanup panics after the deadline has already recorded `Timeout`, the core
logs the failure and preserves `Timeout` as the reported result. A timeout is
not evidence that all cleanup operations eventually succeeded.

## Resource initialization

Importing the SDK synchronously initializes the Encore runtime. Run applications through Encore so runtime configuration is available
before imports. Initialization failures surface during import, before normal
application startup completes.

Buckets, SQL databases, pub/sub topics, and secrets store their declarations and
resolve native handles on first use, caching the results with thread-safe
initialization. These lookups are synchronous against the already initialized
runtime. Importing application modules requires the configured runtime and native
extension. Use `encore test` to run application tests with Encore-managed
resources.

Initialize independently in each worker process. Forking an already initialized
native runtime is not supported by this startup model.

## Logs

Write structured application logs with a message and fields:

```python
from encore import logs

logs.info("Order placed", order_id=42, items=3)
```

`logs.debug`, `info`, `warning`, `error`, and `critical` take a positional
message and structured keyword fields. `logs.exception` logs the active
exception at error level. Helper fields cannot replace metadata or trace
correlation: `message`, `level`, `time`, `logger`, `trace_id`, `span_id`,
`sampled`, `service.name`, `exception.type`, `exception.message`,
`exception.stacktrace`, `code.function.name`, `code.file.path`,
`code.line.number`, `code.column.number`, and `encore.runtime.target` are
reserved, as are `LogRecord` attributes, methods, and factory-added attributes. Collisions gain `raw.` prefixes until the key
conflicts with neither record attributes nor other supplied fields. For
example, `logs.info("charged", level="fatal")` keeps level `info` and writes
`raw.level="fatal"`; if `raw.level` is also supplied, the `level` field
becomes `raw.raw.level`. Keyword arguments are fields, not Python logging
options. Direct `StructuredLogHandler` usage retains its reserved-key behavior:
valid reserved-key attributes can override the corresponding output fields.

The helpers use the standard `encore.logs` logger. With no application
handler, they write Encore-formatted lines to stderr without changing the
root logger. The fallback uses INFO when root remains WARNING with no handlers;
setting root WARNING alone is indistinguishable from the default. To suppress
INFO, set `encore.logs` to WARNING or install an application handler with the
desired level. Other explicit levels, filters and disabling are respected.
Application handlers replace the fallback, without duplicate output.
To enable debug output:

```python
import logging

logging.getLogger("encore.logs").setLevel(logging.DEBUG)
```

### Python logging

Use `StructuredLogHandler` for structured JSON output from standard Python loggers:

```python
import logging

from encore.logs import StructuredLogHandler

logging.basicConfig(level=logging.INFO, handlers=[StructuredLogHandler()])
```

### OpenTelemetry

Encore collects process output and exports it through an out-of-process
collector as OpenTelemetry logs over OTLP. Encore-formatted logs preserve
structured fields, severity and current trace/span IDs, including those from
OpenTelemetry instrumentation. Other output is collected as unstructured text.
Use the helpers or Python `logging` with `StructuredLogHandler` for structured logs;
global OpenTelemetry logger providers are unchanged.

## Traces

Create spans around application work:

```python
from encore import tracing

with tracing.span("place_order", attributes={"order.id": order_id}) as span:
    span.set_attribute("order.items", 3)
    with tracing.span("validate_order"):
        ...
```

A span becomes current inside its block. Nested spans inherit its trace; spans
end on block exit, and uncaught exceptions are recorded as failures and
propagate. Use regular `with` blocks in async code too.

### OpenTelemetry

Encore spans share OpenTelemetry context. Obtain a tracer directly from Encore's
provider for standard trace API calls:

```python
from encore.tracing import tracer_provider

tracer = tracer_provider().get_tracer(__name__)

with tracer.start_as_current_span("place_order") as span:
    span.set_attribute("order.id", order_id)
```

Optional `opentelemetry-instrumentation-*` packages instrument frameworks and
libraries. Pass the provider directly, for example
`FastAPIInstrumentor().instrument_app(app, tracer_provider=tracer_provider())`,
or opt in once if your app owns global OpenTelemetry setup:

```python
from opentelemetry import trace

trace.set_tracer_provider(tracer_provider())
```

Encore always uses its cached, owned provider for SDK-created spans,
independent of the global provider. `tracing.span`, `encore.run` and server
middleware leave global trace, meter and logger providers unchanged.

## Telemetry redaction

`encore.redaction.redactor()` applies the service's deployed policy to telemetry
copies. It neither changes application traffic nor emits telemetry. Unknown
routes omit URL fields; never fall back to the originals. Record `Payload.body` only
when set; `withheld` explains withholding, and both unset means omit.

Select HTTP policy with `redactor().http(method, path_and_query)`.
`request_url()` returns optional `route`, `path`, and `query` strings.
`request(headers=original_headers, body=wire)` and
`response(headers=original_headers, body=wire)` return safe `headers` and an
optional `body: Payload`. Headers, metadata, and trailers are `(str, str)` pairs;
duplicates are preserved. Pass original headers so body decoding uses wire
encoding. Omit `body` or `message` to skip capture; empty bytes request capture.
Use `redactor().topic(name).publish(wire)` for publishing and
`redactor().topic(name).delivery(subscription, wire)` for delivery.

Use `redactor().grpc(method)` with protobuf-py's `protobuf.DescMethod`, obtained
from a generated service descriptor or `registry.service(name).methods`. This
uses `parent.type_name` and `method_kind`, not Google's `MethodDescriptor` API.
The optional `encore-dev[grpc]` extra supplies protobuf-py on Python 3.11+;
HTTP and topic redaction require no protobuf library. Pass unframed message
bytes to `request(metadata=original_metadata, message=wire)` or
`response(metadata=original_metadata, message=wire, trailers=original_trailers)`.
Results contain safe `metadata`, optional `message: Payload`, and `trailers`. Streaming
*directions* are withheld; the unary direction of a streaming RPC still uses
its deployed policy.

### Third-party spans

Encore redacts the request path and user agent it records in its own server
spans. It does **not** sanitize arbitrary span names, attributes, events,
exceptions, or logs, including third-party framework spans exported through
`tracer_provider()`. Passing Encore's provider is not a redaction boundary.

FastAPI's native telemetry and OpenTelemetry's FastAPI/Starlette/ASGI/WSGI
instrumentation can record original paths, URLs, query strings, and headers.
For example, `encore.run(app, server_spans=False)` leaves FastAPI's request span
unredacted even when the deployed policy marks its path parameter sensitive.
Encore middleware inside third-party instrumentation likewise leaves that
instrumentation's span unchanged. The shared provider cannot reliably identify
all request-derived values in user attributes, events, or instrumentation hooks;
it does not rewrite those spans or application requests.

Keep `encore.run`'s default server spans (which suppress FastAPI's native request
telemetry), and disable separate request instrumentation when relying on
Encore's automatic request metadata redaction. For custom instrumentation,
redact telemetry copies explicitly before recording them; avoid recording
original requests, exceptions, or headers containing secrets.

## Metrics

Declare metrics at module scope: `Counter` for increasing totals,
`UpDownCounter` for totals that can decrease, `Gauge` for current values, and
`Histogram` for distributions. Each has a `…Group` form whose labels are defined
as a `TypedDict` or dataclass:

```python
from dataclasses import dataclass

from encore import metrics


@dataclass(frozen=True)
class Labels:
    route: str


latency = metrics.HistogramGroup[Labels]("request_duration", unit="s")

latency.with_labels(Labels("/orders")).record(0.025)
```

A service-scoped metric (the default scope) is exported as `<service>.<name>` —
for example, `request_duration` in the `shop` service is exported as
`shop.request_duration`. Shared (`scope="shared"`) and global (`scope="global"`)
metrics keep their plain name and are declared once: other modules in the same
language import the declaration, while services in another language reference it
by name (for example, `metrics.CounterGroup[Labels].named("responses_total")`).
To pass a metric to another function, obtain a reference with `latency.ref()`.

Metric names and scopes must be string literals. Names must start with a letter
and may contain letters, digits, `_`, `.`, `-`, or `/`. Label keys must be
`snake_case`, and label values must be `str`, `int`, or `bool` (other types
raise `TypeError`). `unit`, `description`, and a histogram's `buckets` must be
literals so Encore's static analyzer can read them.

### OpenTelemetry

Encore metric declarations use the `encore` meter. Obtain a meter from Encore's
provider for standard metrics API calls:

```python
from encore.metrics import meter_provider

meter = meter_provider().get_meter("orders")
orders = meter.create_counter("orders_placed", unit="{order}")
orders.add(1, attributes={"outcome": "success"})
```

These instruments are exported alongside Encore metrics, with their names
unchanged. The meter's instrumentation scope (`orders` here) is distinct from
an Encore declaration's service/shared/global scope. The process resource
identifies the service recording them. Use the standard API for observable
instruments or attributes beyond Encore's label types.

Encore declarations always use the cached, owned meter provider, independent
of the global provider. Pass `meter_provider()` directly to instrumentation,
or opt in once if your app owns global OpenTelemetry setup:

```python
from opentelemetry import metrics

metrics.set_meter_provider(meter_provider())
```

Encore leaves global trace, meter and logger providers unchanged, including in
`encore.run` and server middleware.

## Object storage

Declare a bucket at module scope, then use its async methods:

```python
from encore.storage import objects

uploads = objects.Bucket("uploads")


async def example() -> None:
    await uploads.upload(
        "hello.txt",
        b"Hello!",
        content_type="text/plain",
        if_not_exists=True,
    )
    attrs = await uploads.attrs("hello.txt")
    present = await uploads.exists("hello.txt")
    download = await uploads.download("hello.txt", offset=0, length=5)
    part = await download.read()
    async for entry in uploads.list(prefix="hello", limit=10):
        print(entry.name, entry.size, entry.last_modified)
    download_url = await uploads.signed_download_url("hello.txt", ttl=3600)
    await uploads.remove("hello.txt")
```

`attrs`, `exists`, `download`, and `remove` accept a keyword-only `version`.

`download` returns as soon as the provider responds with object metadata, before
reading the body, so a missing object or an invalid byte range raises
immediately. The returned `Download` exposes object metadata (`revision`,
`size`, `content_type`, `last_modified`) and streams the bytes via
`await download.read()` (to read the entire body) or `async for chunk in download`
(to stream chunks as they arrive). Request a byte range with `offset` and
`length`, or `last=n` for the last `n` bytes; `size` always reports the full
object size.

To replace or delete an object only if it has not been modified since you read
it, pass the download's revision to `upload_if_match` or `remove_if_match`:

```python
async def bump() -> None:
    download = await uploads.download("counter")
    count = int(await download.read())
    try:
        await uploads.upload_if_match(
            "counter", str(count + 1).encode(), download.revision
        )
    except objects.PreconditionFailed:
        ...  # someone else wrote it first; read it again
```

`Revision` values are opaque. Two revisions are equal when they identify the
same object version, regardless of whether they came from a `Download` or from
`attrs.revision`. You can also pass an `ObjectAttrs` directly wherever a
`Revision` is expected.

`signed_upload_url` and `signed_download_url` return URL strings (`str`);
TTL is in seconds, defaults to one hour, and must be between 1 and 604800.
`public_url` is synchronous and requires a public bucket. `Bucket.named(name)`
looks up an existing bucket configured for the service.

Storage failures raise `ObjectsError` (an `EncoreError` subclass), with
`ObjectNotFound`, `PreconditionFailed`, and `InvalidArgument` for specific cases.
`exists` returns False for missing objects and raises on other storage failures.
If leaving a listing early, use `contextlib.aclosing(bucket.list(...))` to close
the native stream promptly.

For large objects, `upload_stream(name, chunks)` consumes an asynchronous iterable
of `bytes` with backpressure. It supports the same `content_type` and
`if_not_exists` options as `upload`. The native pipe is limited to 64 KiB, and
each write across the native boundary is at most 64 KiB. S3 multipart uploads retain at most four 8 MiB part payloads
and apply backpressure while waiting for the provider; completed parts retain
only their metadata. Other providers may use their own upload buffers.
The input iterable owns its chunks, so avoid producing the entire object at once.
Producer exceptions and cancellation abort the upload. The caller owns closing
an input generator that needs cleanup; cancellation cannot undo an upload the
provider has already committed.

Iterating a download yields provider-sized byte chunks, read on demand. Because
an unconsumed download holds its underlying connection open, wrap it with
`contextlib.aclosing` whenever iteration may stop early — including when piping
a download into another upload:

```python
from contextlib import aclosing


async def copy_large_object() -> None:
    async with aclosing(await uploads.download("source.bin")) as chunks:
        await uploads.upload_stream(
            "copy.bin", chunks, content_type="application/octet-stream"
        )
```

## Redis databases

Declare a database at module scope and call commands through its families:

```python
from encore.storage.redis import Database, ReadOnlyDatabaseRef

sessions = Database("sessions")


async def save_user():
    await sessions.string.set("user:1", b"hello", ex=60)
    return await sessions.string.get("user:1")  # bytes | None


async def load(reader: ReadOnlyDatabaseRef):
    return await reader.string.get("user:1")


async def handle_request():
    return await load(sessions.read())
```

By default, a Redis database acts as a cache: it may lose data and evicts
least-recently-used keys when it runs out of memory. Declare
`Database(name, persistent=True)` for durable storage. `Database.named(name)`
references a database declared elsewhere. Creating a database, selecting a
family, and creating a handle defer native lookup until first use. Direct
resource calls must keep the family and command together (as in
`sessions.string.get(...)`) so Encore can determine their permissions. To pass
access to another function or store a family interface in a variable, obtain a
`read()` or `write()` handle first.

Families are the properties `generic`, `string`, `bitmap`, `geo`, `hash`, `json`,
`list`, `set`, `sorted_set`, `stream`, `hyperloglog`, and `pubsub`. Read handles expose
only read operations, and the native runtime also rejects writes through them.
`read(primary=True)` requests primary access; the current runtime uses the primary
for all reads, including when this flag is false.

A pipeline sends multiple commands in a single round trip, and a transaction
(`MULTI`/`EXEC`) executes them atomically. Commands are queued through the same
families, each returning a `Queued` handle whose `value` holds the decoded
result after the batch runs. If any command fails, `execute()` raises
`BatchError`, and reading the failed command's `Queued.value` raises its
individual error:

```python
pipe = sessions.pipeline()
name = pipe.string.get[str]("name:1")
hits = pipe.string.incr("hits")
await pipe.execute()
print(name.value, hits.value)
```

`watch(keys, body)` runs `body(conn, tx)` as an optimistic transaction, retrying
whenever a watched key changes. `acquire()` checks out a dedicated connection
from the pool (`async with sessions.acquire() as conn:`). A `Script` executes by
its SHA-1 hash and automatically falls back to its source if the server has not
cached it. Because Encore only prefixes keys passed in `KEYS`, pass every key
the script touches via `key()`:

```python
RELEASE = Script(
    'if redis.call("get", KEYS[1]) == ARGV[1] then '
    'return redis.call("del", KEYS[1]) end return 0'
)
released = await sessions.script(RELEASE).key("lock:job").arg(token).invoke()
```

Blocking pop commands (`list.blpop`, `brpop`, `blmove`, `blmpop`,
`sorted_set.bzpopmin`, `bzpopmax`, `bzmpop`) take a keyword-only `timeout` in
seconds (`0` waits forever) and return `None` when the timeout expires. They
wait on a dedicated connection so they never block other commands, and
cancelling the task cancels the wait. Blocking commands cannot be queued in a
batch or run on an acquired connection. `bitmap.bitfield(key)` builds a
`BITFIELD` command (`.get()`, `.set()`, `.incrby()`, `.overflow()`, then
`await .invoke()`), and `generic.scan_iter()`, `hash.hscan_iter`,
`set.sscan_iter`, and `sorted_set.zscan_iter` iterate through a scan cursor to
completion.

Use `command(name)` to send a Redis command that is not covered by the typed
families. The command name must be a string literal:
`await sessions.command("OBJECT").arg("FREQ").key("hot").invoke()`. Before
sending the command, the runtime validates it against Redis's command table and
raises `CommandRefused` if any key argument was not passed with `key()`, if the
command would reach outside the database or alter shared connection state, or if
the SDK already provides a dedicated API for it (`MULTI`, `SUBSCRIBE`, `EVAL`,
`SCAN`, `FLUSHALL`, etc.). Commands rejected by the server raise `ServerError`,
whose `code` is the first word of the server error message (such as `WRONGTYPE`).

Keys and hash/stream field names are `str` inputs. Stored values, members, and
message payloads accept `Value`: `bytes`, `str`, `int`, `float`, or an implementation of
`RedisValue`. Strings are encoded as UTF-8, integers as decimal text, floats as
ASCII text using `repr()`, and bytes are sent unchanged. Booleans are not
supported as stored values. Floats include `nan` and infinities, which can be
stored and retrieved but may be rejected by Redis numeric commands.

Reads return bytes by default. Select a type with `command[str](...)`,
`command[int](...)`, `command[float](...)`, or a custom value class to decode
stored values. The return type follows the requested type:

```python
await sessions.string.set("visits", 42)
visits = await sessions.string.get[int]("visits")  # int | None

await sessions.string.set("balance", 1.25)
balance = await sessions.string.get[float]("balance")  # float | None

await sessions.list.rpush("names", "Ada", "Grace")
names = await sessions.list.lrange[str]("names", 0, -1)  # list[str]
```

`RedisValue` is a structural protocol: no base class or registration is required.
Implement `encode(self) -> bytes` and a class method `decode(cls, data: bytes)`
that returns an instance of the class:

```python
import json
from dataclasses import dataclass


@dataclass
class User:
    name: str

    def encode(self) -> bytes:
        return json.dumps({"name": self.name}).encode("utf-8")

    @classmethod
    def decode(cls, data: bytes) -> "User":
        return cls(**json.loads(data))


await sessions.string.set("user:1", User("Ada"))
user = await sessions.string.get[User]("user:1")  # User | None
await sessions.hash.hset("profiles", ("first", User("Ada")))
users = await sessions.hash.hgetall[User]("profiles")  # dict[bytes, User]
```

The same conversion applies to list elements, hash values, set/sorted-set/geo
members, stream field values, and pubsub payloads. For pubsub, use `subscribe[User](...)`
or `psubscribe[User](...)`; `Message.payload` then has that type.
Database keys, hash/stream field names, stream IDs, channel names, cursors,
scores, and other metadata retain their existing types. For commands that return
hash field names (`hkeys`, and `hrandfield` without values), the type parameter
applies to those field names — for example, `hkeys[str]` returns `list[str]`.
Custom value types are not recorded in Redis, so callers must specify the
matching decoder.

Missing values remain `None`, and empty collections remain empty. Malformed
UTF-8, invalid integers, and custom codec errors raise instead of becoming
`None`. Reads that also mutate data (for example `getdel`, `lpop`, or `set` with
`get=True`) execute before decoding: a decoding error does not undo the command.
`set[User](..., get=True)` decodes the previous value; without `get=True`,
`set` only accepts the default bytes response mode.

Multi-value operations accept variadic arguments, with tuples for grouped values,
for example
`db.hash.hset("user", ("name", b"Ada"))` and
`db.string.mget("first", "second")`. Unpack existing collections with `*items`.
Most commands require at least one item; `geo.geohash`, `geo.geopos`, and
`json.get` allow none. `json.mget` requires a keyword-only `path`, and
`sorted_set.zinterstore`/`zunionstore` keep `weights` as a keyword sequence.
Commands with structured, option-dependent
replies (including streams and geo searches) retain the native RESP structure:
lists/dictionaries containing bytes, numbers, and `None`. With `withscores=True`,
sorted-set ranges return `(member: bytes, score: float)` pairs.

`string.set()` returns `None` normally; with `get=True` it returns the previous
value. With `nx=True` or `xx=True` and no `get`, it returns `b"OK"` if the write
happened and `None` otherwise.

RedisJSON methods accept Python JSON values and decode document replies:

```python
await sessions.json.set("profile", "$", {"name": "Ada", "active": True})
profiles = await sessions.json.get("profile", "$")
```

JSONPath replies preserve arrays of matches. JSON requires a server with
RedisJSON support; the local emulator does not currently implement it.

Redis channel subscriptions are separate from Encore's `pubsub.Topic` API. Use
an async context manager to release the dedicated connection on exit:

```python
async def listen():
    async with await sessions.pubsub.subscribe("events") as messages:
        async for message in messages:
            print(message.channel, message.payload)  # both bytes
```

`psubscribe()` accepts glob patterns. `Subscription.receive()` returns a `Message`
or `None` after closure; `close()` interrupts pending receives and is safe to
repeat. Leaving the context also closes the subscription when the body raises or
is cancelled.

`db.connection_string` (also available on write handles) returns the direct server
URL and grants broad read-write access. External clients using that URL do not
apply Encore's key prefixes or tracing. Read-only handles do not expose this URL.
