Metadata-Version: 2.5
Name: drakaina
Version: 1.0.0rc2
Summary: Module for simple RPC service implementation
Project-URL: Homepage, https://gitlab.com/tau_lex/drakaina
Project-URL: Repository, https://gitlab.com/tau_lex/drakaina
Project-URL: Bug Tracker, https://gitlab.com/tau_lex/drakaina/-/issues
Author-email: Aleksey Terentyev <terentyev.a@pm.me>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright 2022-2023 Aleksey Terentyev (terentyev.a@pm.me)
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Keywords: jsonrpc,openrpc,rpc
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Web Environment
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Networking
Requires-Python: >=3.12
Requires-Dist: anyio<5.0,>=4.0
Requires-Dist: mashumaro<4.0.0,>=3.23
Provides-Extra: amqp
Requires-Dist: aio-pika<10.0.0,>=9.0.0; extra == 'amqp'
Provides-Extra: django
Requires-Dist: django<7.0,>=4.2.8; extra == 'django'
Requires-Dist: pyjwt<3.0.0,>=2.7.0; extra == 'django'
Provides-Extra: docs
Requires-Dist: docstring-parser<0.16,>=0.15; extra == 'docs'
Provides-Extra: jwt
Requires-Dist: pyjwt<3.0.0,>=2.7.0; extra == 'jwt'
Provides-Extra: msgpack
Requires-Dist: msgpack<2.0.0,>=1.0.5; extra == 'msgpack'
Provides-Extra: orjson
Requires-Dist: orjson<4.0.0,>=3.8.14; extra == 'orjson'
Provides-Extra: redis
Requires-Dist: redis<6.0,>=5.0; extra == 'redis'
Provides-Extra: ujson
Requires-Dist: ujson<6.0.0,>=5.7.0; extra == 'ujson'
Description-Content-Type: text/markdown

<p style="text-align: center;"><img src="https://gitlab.com/tau_lex/drakaina/-/raw/main/content/drakaina300.png" style="" /></p>
<h2 style="text-align: center;">drakaina</h2>

