Skip to content

django-neolith

Deploy Django apps, not Django projects.

CI PyPI version Python versions Django versions License: BSD-3-Clause Code style: Ruff Checked with mypy

Status: alpha (0.1.0a4). The API may change before 0.1.

pip install --pre django-neolith

What it is

Neolith makes the Django app, not the Django project, the unit of deployment. An app can run inside a shared process or on its own as a service, with its models, migrations, admin and tests intact, and without changing its code. Apps talk to each other only through typed contracts, so the same code and the same tests hold in both arrangements. Neolith is defined by a specification that is independent of Django and of Python, and django-neolith is its reference implementation.

Features

What this version does. The changelog has the details.

  • Typed contracts. A contract is a Protocol class with @contract and @action, and an implementation is marked with @implements. Request and reply types are Pydantic models in a portable type system, and every check runs when the module is imported.
  • Typed errors. ContractError carries a kind, a message and a detail. An action can declare its own error kinds with their detail records.
  • Calls cross as JSON, in-process too. Every request, reply and error detail is written and read through its declared type, so an in-process call carries exactly what a remote one will.
  • App declaration. An app declares what it provides, requires and owns on its NeolithAppConfig, and the declaration is checked when the class is defined.
  • Checks before serving. At start-up the host resolves every required contract to a provider and validates each implementation, listing every refusal in one error; once those pass, it runs its system checks on the settings and reports all their errors together.
  • One database per app. neolith.routers.AppRouter keeps each app's data on a database alias of its own.
  • Call context. A principal, a trace, a deadline and the calling app travel with each call. A root is opened for each request by RootMiddleware, and for a command or background work by command_scope.
  • Request principal. NEOLITH["PRINCIPAL_BACKENDS"] lists ordered principal backends, such as neolith.principals.DjangoUserBackend for the logged-in Django user. They name who a request is for, and PrincipalMiddleware fixes that principal for the request's calls.
  • HTTP transport. NEOLITH["REMOTE_PROVIDERS"] names a provider that another host serves, and a connector then sends that contract's calls over HTTP with a token signed by the calling app's key in NEOLITH["SIGNING_SECRETS"]. The host serves its own contract endpoints, names the app that calls them through NEOLITH["CALLER_BACKENDS"], and serves an OpenAPI 3.1.2 document at /.well-known/neolith/openapi.json; the client uses only the standard library.
  • local-first routing. NEOLITH["ROUTING_POLICIES"] can name local-first for a contract version with two or more providers, tried in order; an idempotent call moves to the next on unavailable, within its one deadline.
  • Conformance suite. Spec 06's suite runs each contract case over the in-process and the HTTP transports and checks that they give one outcome.
  • One app alone. neolith run <app> boots apps from their declarations and serves them, and neolith migrate <app> applies each app's migrations to its own database.
  • Boundary check. neolith check <app> [<app> ...] --settings <module>, or manage.py checkapps in a host built by a settings module, reports before deployment what the hosted apps do across an app boundary, such as a relation to another app's model; it opens no database connection itself and refuses any while it runs (under manage.py checkapps, only once Django has loaded the apps). An app listed in [tool.neolith] boundary-report-only in pyproject.toml is reported without failing the check.

Not yet in this version: events. See the roadmap below.

A short example

A contract, in a contract package other apps may import:

# inventory/contracts.py
from typing import Protocol

from pydantic import BaseModel

from neolith import action, contract


class ReserveRequest(BaseModel):
    sku: str
    qty: int


class ReserveReply(BaseModel):
    reserved: int


@contract("inventory.v1")
class Inventory(Protocol):
    @action(idempotent=True)
    def reserve(self, request: ReserveRequest) -> ReserveReply: ...

Its implementation, private to the app that provides it:

# inventory/services.py
from neolith import CallContext, implements

from inventory.contracts import Inventory, ReserveReply, ReserveRequest


@implements(Inventory)
class InventoryService:
    def reserve(self, request: ReserveRequest, ctx: CallContext) -> ReserveReply:
        return ReserveReply(reserved=request.qty)

The two apps' declarations:

# inventory/apps.py
from neolith import NeolithAppConfig, Provided

from inventory.contracts import Inventory


class InventoryConfig(NeolithAppConfig):
    name = "inventory"
    label = "inventory"
    provides = (
        Provided(
            Inventory,
            implementation="inventory.services.InventoryService",
            principal_from=("shop",),  # apps that may pass a principal on their calls
        ),
    )


# shop/apps.py
from neolith import NeolithAppConfig

from inventory.contracts import Inventory


class ShopConfig(NeolithAppConfig):
    name = "shop"
    label = "shop"
    requires = (Inventory,)

And a call from the shop app, which knows the contract and nothing else of inventory:

# shop/orders.py
from neolith import ContractError, connect

from inventory.contracts import ReserveRequest

inventory = connect("inventory.v1")


def place_order(sku: str, qty: int) -> int:
    try:
        reply = inventory.reserve(ReserveRequest(sku=sku, qty=qty))
    except ContractError as error:
        print(error.kind)  # "unavailable", "conflict", ...
        raise
    return reply.reserved

The settings, beside the project's usual ones such as SECRET_KEY. They end with the host's builder, which builds INSTALLED_APPS, DATABASES and DATABASE_ROUTERS from the apps' declarations and NEOLITH, and checks the rest before the host serves:

# settings.py
from neolith.host import build_settings

MIDDLEWARE = [
    "neolith.middleware.RootMiddleware",  # first, and listed once
    "neolith.middleware.PrincipalMiddleware",  # listed once
]
NEOLITH = {}

globals().update(build_settings(["inventory", "shop"], globals()))

With these, a view in the shop app can call place_order directly; a command opens its root first, with neolith.command_scope("shop"). A test runs every Python block on this page under these settings.

To run apps without a project, put the deployer's names (SECRET_KEY, MIDDLEWARE, ROOT_URLCONF, NEOLITH and the rest) in a module that does not call the builder, then apply the migrations and serve:

$ neolith migrate inventory shop --settings deploy
$ neolith run inventory shop --settings deploy --bind 127.0.0.1:8000

neolith run uses Django's development server, which is not for production; in production, serve a settings module like the one above with any WSGI or ASGI server. On SIGINT or SIGTERM it stops taking requests and gives each request in flight until NEOLITH["REQUEST_DEADLINE"], or 30 seconds when that is None. Under another server, give its graceful shutdown a timeout no shorter than the request deadline. In a host built by a settings module, manage.py migrateapps is the migrate step, and manage.py migrateapps --check reports what the host would refuse at start-up.

Roadmap

The steps to 0.1 are in the roadmap.

Links

Licensed under the BSD 3-Clause License.

Releases

Packages

Used by

Contributors

Languages