Metadata-Version: 2.4
Name: lifebeacon
Version: 2.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. Designed for notifying external systems about critical events such as failures or exceptions. Supports both async and sync usage.

The internal HTTP client is created lazily on first use and reused across subsequent calls. Call `aclose()` in async contexts or `close()` in sync contexts when the instance is no longer needed to release the underlying connection pool.

**Async usage:**

```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
)

await alert.async_send(message="Database connection failed", level="critical")

await alert.aclose()
```

**Sync usage:**

```python
from lifebeacon import CriticalAlert

alert = CriticalAlert(
    url="https://monitoring.example.com/alert",
    token="your-token",
    service="my-service",
)

alert.sync_send(message="Database connection failed", level="critical")

alert.close()
```

Extra keyword arguments passed to `async_send()` or `sync_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.aclose()` / `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-запит. Призначений для сповіщення зовнішніх систем про критичні події — збої, виключення тощо. Підтримує як async, так і sync використання.

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

**Async використання:**

```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.async_send(message="Database connection failed", level="critical")

await alert.aclose()
```

**Sync використання:**

```python
from lifebeacon import CriticalAlert

alert = CriticalAlert(
    url="https://monitoring.example.com/alert",
    token="your-token",
    service="my-service",
)

alert.sync_send(message="Database connection failed", level="critical")

alert.close()
```

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

### Примітки

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