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.15.tar.gz (74.6 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.15-py3-none-any.whl (142.2 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: unrealon-0.1.15.tar.gz
  • Upload date:
  • Size: 74.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.2 Darwin/24.5.0

File hashes

Hashes for unrealon-0.1.15.tar.gz
Algorithm Hash digest
SHA256 06c7f25cc25144c9a046665349e9346711a4844c9973b8955dc0eb4bc12615c4
MD5 6702a522c5a6fbf66c69fa2f353c3a43
BLAKE2b-256 c0de35961f9ca7498b51250002d319d8604ba894f961b79afe19d237cb15f73b

See more details on using hashes here.

File details

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

File metadata

  • Download URL: unrealon-0.1.15-py3-none-any.whl
  • Upload date:
  • Size: 142.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.2.1 CPython/3.13.2 Darwin/24.5.0

File hashes

Hashes for unrealon-0.1.15-py3-none-any.whl
Algorithm Hash digest
SHA256 547db0f3bef63a1c0b5873ca352e76093af40d3c9085f96ea6692fb915a89b3a
MD5 fdd81e07ce1d6b6903662e404bc86fdb
BLAKE2b-256 a1803a71c2afaa951d4bb35fd64660f7f0edc72597b3712d784b079f7c87fee9

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