Metadata-Version: 2.5
Name: skoll
Version: 1.0.0
Summary: A small Python toolkit for domain-driven, message-based backends: validated objects, Result type, NATS services, asyncpg repositories, JetStream KV and async DI
Author-email: Monzon Diarra <diarramonzon4@gmail.com>
License-Expression: MIT
License-File: LICENSE
Keywords: asyncpg,ddd,jetstream,nats,postgresql,result,value-objects
Classifier: Framework :: AsyncIO
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.14
Requires-Dist: asyncpg>=0.31.0
Requires-Dist: attrs>=25.4.0
Requires-Dist: nats-py[nkeys]>=2.13.1
Requires-Dist: ulid>=1.1
Description-Content-Type: text/markdown

# 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

```bash
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

```python
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.

```python
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.

```python
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

```bash
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](LICENSE) file for details.
