Skip to main content

Async RabbitMQ worker utilities

Project description

WorkerLib - асинхронная работа с RabbitMQ

Быстрый старт

import asyncio
from workerlib import WorkerPool

async def task_handler(data: dict) -> bool:
    print(f"Обработка: {data}")
    return True

async def main():
    async with WorkerPool() as pool:
        pool.add_worker("tasks", task_handler)
        await pool.send("tasks", {"id": 1, "cmd": "start"})
        await asyncio.sleep(2)

asyncio.run(main())

Формат сообщений

JSON сообщение Библиотека автоматически сериализует dict в JSON при отправке:

# Отправка простого сообщения
await pool.send("queue", {
    "event": "user_created",
    "user_id": 123,
    "email": "user@example.com",
    "timestamp": "2024-01-15T10:30:00Z"
})

# Отправка вложенных структур
await pool.send("queue", {
    "type": "order",
    "data": {
        "order_id": "ORD-12345",
        "items": [
            {"id": 1, "quantity": 2},
            {"id": 2, "quantity": 1}
        ],
        "total": 299.99
    },
    "metadata": {
        "source": "api",
        "version": "1.0"
    }
})

Основные примеры

  1. Пул с несколькими воркерами
from workerlib import WorkerPool, ErrorHandlingStrategy

async def main():
    async with WorkerPool() as pool:
        # Email воркер с DLQ
        pool.add_worker(
            "emails",
            email_handler,
            error_strategy=ErrorHandlingStrategy.DLQ,
            prefetch_count=5
        )
        
        # Обработчик платежей
        pool.add_worker(
            "payments",
            payment_handler,
            error_strategy=ErrorHandlingStrategy.REQUEUE_END
        )
        
        # Отправка задач
        await pool.send("emails", {"to": "user@test.com"})
        await pool.send("payments", {"amount": 100})
  1. Кастомное подключение и retry
from workerlib import ConnectionParams, RetryConfig

params = ConnectionParams(
    host="rabbit.local",
    username="admin",
    password="secret"
)

retry_config = RetryConfig(
    max_attempts=3,
    initial_delay=1.0,
    backoff_factor=2.0
)

async with WorkerPool(connection_params=params) as pool:
    pool.add_worker(
        "critical",
        critical_handler,
        retry_config=retry_config
    )
  1. Обработка ошибок
from workerlib import ErrorHandlingStrategy

# Варианты:
# IGNORE - проигнорировать ошибку
# REQUEUE_END - в конец очереди с задержкой
# REQUEUE_FRONT - в начало очереди
# DLQ - в Dead Letter Queue

pool.add_worker(
    "tasks",
    my_handler,
    error_strategy=ErrorHandlingStrategy.DLQ,
    dlq_enabled=True,
    requeue_delay=5.0  # задержка повторной обработки
)
  1. Метрики
async with WorkerPool() as pool:
    pool.add_worker("monitored", handler)
    
    # Отправляем задачи
    for i in range(10):
        await pool.send("monitored", {"task": i})
    
    # Получаем метрики
    metrics = pool.get_metrics("monitored")
    print(f"Обработано: {metrics['consumer']['processed']}")
    print(f"Ошибок: {metrics['consumer']['failed']}")
  1. FastAPI интеграция
from fastapi import FastAPI
from workerlib import WorkerPool

app = FastAPI()
worker_pool = WorkerPool(auto_start=False)

@app.on_event("startup")
async def startup():
    await worker_pool.start()
    worker_pool.add_worker("api_tasks", task_handler)

@app.on_event("shutdown")
async def shutdown():
    await worker_pool.stop()

@app.post("/task")
async def create_task(data: dict):
    await worker_pool.send("api_tasks", data)
    return {"status": "queued"}

Конфигурация

ConnectionParams

ConnectionParams(
    host="127.0.0.1",
    port=5672,
    username="guest",
    password="guest",
    heartbeat=60,
    timeout=10
)

QueueConfig

QueueConfig(
    name="queue_name",
    durable=True,
    prefetch_count=1
)

RetryConfig

RetryConfig(
    max_attempts=3,
    initial_delay=1.0,
    backoff_factor=2.0,
    max_delay=60.0
)

Установка

pip install workerlib

Требования: Python 3.10+, aio_pika

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

workerlib-0.4.5.tar.gz (15.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

workerlib-0.4.5-py3-none-any.whl (11.7 kB view details)

Uploaded Python 3

File details

Details for the file workerlib-0.4.5.tar.gz.

File metadata

  • Download URL: workerlib-0.4.5.tar.gz
  • Upload date:
  • Size: 15.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for workerlib-0.4.5.tar.gz
Algorithm Hash digest
SHA256 a874460f17ad43bd539d73b8db0ea1bf769fe0bfcd4bcc6b429fd26188126d20
MD5 29c9996fc26fdf0b8d05f575fba9d595
BLAKE2b-256 4526f97c3432c06f5f6597d21a57b1d67c521660455910bddad959e904fb8c8a

See more details on using hashes here.

Provenance

The following attestation bundles were made for workerlib-0.4.5.tar.gz:

Publisher: publish.yml on ametist-dev/workerlib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file workerlib-0.4.5-py3-none-any.whl.

File metadata

  • Download URL: workerlib-0.4.5-py3-none-any.whl
  • Upload date:
  • Size: 11.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for workerlib-0.4.5-py3-none-any.whl
Algorithm Hash digest
SHA256 9bbe180e32a2dcce53b0ac0afc37a06c7e4c80254efa67b7189c18659c21f652
MD5 06a00adef940ff4213006af8ecc175d7
BLAKE2b-256 34ddef147fdabfef3942a3bba26b23faca1716eaed4bc97b5cc5914e935650e6

See more details on using hashes here.

Provenance

The following attestation bundles were made for workerlib-0.4.5-py3-none-any.whl:

Publisher: publish.yml on ametist-dev/workerlib

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page