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}

Расписания

Расписания (Schedules) запускаются автоматически по cron-выражению. Если action_type расписания совпадает с зарегистрированной командой — используется тот же обработчик:

# Этот handler сработает и для ручного Run, и для scheduled run
client.on_command("run", handle_run)

Если нужно разное поведение — регистрируй отдельный schedule handler:

@client.on_schedule("process")
def handle_scheduled_process(schedule, params):
    # schedule.name, schedule.id доступны
    return {"items_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.16.tar.gz (75.1 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.16-py3-none-any.whl (142.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: unrealon-0.1.16.tar.gz
  • Upload date:
  • Size: 75.1 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.16.tar.gz
Algorithm Hash digest
SHA256 1492e557dc821dbf05e5e6179f735e162a801f1d38f100bd42a216bc850f34a0
MD5 63d0b77a75770e994f2793b8a5e3b22c
BLAKE2b-256 af2853a7c6a4c41291b182783e187f3cb71ae5bd17dabb36e9777eb2ce50b349

See more details on using hashes here.

File details

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

File metadata

  • Download URL: unrealon-0.1.16-py3-none-any.whl
  • Upload date:
  • Size: 142.8 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.16-py3-none-any.whl
Algorithm Hash digest
SHA256 d04ce5362320f87c7dace4eaf940118f363a5822cb427e02d1092598aca8e57a
MD5 b37d5f4c6cc297601049eb29b1f70440
BLAKE2b-256 032acbe31ad9f6a13e26b7df455890361aecb16dff5bf966f83af4def24545c1

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