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.4.tar.gz (15.4 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.4-py3-none-any.whl (11.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: workerlib-0.4.4.tar.gz
  • Upload date:
  • Size: 15.4 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.4.tar.gz
Algorithm Hash digest
SHA256 86210b9b393d75a87441757ae508b1417afc1a59a10b2782b0cef210bb600ac6
MD5 ed4e073b555df002667162a23d0c8848
BLAKE2b-256 ea24052a3d5bbcfa83ba0c1461d4689e2dd3c09deed20c99b9c55b283a7d2abc

See more details on using hashes here.

Provenance

The following attestation bundles were made for workerlib-0.4.4.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.4-py3-none-any.whl.

File metadata

  • Download URL: workerlib-0.4.4-py3-none-any.whl
  • Upload date:
  • Size: 11.6 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.4-py3-none-any.whl
Algorithm Hash digest
SHA256 1acf66c8aa66def74fe954c8c4a16e8a72f0d5c0aec9ddceff934456f124f1f9
MD5 17f9c6a08af8d4f5492dc06a6bb96493
BLAKE2b-256 bb96258193c2555efd4e435dfea3fa403298a2687992579a83c60784172c5461

See more details on using hashes here.

Provenance

The following attestation bundles were made for workerlib-0.4.4-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