Metadata-Version: 2.4
Name: taba-client
Version: 0.3.19rc1
Summary: Taba messaging system client: the nine operations, subscribe, call retries. No dependencies.
License: Apache-2.0
Project-URL: Repository, https://github.com/rafaelpontani/taba
Keywords: taba,queue,messaging,client
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# taba-client (Python)

The Python client of [Taba](https://github.com/rafaelpontani/taba): the nine operations of the client API, `subscribe`, consuming with a handler (with automatic renewal of the invisibility) and the call retries of the common contract. **No dependencies** (only the standard library); typed.

> Other languages: [Português (Brasil)](https://github.com/rafaelpontani/taba/blob/main/doc/pt-BR/21-conectores.md) · [all languages](https://github.com/rafaelpontani/taba/blob/main/doc/README.md)

- **Python 3.9 or later.**
- `taba.Client` is synchronous and safe for concurrent use (each thread has its own connection); `taba.aio.AsyncClient` is the `asyncio` one.

```python
from taba import Client, TopicRequest

with Client("http://localhost:8080", token="...") as client:
    client.create_topic(TopicRequest("orders", "queue"))
    client.publish_json("orders", {"order": 9001})

    # Consume with a handler: the message is deleted if the handler does not raise.
    def handle(context):
        print(context.message.body_text)

    client.consume_with("orders", handle, wait_time=20)

    # Or the whole loop, until the token is cancelled.
    # client.subscribe("orders", lambda message: print(message.json()), cancel=token)
```

```python
import asyncio
from taba.aio import AsyncClient

async def main():
    async with AsyncClient("http://localhost:8080") as client:
        for message in await client.consume("orders", wait_time=20):
            await client.ack("orders", message)

asyncio.run(main())
```

## Installing

```
pip install taba-client
```

The package has the version of the Taba release it came with and is published from the release workflow of this repository with PyPI Trusted Publishing. A release candidate is published in the PEP 440 form (`0.3.19rc1`), which `pip` only installs when asked (`pip install --pre taba-client`). Each [Release](https://github.com/rafaelpontani/taba/releases) also has the same wheel, `taba_client-<release>-py3-none-any.whl`, with its checksum in `SHA256SUMS` and its provenance (`gh attestation verify <file> -R rafaelpontani/taba`).

Straight from the source, with no Release (a branch, a tag or a commit after the `@`):

```
pip install "git+https://github.com/rafaelpontani/taba.git@release#subdirectory=connectors/python"
```

## Declaring a topic

`create_or_update_topic(request, recreate=None)` (`PUT /topics/{topic}`, also on `AsyncClient`) creates the topic or brings it to the declared state, and returns a `TopicPut` with the `topic` and the `outcome` (`created`, `updated` or `recreated`). What is left out goes back to the server default (a full replacement, unlike the update); another type, `fifo` or `volatile` is the error `409 topic.immutable-mismatch` unless `recreate` is `if-empty` (only when the queue and its dead-letter are empty, `409 topic.not-empty` otherwise) or `always` (drops the messages; new `id`). After a `503` the call is repeated like the others. `delete_topic(name, if_empty=True)` only removes a queue with no message. `create_topic` does not change (`409` when it exists). Details: [Create or update a topic](https://github.com/rafaelpontani/taba/blob/main/doc/en-US/16-client-api.md#create-or-update-a-topic-put-topicstopic).

## Batches

Many messages in one request, next to the single calls (optional): `publish_batch(topic, [BatchMessage(body, content_type=...)])`, `ack_batch(topic, messages)` and `change_visibility_batch(topic, messages, seconds)` (also on `AsyncClient`) return one `BatchResult` per item (`ok`, `status`, `id`, `error_code`). Each item is answered as its single call, in order, and an item that failed comes back with its `status` and error code instead of throwing. The bodies go in base64, so any type fits. Details: [Messages in batch](https://github.com/rafaelpontani/taba/blob/main/doc/en-US/16-client-api.md#messages-in-batch-post-messagesbatch-ack-and-visibility).

## Configuration

`Client(Config(...))`, or `Client(base_url, **options)` with the same fields. The client does not read environment variables: `TABA_*` belongs to the server.

| Field | Default | |
|---|---|---|
| `base_url` | required | `http://host:port` or `https://...` |
| `token` | none | `Authorization: Bearer` |
| `connect_timeout` | `5.0` | seconds |
| `request_timeout` | `30.0` | seconds; `consume` uses `wait_time + 10` |
| `max_attempts` | `3` | counting the first |
| `user_agent` | `taba-python/<version>` | |
| `serializer` | `json` | an object with `dumps` and `loads`, for `publish_json` and `consume_json` |
| `ssl_context` | system's, TLS 1.2+ | an own `ssl.SSLContext` (a private CA, for example) |

## What differs from the other connectors

- Names are `snake_case`; options are keyword arguments (`client.consume("q", max_messages=5, wait_time=20)`), and `ack`/`change_visibility` take the `Message` you received or its id plus `receipt_token`.
- A `TopicUpdate` field left at its default is not sent; `None` sends `null` (back to the server default) for `max_message_bytes`, `ttl` and `max_deliveries`.
- Cancelling: the synchronous client takes a `CancelToken` (`cancel=token`; it closes the connection in flight, so a long polling does not wait for its timeout) and raises `taba.Cancelled`; `subscribe` returns without an exception. The `asyncio` client is cancelled the `asyncio` way (`task.cancel()`), which raises `asyncio.CancelledError`.
- `iter_topics()` is a generator over all the pages; `list_all_topics()` returns the list.
- Errors are always a `TabaError` with `status`, `code`, `message`, `request_id`, `retry_after`, `details`. Test the `code`, never the `message`.
- The standard library has no asynchronous HTTP client, so the `asyncio` client runs the synchronous transport in worker threads (`asyncio.to_thread`).
- TLS is Python's own, with TLS 1.2 as the minimum; the certificate is always verified.

## Tests

```
cd connectors/python
python -m unittest discover -s tests -t .
```

The tests start a local HTTP server that records every request and answers from a script (the equivalent of the C# `ScriptedHandler`). The **contract tests** run the same scenario against a real Taba (one node in Docker), on the oldest supported version: `contract/run.sh` (`../contract/run.sh` for all the connectors; [how it works](https://github.com/rafaelpontani/taba/blob/main/connectors/contract/README.md)).
