Metadata-Version: 2.4
Name: lifebeacon
Version: 1.0.0
Summary: Lightweight heartbeat and critical alert monitoring for microservices
License-Expression: MIT
License-File: LICENSE
Keywords: alerting,heartbeat,microservices,monitoring
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27.0
Description-Content-Type: text/markdown

# lifebeacon

**[English](#english) | [Українська](#українська)**

---

## English

Lightweight monitoring library for microservices. Provides two independent components: periodic heartbeat pings and one-time critical alert notifications over HTTP.

### Installation

```bash
pip install lifebeacon
```

```bash
uv add lifebeacon
```

### Requirements

- Python 3.11+

### Components

#### Heartbeat

Sends periodic HTTP requests to a specified endpoint on a background daemon thread. Useful for signaling liveness to external monitoring systems.

```python
from lifebeacon import Heartbeat

heartbeat = Heartbeat(
    url="https://monitoring.example.com/ping",
    interval=60,           # seconds between requests, default 120
    token="your-token",    # optional Bearer token
    method="POST",         # default POST
    timeout=5,             # request timeout in seconds, default 5
    service="my-service",  # any extra fields go into the JSON body
)

heartbeat.start()  # starts background thread, no effect if already running
# ...
heartbeat.stop()   # stops the thread and waits up to 5 seconds for it to finish
```

#### CriticalAlert

Sends a one-time HTTP request asynchronously. Designed for notifying external systems about critical events such as failures or exceptions.

The HTTP client is reused across calls. Call `close()` when the instance is no longer needed to release the underlying connection pool.

```python
from lifebeacon import CriticalAlert

alert = CriticalAlert(
    url="https://monitoring.example.com/alert",
    token="your-token",    # optional Bearer token
    method="POST",         # default POST
    timeout=5,             # request timeout in seconds, default 5
    service="my-service",  # any extra fields become default JSON body fields
)

# Send an alert with additional fields
await alert.send(message="Database connection failed", level="critical")

# Release resources when done
await alert.close()
```

Extra keyword arguments passed to `send()` are merged with the instance-level defaults. Call-time values override instance-level defaults for duplicate keys.

### Notes

- All HTTP errors are silently suppressed in both components to avoid disrupting the host application.
- `Heartbeat` runs on a daemon thread — it will not prevent the process from exiting.
- `CriticalAlert.close()` must be called explicitly when the instance is no longer needed.

---

## Українська

Легковагова бібліотека моніторингу для мікросервісів. Надає два незалежних компоненти: періодичні heartbeat-пінги та одноразові сповіщення про критичні події через HTTP.

### Встановлення

```bash
pip install lifebeacon
```

```bash
uv add lifebeacon
```

### Вимоги

- Python 3.11+

### Компоненти

#### Heartbeat

Відправляє періодичні HTTP-запити на вказаний endpoint у фоновому daemon-потоці. Використовується для сигналізації про роботу сервісу зовнішнім системам моніторингу.

```python
from lifebeacon import Heartbeat

heartbeat = Heartbeat(
    url="https://monitoring.example.com/ping",
    interval=60,           # секунди між запитами, за замовчуванням 120
    token="your-token",    # опціональний Bearer токен
    method="POST",         # за замовчуванням POST
    timeout=5,             # таймаут запиту в секундах, за замовчуванням 5
    service="my-service",  # будь-які додаткові поля потрапляють у тіло JSON
)

heartbeat.start()  # запускає фоновий потік, не має ефекту якщо вже запущений
# ...
heartbeat.stop()   # зупиняє потік і чекає до 5 секунд на завершення
```

#### CriticalAlert

Відправляє одноразовий HTTP-запит асинхронно. Призначений для сповіщення зовнішніх систем про критичні події — збої, виключення тощо.

HTTP-клієнт перевикористовується між викликами. Викличте `close()` коли інстанс більше не потрібен, щоб звільнити connection pool.

```python
from lifebeacon import CriticalAlert

alert = CriticalAlert(
    url="https://monitoring.example.com/alert",
    token="your-token",    # опціональний Bearer токен
    method="POST",         # за замовчуванням POST
    timeout=5,             # таймаут запиту в секундах, за замовчуванням 5
    service="my-service",  # будь-які додаткові поля стають дефолтними полями JSON тіла
)

# Відправити алерт з додатковими полями
await alert.send(message="Database connection failed", level="critical")

# Звільнити ресурси після завершення роботи
await alert.close()
```

Додаткові keyword-аргументи, передані в `send()`, мерджаться з дефолтними полями інстансу. При дублюванні ключів — значення з `send()` мають пріоритет.

### Примітки

- Всі HTTP-помилки мовчазно ігноруються в обох компонентах, щоб не переривати роботу хост-додатку.
- `Heartbeat` працює в daemon-потоці — він не блокує завершення процесу.
- `CriticalAlert.close()` потрібно викликати явно коли інстанс більше не потрібен.