[![image](https://img.shields.io/pypi/v/drakaina.svg)](https://pypi.python.org/pypi/drakaina)
[![image](https://img.shields.io/pypi/l/drakaina.svg)](https://pypi.python.org/pypi/drakaina)
[![image](https://img.shields.io/pypi/pyversions/drakaina.svg)](https://pypi.python.org/pypi/drakaina)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v1.json)](https://github.com/charliermarsh/ruff)
[![OpenRPC](https://img.shields.io/endpoint?url=https%3A%2F%2Fgitlab.com%2Ftau_lex%2Fdrakaina%2F-%2Fraw%2Fmain%2Fcontent%2Fopenrpc-badge.json)](https://open-rpc.org)
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)

Contract-oriented JSON-RPC 2.0 services for Python, with typed pub/sub events.

## Features

- Synchronous WSGI and AnyIO-based ASGI HTTP dispatchers; WebSocket and broker RPC.
- Parameter/result contracts from Python annotations, encoded with mashumaro.
- Typed call contexts, authentication/permission decorators and call hooks.
- OpenRPC, OpenAPI and AsyncAPI schemas generated from registered contracts.
- Pub/sub events, competing-consumer task queues, AMQP and Redis adapters.
- JSON by default; optional `orjson`, `ujson` and `msgpack` wire backends.
- CORS and JWT middleware for WSGI and ASGI; synchronous Django integration.

## Installation and Dependencies

Requires **Python 3.12 or higher** (CI tests Python 3.12 and 3.13).
The base package depends on `mashumaro` and `anyio`; servers are installed separately.

```shell
pip install drakaina
```

Install only the extras you use (quote the argument in your shell):

```shell
pip install 'drakaina[jwt,django,amqp,redis,orjson,ujson,msgpack,docs]'
```

`jwt` provides PyJWT, `django` adds Django and PyJWT, `amqp` provides aio-pika,
`redis` provides the Redis client, and `docs` adds docstring parsing.
The base package imports without these extras. Pass a wire serializer such as
`ORJsonSerializer()` from `drakaina.serializers` to the protocol's `serializer=`
argument to change the backend; typed contracts are independent of that choice.

## Quick start: WSGI

Save this as `main.py`. The decorator uses the package-level `rpc_registry` by
default. For independent services, pass an explicit `RPCRegistry` to both the
`remote_procedure` decorator and the protocol's `registry=` argument.

```python
import json

from drakaina import remote_procedure
from drakaina.rpc_protocols import JsonRPCv2
from drakaina.wsgi import WSGIHandler


@remote_procedure("hello")
def hello(name: str) -> str:
    return f"Hello, {name}!"


protocol = JsonRPCv2()
request = json.loads(
    '{"jsonrpc": "2.0", "method": "hello", '
    '"params": ["🐍 Python"], "id": 1}'
)
assert protocol.handle(request) == {
    "jsonrpc": "2.0", "result": "Hello, 🐍 Python!", "id": 1,
}
app = WSGIHandler(
    route="/rpc",
    handler=protocol,
    openrpc_url="/openrpc.json",
    openapi_url="/openapi.json",
)
```

Run it with a WSGI server, for example Gunicorn:

```shell
pip install gunicorn
gunicorn main:app
```

Send JSON-RPC requests with `POST /rpc` and `Content-Type: application/json`.
A request with no `id` is a notification and produces no JSON-RPC response.
Batch requests are JSON arrays. Both HTTP handlers default to a 256 KiB body
limit (`max_content_size`). `GET /openrpc.json` and `GET /openapi.json` serve the
configured schemas; without configured schema URLs there is no schema GET route.

## ASGI and the async core

Alternatively, save this **complete replacement** as `main.py`:

```python
import anyio

from drakaina import remote_procedure
from drakaina.asgi import ASGIHandler
from drakaina.rpc_protocols import AsyncJsonRPCv2


@remote_procedure("hello")
async def hello(name: str) -> str:
    await anyio.sleep(0)
    return f"Hello, {name}!"


@remote_procedure("add")
def add(left: int, right: int) -> int:
    return left + right


protocol = AsyncJsonRPCv2(batch_concurrency=8)
app = ASGIHandler(route="/rpc", handler=protocol)


async def demo() -> None:
    responses = await protocol.handle([
        {"jsonrpc": "2.0", "method": "hello", "params": ["ASGI"], "id": 1},
        {"jsonrpc": "2.0", "method": "add", "params": [2, 3], "id": 2},
    ])
    assert responses == [
        {"jsonrpc": "2.0", "result": "Hello, ASGI!", "id": 1},
        {"jsonrpc": "2.0", "result": 5, "id": 2},
    ]


if __name__ == "__main__":
    anyio.run(demo)
```

```shell
pip install uvicorn
uvicorn main:app
```

`AsyncJsonRPCv2` awaits async procedures and **automatically offloads every sync
procedure** through `anyio.to_thread.run_sync`; no decorator marker is needed.
`JsonRPCv2` is synchronous: async procedures are rejected with `-32603 Internal
error`. A sync callable returning a coroutine is also rejected (and its coroutine
closed), not implicitly awaited, in either core.

Important async execution rules:

- Sync calls share AnyIO's default worker-thread limiter (**40 tokens by
  default**), independently of `batch_concurrency`. Saturated calls wait for a
  worker token. This is not a dedicated pool per procedure or batch.
- Cancellation does not interrupt sync code already running in a worker thread.
  With the default `run_sync` settings, cancellation is deferred until it finishes.
- Thread-local state belongs to the worker thread, not the request/event-loop
  thread. `contextvars` are copied into the worker; changes made there do not
  propagate back to the calling task.
- Django + the async core is not the Django view integration below. If using
  Django ORM inside offloaded procedures, manage connections in those worker
  threads explicitly: request-thread `close_old_connections` does **not** manage
  their connections. Do not assume thread affinity across calls.
- Async batches accept at most 100 items by default (`max_batch_size`); a larger
  batch is rejected as one JSON-RPC `-32600 Invalid Request` response with
  `id: null`, including notification-only batches, before any item runs. Set a
  different positive `max_batch_size` to customize this bound.
- A batch uses at most 16 worker tasks (`batch_concurrency`), not one task per
  item. Configure a positive value up to 16; passing `None` selects the safe
  default of 16 and no longer means unlimited. Responses and HTTP response
  effects retain request order,
  excluding notifications from the response array.
- An instance-wide, thread-safe execution limit allows at most 64 procedure
  executions at once across event loops/threads using that same
  `AsyncJsonRPCv2` instance. Batch items and standalone `handle()`/`execute()`
  calls share these slots; additional calls wait, and cancellation releases
  acquired slots. This is per instance, not a process-wide limit across distinct
  protocol instances. Batches create at most `min(batch_concurrency, item_count)`
  workers each; server-level limits are still needed to bound incoming request
  tasks and transport backlog.
- These batch bounds do not change AnyIO's default 40-token worker-thread
  limiter for synchronous procedures; saturated sync calls wait for a thread
  token. Cancellation does not interrupt sync code already running in a worker
  thread. With the default `run_sync` settings, cancellation is deferred until
  it finishes.

## Contracts and generated RPC schemas

Ordinary dataclasses need no serialization mixin. Registration builds mashumaro
codecs from parameter and return annotations. Named and positional parameters are
supported; `Any` and unannotated values retain the raw path. This is mashumaro
conversion, **not strict JSON Schema validation** (for example, numeric strings
may be converted to integers). Invalid typed input becomes `-32602 Invalid params`.

```python
from dataclasses import dataclass

from drakaina import RPCRegistry, remote_procedure
from drakaina.rpc_protocols import JsonRPCv2


@dataclass
class Item:
    name: str
    quantity: int = 1


procedures = RPCRegistry()


@remote_procedure("order", registry=procedures)
def order(item: Item) -> Item:
    return Item(item.name, item.quantity + 1)


protocol = JsonRPCv2(registry=procedures)
response = protocol.handle({
    "jsonrpc": "2.0", "method": "order",
    "params": {"item": {"name": "book", "quantity": 2}}, "id": 1,
})
assert response == {
    "jsonrpc": "2.0", "result": {"name": "book", "quantity": 3}, "id": 1,
}
```

OpenRPC/OpenAPI parameter and result schemas come from these same contracts.
Configure `openrpc_url`/`openapi_url` on either HTTP handler (as in the WSGI example).
Schema caches are invalidated when the registry version changes. A standalone
protocol generating OpenAPI needs `schema_url` for its RPC endpoint; a handler
with a string `route` supplies it automatically.

## Typed call context

Use `provide_request=True` to inject `request` (it is not a wire parameter).
Annotate it with `CallContext` for transport-neutral identity/application data,
or the specialization you require:

| Context | Transport-specific data |
| --- | --- |
| `HTTPContext` | WSGI environ / ASGI scope and `response_effects` |
| `MessageContext` | `message_id`, `event_id`, `correlation_id`, `reply_to`, immutable `headers`, `delivery_count` |
| `WSContext` | `connection_id` and the `connection` handle |

All inherit `CallContext`: `user`, `user_id`, `is_authenticated`, `auth_payload`,
normalized `auth_scopes` (a tuple), `auth_exception`, and `app`. Contexts also expose
mapping access for application-specific values. A specialized annotation requires
a compatible context; an HTTP-only procedure is not portable to broker RPC.

```python
from drakaina import HTTPContext, remote_procedure
from drakaina.rpc_protocols import JsonRPCv2
from drakaina.types import ResponseEffects


@remote_procedure("whoami", provide_request=True)
def whoami(request: HTTPContext) -> str | None:
    request.response_effects = ResponseEffects(
        headers=(*request.response_effects.headers, ("X-Service", "identity")),
    )
    return request.user_id


protocol = JsonRPCv2()
context = HTTPContext({}, app=protocol)
context.user_id = "42"
response = protocol.handle(
    {"jsonrpc": "2.0", "method": "whoami", "id": 1}, request=context,
)
assert response["result"] == "42"
assert context.response_effects.headers == (("X-Service", "identity"),)
```

`ResponseEffects` is immutable: assign a new value to add HTTP response headers.
Names must be unique ignoring case, and `Content-Type`/`Content-Length` are owned
by the transport and cannot be set through effects.

In **both cores**, every batch call starts with empty, isolated `response_effects`;
other context fields remain shared. After execution, effects merge in **batch
request order**, not completion order. Middleware effects written before the
batch are the merge baseline. A case-insensitive header-name conflict gives the
later call `-32603 Internal error` and discards **all** of that call's effects.
For a notification, conflicting effects are discarded without a response.
Effects from a procedure that raises an error are otherwise preserved if there is
no conflict. A single non-batch request keeps its normal, unisolated behavior.

## Middleware

The `middlewares` list accepts Drakaina middleware classes or configured
`functools.partial` objects. Entries are entered in list order (first = outermost),
then unwind in reverse order. They receive typed contexts, not raw environ/scope:
subclass `WSGIMiddleware` or `ASGIMiddleware` and call `self.app` to continue.
Raw third-party WSGI/ASGI middleware belongs **outside** the HTTP handler instead.

```python
from drakaina import CallContext, remote_procedure
from drakaina.asgi import ASGIHandler
from drakaina.middleware.base import ASGIMiddleware, WSGIMiddleware
from drakaina.wsgi import WSGIHandler


class TraceMiddleware(WSGIMiddleware):
    def __call__(self, context, start_response):
        context["trace_id"] = "readme-trace"
        return self.app(context, start_response)


class AsyncTraceMiddleware(ASGIMiddleware):
    async def __call__(self, context, receive, send):
        context["trace_id"] = "readme-trace"
        await self.app(context, receive, send)


@remote_procedure("trace", provide_request=True)
def trace(request: CallContext) -> str:
    return str(request["trace_id"])


wsgi_app = WSGIHandler(route="/rpc", middlewares=[TraceMiddleware])
app = ASGIHandler(route="/rpc", middlewares=[AsyncTraceMiddleware])
```

Handlers automatically install an outer `ExceptionMiddleware` (WSGI) or
`ASGIExceptionMiddleware` (ASGI) to convert unhandled HTTP middleware errors into
RPC errors. ASGI errors after response start are re-raised: an already-started
response cannot be replaced. Pass `logger=` to the handler for error logging.
Use `response_effects` (above) for procedure-owned headers rather than mutating
transport internals.

### CORS

```python
from functools import partial

from drakaina.asgi import ASGIHandler
from drakaina.middleware.cors import ASGICORSMiddleware, CORSMiddleware
from drakaina.wsgi import WSGIHandler


policy = {
    "allow_origin": ["https://client.example"],
    "allow_methods": ["POST", "OPTIONS"],
    "allow_headers": ["Content-Type", "Authorization"],
    "allow_credentials": True,
    "expose_headers": ["X-Service"],
    "max_age": 600,
}
wsgi_app = WSGIHandler(
    route="/rpc", middlewares=[partial(CORSMiddleware, **policy)],
)
app = ASGIHandler(
    route="/rpc", middlewares=[partial(ASGICORSMiddleware, **policy)],
)
```

CORS middleware handles `OPTIONS` requests carrying `Origin` before RPC dispatch,
including browser preflights with `Access-Control-Request-Method`. Put CORS before
JWT/auth middleware so preflights do not require credentials. Responses retain/merge
`Vary: Origin` when origin-dependent. Credentials are enabled by the policy,
**not** by whether the request happens to contain a cookie. With
`allow_origin="*"` and credentials enabled, the request origin is reflected rather
than sending the invalid wildcard-plus-credentials combination. Prefer an explicit
origin allowlist. CORS is a browser policy, not authentication.

### JWT

Install the `jwt` extra and provide a signing/verification key through your runtime
(e.g. the `DRAKAINA_JWT_SECRET_KEY` environment variable). No key is embedded here.
This example accepts `Authorization: Bearer <token>`, verifies HS256 signatures,
and reads `user_id` and the application-defined `scp` scopes from the payload:

```python
import os
from functools import partial

from drakaina import (
    CallContext, check_permissions, login_required, match_any, remote_procedure,
)
from drakaina.asgi import ASGIHandler
from drakaina.contrib.jwt.middleware import (
    ASGIJWTAuthenticationMiddleware, JWTAuthenticationMiddleware,
)
from drakaina.wsgi import WSGIHandler


@login_required
@remote_procedure("profile", provide_request=True)
def profile(request: CallContext) -> str | None:
    return request.user_id


@check_permissions(["user:read", "user:admin"], match_any)
@remote_procedure("users", provide_request=True)
def users(request: CallContext) -> list[str]:
    return ["visible to authorized users"]


def get_scopes(request: CallContext, payload: dict) -> str | list[str] | None:
    return payload.get("scp")


options = {
    "secret_key": os.environ["DRAKAINA_JWT_SECRET_KEY"],
    "algorithms": ["HS256"],
    "credentials_required": True,
    "prefix": "Bearer",
    "scopes_getter": get_scopes,
}
wsgi_app = WSGIHandler(
    route="/rpc",
    middlewares=[partial(JWTAuthenticationMiddleware, **options)],
)
app = ASGIHandler(
    route="/rpc",
    middlewares=[partial(ASGIJWTAuthenticationMiddleware, **options)],
)
```

`login_required` checks authenticated identity; `check_permissions` additionally
checks normalized scopes (`match_any` or `match_all`). Keep `remote_procedure`
innermost as shown, and enable request injection for guarded procedures.
Optional `user_getter`, `token_getter` and `revoke_checker` callbacks customize
identity lookup, token extraction and revocation. ASGI user/scope/revocation
getters may be sync or async; WSGI callbacks and token getters must be sync.
Signature verification cannot be disabled with `decode_options`.

## Events and lifecycle

Events are **pub/sub**, not task queues. Each event name has one dataclass payload
contract in its `EventRegistry`, independent of `RPCRegistry`; several handlers
may share that contract. Evolve payloads additively with defaults for new fields;
breaking changes require a new event name. `EventPublisher` publishes dataclass
instances; it does not own the transport lifecycle.

This self-contained in-memory example runs without an external broker:

```python
from contextlib import asynccontextmanager
from dataclasses import dataclass

import anyio

from drakaina import EventPublisher, EventRegistry, MessageContext, event_handler
from drakaina.events.lifespan import Lifespan
from drakaina.events.memory import MemoryTransport


@dataclass
class UserCreated:
    user_id: str


events = EventRegistry()
seen = []


@event_handler("users.created", registry=events, provide_request=True)
async def on_user_created(event: UserCreated, *, request: MessageContext) -> None:
    seen.append(event.user_id)
    assert request.event_id is not None


transport = MemoryTransport()
lifespan = Lifespan()


@asynccontextmanager
async def event_resources(task_group):
    await transport.open(task_group=task_group)
    try:
        async with events.subscribe(
            transport, namespace="demo", task_group=task_group,
        ):
            yield transport
    finally:
        await transport.close()


lifespan.add(event_resources)


async def demo() -> None:
    async with lifespan.run():
        publisher = EventPublisher(transport, namespace="demo")
        await publisher.publish("users.created", UserCreated("42"))
        assert seen == ["42"]


if __name__ == "__main__":
    anyio.run(demo)
```

`Lifespan` owns a supervised AnyIO task group and resource factories: startup in
registration order, shutdown in reverse order. Pass it as `ASGIHandler(lifespan=...)`
to bind resources to ASGI startup/shutdown, or use `lifespan.run()` in standalone
workers. Register consumers/subscriptions in resource factories, not per request.
`MemoryTransport` is process-local and non-persistent; it is for tests/local use.

For production transports, see `AMQPTransport` (`amqp` extra, asyncio-only via
aio-pika) and `RedisTransport` (`redis` extra). Pub/sub delivery is best-effort;
competing-consumer queues are a separate API with acknowledgement/redelivery.
Use broker JSON-RPC `BrokerRPCConsumer`/`BrokerRPCClient` for task queues, not the
event registry. See [broker RPC](docs/references/broker-rpc.md) and
[delivery semantics](docs/design-docs/e5-semantika-dostavki.md).

## AsyncAPI

`build_asyncapi_schema` builds **AsyncAPI 3.1.0** from event payload contracts,
including AMQP and WebSocket descriptions. It requires an explicit registry:
it does not inspect the global RPC registry, open a broker, or enable WebSocket
routing. The following example can also be saved as `main.py`:

```python
from dataclasses import dataclass

from drakaina import EventRegistry, build_asyncapi_schema, event_handler
from drakaina.asgi import ASGIHandler
from drakaina.wsgi import WSGIHandler


@dataclass
class UserCreated:
    user_id: str


events = EventRegistry()


@event_handler("users.created", registry=events)
def on_user_created(event: UserCreated) -> None:
    pass


document = build_asyncapi_schema(events, title="User events", version="1.0.0")
assert document["asyncapi"] == "3.1.0"
app = ASGIHandler(
    route="/rpc", asyncapi_url="/asyncapi.json", event_registry=events,
)
wsgi_app = WSGIHandler(
    route="/rpc", asyncapi_url="/asyncapi.json", event_registry=events,
)
```

Both handlers serve `GET /asyncapi.json`. Configuring `asyncapi_url` without
`event_registry` raises `ValueError`. Payload schemas with custom `$id` values
may keep absolute references and are not necessarily self-contained for offline
validation. WebSocket serving is configured separately with `WebSocketGateway`
and a `Lifespan`; see the [WebSocket guide](docs/references/websocket.md).
For synchronous publishers/broker RPC callers, see `SyncClient` in the
[broker guide](docs/references/broker-rpc.md).

## Django

Install the `django` extra. The integration uses the **sync** `JsonRPCv2` core.
In an installed Django application's `rpc_views.py`:

```python
# rpc_views.py
from drakaina import remote_procedure


@remote_procedure("hello_django")
def hello_django() -> str:
    return "Hello, Django!"
```

In your project's `urls.py`, autodiscover that module in installed apps:

```python
# urls.py
from django.urls import path

from drakaina.contrib.django import RPCView


urlpatterns = [
    path("api/", RPCView.as_view(autodiscover="rpc_views")),
]
```

For JWT, configure `DRAKAINA_JWT_SECRET_KEY` in `settings.py` from runtime secrets
and restrict accepted algorithms to those issued by your identity provider:

```python
# settings.py
import os


DRAKAINA_JWT_SECRET_KEY = os.environ["DRAKAINA_JWT_SECRET_KEY"]
DRAKAINA_JWT_ALGORITHMS = ["HS256"]
```

Then use this alternative `urls.py` to wrap the view:

```python
# urls.py
from django.urls import path

from drakaina.contrib.django import JWTAuthenticationMiddleware, RPCView


urlpatterns = [
    path("api/", JWTAuthenticationMiddleware(
        RPCView.as_view(autodiscover="rpc_views"),
    )),
]
```

Django middleware callbacks receive Django's `HttpRequest`; RPC procedures receive
the typed `HTTPContext`. Unknown or invalid `DRAKAINA_*` settings fail validation;
in production (`DEBUG=False`) a JWT secret key is required.

## Further reading

- [Migration guide 0.7 → 1.0](MIGRATION.md)
- [RPC hooks](docs/references/rpc-hooks.md)
- [Task status events](docs/references/task-statuses.md)
- [Architecture](ARCHITECTURE.md)

## License

Apache License 2.0

## Artwork

"[drakaina.png](content/drakaina.png)" by Korolko Anastasia is licensed under
<a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/"><img alt="License Creative Commons" style="border-width:0" src="https://i.creativecommons.org/l/by-sa/4.0/80x15.png" /></a> ([CC BY-SA 4.0](http://creativecommons.org/licenses/by-sa/4.0/)).
