Skip to main content

Unrealon SDK - Service management for Django backend (registration, heartbeat, logging, commands)

Project description

Unrealon SDK

Python SDK для мониторинга и управления сервисами через Unrealon платформу.

Что даёт SDK

  • Мониторинг — видишь статус сервиса в реальном времени
  • Логи в облако — все логи доступны в веб-интерфейсе
  • Управление — pause/resume/stop прямо из дашборда
  • Метрики — счётчики обработанных элементов и ошибок

Установка

pip install unrealon

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

Минимальный пример

from unrealon import ServiceClient

with ServiceClient(api_key="pk_xxx", service_name="my-service") as client:
    client.info("Started")

    for item in items:
        process(item)
        client.increment_processed()

    client.info("Done")

Всё. Сервис зарегистрируется, логи пойдут в облако, метрики будут отображаться.

С поддержкой pause/resume

from unrealon import ServiceClient

with ServiceClient(api_key="pk_xxx", service_name="my-parser") as client:
    client.info("Started")

    for item in items:
        client.check_interrupt()  # Тут парсер встанет на паузу если нажать Pause

        process(item)
        client.increment_processed()

    client.info("Done")

check_interrupt() делает две вещи:

  • Если нажали Pause — ждёт пока нажмут Resume
  • Если нажали Stop — выбрасывает StopInterrupt

Continuous Mode

Сервис который ждёт команд из дашборда:

import time
from unrealon import ServiceClient
from unrealon.exceptions import StopInterrupt

with ServiceClient(api_key="pk_xxx", service_name="my-parser") as client:

    def handle_run(params: dict) -> dict:
        limit = params.get("limit", 100)

        client.set_busy()
        try:
            for i in range(limit):
                client.check_interrupt()
                do_work()
                client.increment_processed()
            return {"status": "ok"}
        except StopInterrupt:
            return {"status": "stopped"}
        finally:
            client.set_idle()

    client.on_command("run", handle_run)

    # Ждём команд
    client.set_idle()
    while not client.should_stop:
        time.sleep(1)

Теперь можно из дашборда:

  • Нажать Run — запустится handle_run
  • Нажать Pause — парсер встанет на check_interrupt()
  • Нажать Resume — продолжит с того же места
  • Нажать Stop — завершится gracefully

API

Логирование

client.debug("Debug message")
client.info("Info message", key="value")
client.warning("Warning")
client.error("Error", code=500)

Логи идут в три места: консоль (Rich), файл, облако.

Метрики

client.increment_processed()      # +1 обработано
client.increment_processed(10)    # +10 обработано
client.increment_errors()         # +1 ошибка

Статусы

client.set_busy()    # Показывает "Busy" в дашборде
client.set_idle()    # Показывает "Idle"

Состояние

client.is_paused     # True если на паузе
client.should_stop   # True если запрошена остановка
client.is_connected  # True если подключен к серверу

Команды

# Регистрация обработчика
client.on_command("run", handle_run)
client.on_command("custom", handle_custom)

# Обработчик получает params и возвращает результат
def handle_run(params: dict) -> dict:
    limit = params.get("limit", 10)
    # ... do work ...
    return {"status": "ok", "processed": 100}

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

Через переменные окружения

export UNREALON_API_KEY=pk_xxx
export UNREALON_SERVICE_NAME=my-service
# Подхватит из env
with ServiceClient() as client:
    ...

Dev mode (локальный сервер)

with ServiceClient(
    api_key="dk_xxx",
    service_name="my-service",
    dev_mode=True,  # Подключится к localhost:50051
) as client:
    ...

Exceptions

from unrealon.exceptions import (
    StopInterrupt,        # Stop requested (наследует BaseException!)
    UnrealonError,        # Base SDK error
    AuthenticationError,  # Bad API key
    RegistrationError,    # Can't register
)

try:
    with ServiceClient(...) as client:
        for item in items:
            client.check_interrupt()
            process(item)
except StopInterrupt:
    print("Stopped by command")

Важно: StopInterrupt наследует BaseException, не Exception. Это значит что except Exception его НЕ поймает — специально, чтобы generic error handlers не глотали команду stop.

Standalone Logger

Можно использовать логгер отдельно от SDK:

from unrealon.logging import get_logger

log = get_logger("myapp")
log.info("Starting", version="1.0")
log.error("Failed", error="connection timeout")

Логи пойдут в консоль и файл (без облака).

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

unrealon-0.1.14.tar.gz (73.4 kB view details)

Uploaded Source

Built Distribution

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

unrealon-0.1.14-py3-none-any.whl (125.2 kB view details)

Uploaded Python 3

File details

Details for the file unrealon-0.1.14.tar.gz.

File metadata

  • Download URL: unrealon-0.1.14.tar.gz
  • Upload date:
  • Size: 73.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.18

File hashes

Hashes for unrealon-0.1.14.tar.gz
Algorithm Hash digest
SHA256 97883d1482647226f0a327bb184d042ad28f22da05145f7568f823631bde8e6e
MD5 8e2283a95cbc38fd81e60851f2e478ab
BLAKE2b-256 2e7cdfc1925f0c29f9932371c35c5d6cfbfed109df256aa8ddfcc8a06ba93231

See more details on using hashes here.

File details

Details for the file unrealon-0.1.14-py3-none-any.whl.

File metadata

  • Download URL: unrealon-0.1.14-py3-none-any.whl
  • Upload date:
  • Size: 125.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.10.18

File hashes

Hashes for unrealon-0.1.14-py3-none-any.whl
Algorithm Hash digest
SHA256 935eac20cdf13a655c82e8d544bc914e5ab58d786b3aa78a8de8aed03e7c851a
MD5 bd95f82776ebfc582ed20bc6e15b17b3
BLAKE2b-256 2135f2fcd7f2367c32ac4d9d34c43a5bceebed7cb0d36144f3523dfe78ab7946

See more details on using hashes here.

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