This release is a pre-release and may not be stable for production use.
drakaina
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,ujsonandmsgpackwire 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.
pip install drakaina
Install only the extras you use (quote the argument in your 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.
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:
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:
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)
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_syncsettings, cancellation is deferred until it finishes. - Thread-local state belongs to the worker thread, not the request/event-loop
thread.
contextvarsare 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_connectionsdoes 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 Requestresponse withid: null, including notification-only batches, before any item runs. Set a different positivemax_batch_sizeto 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; passingNoneselects 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
AsyncJsonRPCv2instance. Batch items and standalonehandle()/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 mostmin(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_syncsettings, 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.
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.
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.
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
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:
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:
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 and
delivery semantics.
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:
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.
For synchronous publishers/broker RPC callers, see SyncClient in the
broker guide.
Django
Install the django extra. The integration uses the sync JsonRPCv2 core.
In an installed Django application's rpc_views.py:
# 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:
# 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:
# 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:
# 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
License
Apache License 2.0
Artwork
"drakaina.png" by Korolko Anastasia is licensed under
(CC BY-SA 4.0).
Metadata
Release files for drakaina 1.0.0rc2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| drakaina-1.0.0rc2.tar.gz | 718.5 kB | Without provenance | Details for drakaina-1.0.0rc2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| drakaina-1.0.0rc2-py3-none-any.whl | Python 3 | none | any | Details for drakaina-1.0.0rc2-py3-none-any.whl |
Total release size: 894.2 kB
Release files / drakaina-1.0.0rc2.tar.gz
| Download URL | drakaina-1.0.0rc2.tar.gz |
|---|---|
| Size | 718.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
05172fd444ad7e13c0e137d489794d65f049b2af14d695a54b32a5f8f3a94258
|
|
BLAKE2b-256 checksum How to use checksums |
cab43a3a355b21a84bcedfe22124eb0341f660f73a9145c22671e4879ce7fa3b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / drakaina-1.0.0rc2-py3-none-any.whl
| Download URL | drakaina-1.0.0rc2-py3-none-any.whl |
|---|---|
| Size | 175.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
e9d619e5aae5c1e4a1ccbb71012b7ce82110af085de08229c55ac81bc1d5888b
|
|
BLAKE2b-256 checksum How to use checksums |
00bcff0b0d874547de32da4ab30e2732f8885bbcc70c4f872fad51cba46ed10f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.10.4 {"installer":{"name":"uv","version":"0.10.4","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for drakaina 1.0.0rc2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.