Skip to main content

Skoll

A small Python toolkit for building domain-driven, message-based backends. It provides a Result type, validated value objects, a repository/ports-and-adapters layer (PostgreSQL via asyncpg), a NATS-based mediator with a JetStream KV store, and a lightweight async dependency-injection resolver.

Installation

pip install skoll

Usage

Skoll has three parts: skoll.core (validated objects, Result, errors), skoll.messaging (services on NATS) and skoll.storage (PostgreSQL repositories and the NATS KV store).

Objects and results

from skoll import AggregateRoot, Object, InvalidValue, ok, fail, is_ok


class Email(Object):  # a value object: a single `value` field
    value: str

    @classmethod
    def prepare(cls, raw):
        value = str(raw).strip().lower()
        return ok(value) if "@" in value else fail(InvalidValue(field="email", detail="Not an email."))


class UserId(Object):
    value: str


class User(AggregateRoot[UserId]):  # `id`, `version`, optimistic concurrency
    email: Email
    name: str


res = User.create({"id": "01j...", "email": "A@B.CO", "name": "Awa"})
if is_ok(res):
    changed = res.value.update(name="Awa D.")  # validated copy (a Result), version + 1
    # `evolve(...)` does the same without validation, for values your code already trusts

Services

A callback's first parameter is its input: an Input subclass mapped to a subject. A service dispatches on that type, so registering the callback is all the routing there is. The input builds itself from the message with from_message: the payload by default, plus whatever it takes from the message context. The other parameters are dependencies.

from typing import Annotated, AsyncGenerator, ClassVar, Self
from skoll import Depends, Input, Message, Object, NotFound, NatsBroker, PostgresDB, PostgresRepo, Result, Service, fail


class Actor(Object):
    user_id: str


class ActorInput(Input):  # shared base: the caller always comes from the context, never from the payload
    actor: Actor

    @classmethod
    def from_message(cls, msg: Message) -> Result[Self]:
        return cls.create({**msg.payload, "actor": msg.cxt.get("actor")})


class GetUser(ActorInput):
    __subject__: ClassVar[str] = "qry.users.get"
    id: str


class OrderCreated(Input):
    __subject__: ClassVar[str] = "evt.orders.created"
    order_id: str


class UserRepo(PostgresRepo[User]):
    table = "users"
    model = User


async def users(db: PostgresDB) -> AsyncGenerator[UserRepo]:
    async with db.transaction() as conn:  # committed after the callback, rolled back on failure
        yield UserRepo(conn)


service = Service("users", context={"db": PostgresDB()})


@service.reply
async def get_user(qry: GetUser, repo: Annotated[UserRepo, Depends(users)]):
    user = await repo.get(UserId(value=qry.id))
    return user if user is not None else fail(NotFound())


@service.on(stream="ORDERS", max_deliver=10, concurrency=4)
async def on_order(evt: OrderCreated, repo: Annotated[UserRepo, Depends(users)]) -> None: ...


async def main():
    async with service.context["db"], NatsBroker(servers=["nats://localhost:4222"]) as broker:
        await broker.serve(service)
        res = await broker.request(Message(subject="qry.users.get", payload={"id": "01j..."}, cxt={"actor": ...}))
        await broker.publish(OrderCreated(order_id="01j..."))
        cache = await broker.kv("sessions", ttl=3600)

await service.call(GetUser(id="...", actor=...)) hands a ready-made input to the callback, without NATS, for tests.

Querying

Every repository query takes the same where: a column mapping, with operators where needed, or a reusable Criteria that renders its own SQL.

from skoll import Gte, ILike, Not

page = await repo.find({"org_id": org, "age": Gte(18), "name": ILike("aw%"), "deleted_at": None}, limit=50)
more = await repo.find(same_filter, after=page.next_cursor)
total = await repo.count(ActiveInOrg(org_id=org))  # class with `to_sql(self, start) -> (sql, params)`

Stream listeners retry errors flagged RETRYABLE with a doubling delay, up to max_deliver deliveries (5 by default), and drop the others. concurrency lets one instance handle several messages at once.

Development

uv run pytest                       # unit tests
docker compose up -d                # NATS (JetStream) and PostgreSQL for the integration tests
SKOLL_NATS_URL=nats://127.0.0.1:4222 SKOLL_PG_DSN=postgresql://skoll:skoll@127.0.0.1:5432/skoll uv run pytest

License

This project is licensed under the MIT License - see the LICENSE file for details.

Metadata

Release files for skoll 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for skoll 1.0.0
File Size Uploaded Provenance Actions
skoll-1.0.0.tar.gz 46.2 kB Without provenance Details for skoll-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for skoll 1.0.0
File Interpreter ABI Platform Actions
skoll-1.0.0-py3-none-any.whl Python 3 none any Details for skoll-1.0.0-py3-none-any.whl

Total release size: 82.8 kB

Release files / skoll-1.0.0.tar.gz

Download URL skoll-1.0.0.tar.gz
Size 46.2 kB
Tags Source
SHA-256 checksum
How to use checksums
e8bfb3508d8517077bbce7ad499592fd4088873f1b75cbebad7f0705aa6849a8
BLAKE2b-256 checksum
How to use checksums
4d7053b3cc241cec344be7450433a761cd400e495be49a6ccfaf431712d49143
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / skoll-1.0.0-py3-none-any.whl

Download URL skoll-1.0.0-py3-none-any.whl
Size 36.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1bf6a0f3bd0e62bf9732eb8888dab05d0ecaa10694da4b38481b41e4789952fb
BLAKE2b-256 checksum
How to use checksums
12122194fdf89cdfbddb53821372795760d9cbcd6c4df8627524eb8ab07ac0fd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for skoll 1.0.0

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.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page