Metadata-Version: 2.4
Name: wardy-utils
Version: 2.0.0
Summary: General Utilities
Author: Wardy
Author-email: Wardy <wardy3+gitlab@gmail.com>
License-Expression: MIT
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Dist: pydantic-settings>=2.12.0
Requires-Dist: loguru>=0.7.3 ; extra == 'log'
Requires-Dist: httpx>=0.28.1 ; extra == 'neon'
Requires-Dist: anysqlite>=0.0.5 ; extra == 'web'
Requires-Dist: hishel[httpx]>=2,<3 ; extra == 'web'
Requires-Dist: httpx[brotli,http2,zstd]>=0.28.1 ; extra == 'web'
Requires-Python: >=3.12
Provides-Extra: log
Provides-Extra: neon
Provides-Extra: web
Description-Content-Type: text/markdown

# Wardy Utils

**Wardy Utils** is a collection of general-purpose utilities designed to simplify and enhance your Python scripting experience. This library provides reusable components that can be integrated into your projects to save time and effort.

## Installation

```bash
pip install wardy-utils
```

The base package only includes `pydantic-settings`. Install extras for additional functionality:

```bash
# Logging with Loguru
pip install wardy-utils[log]

# HTTP client with caching
pip install wardy-utils[web]

# Neon free-plan usage check
pip install wardy-utils[neon]

# Both
pip install wardy-utils[log,web]
```

## Features

### Logging (`wardy-utils[log]`)

Flexible logging setup using [Loguru](https://github.com/Delgan/loguru), with optional [Logfire](https://logfire.pydantic.dev/) integration for cloud logging and metrics.

**Key features:**

- Simple setup for rotating file and stderr logging
- Intercepts standard Python logging and redirects to Loguru
- Optional Logfire integration for cloud log aggregation
- Automatic instrumentation of available libraries (system-metrics, psycopg, httpx, sqlalchemy, redis, asyncpg)

**Basic usage:**

```python
from wardy_utils.log import configure_logging, logger

# Set up logging to both stderr and a rotating file
configure_logging("myapp")

logger.info("Hello from Loguru!")

# Standard logging is also intercepted:
import logging
logging.warning("This will also go to Loguru!")
```

**With Logfire cloud logging:**

```python
from wardy_utils.log import configure_logging, logger

# service_name defaults to the current working directory name
configure_logging("my-app")

# Or specify explicitly
configure_logging("my-app", service_name="my-app", environment="prod")

logger.info("This goes to Logfire too!")
```

Set `WARDY_UTILS_LOG_LOGFIRE_TOKEN` to enable Logfire. You must have `logfire` installed separately:

```bash
pip install logfire[system-metrics,psycopg,httpx]  # with desired extras
```

**FastAPI:**

```python
from wardy_utils.log import instrument_fastapi

instrument_fastapi(app)  # no-op (returns False) without a Logfire token
```

Needs `logfire[fastapi]`. Healthchecks (`/ping`, `/healthz`) aren't traced by default; pass
`excluded_urls` (regexes searched for in the full URL) to override.

**Customization:**

```python
from wardy_utils.log import configure_logging, LogConfig

config = LogConfig(
    file_level="INFO",
    standard_format="[{time}] {level} - {message}",
    detail_format="{time} {file}:{line} {level} {message}",
    rotation="1 hour",
    retention="14 days",
)

configure_logging("my-app", service_name="my-app", config=config)
```

**Environment variables:**

| Variable                               | Description                     | Default    |
| -------------------------------------- | ------------------------------- | ---------- |
| `WARDY_UTILS_LOG_LOGFIRE_TOKEN`        | Token for Logfire cloud logging | (disabled) |
| `WARDY_UTILS_LOG_LOGFIRE_SERVICE_NAME` | Service name for Logfire        | (cwd name) |
| `WARDY_UTILS_LOG_LOGFIRE_ENVIRONMENT`  | Environment name for Logfire    | (cascaded) |

Cascade behavior when not explicitly set:

- `LOGFIRE_SERVICE_NAME`: Falls back to the current working directory name (e.g. `beer-cloud`)
- `LOGFIRE_ENVIRONMENT`: Falls back to `APP_ENVIRONMENT` → `REFLEX_ENV_MODE` → `NODE_ENV` → `ENVIRONMENT`

### HTTP Client (`wardy-utils[web]`)

A high-level HTTP client built on [httpx](https://www.python-httpx.org/) and [hishel](https://hishel.com/) with built-in caching.

**Basic usage:**

```python
from wardy_utils.web import cached_client

client = cached_client()
response = client.get("https://example.com")
print(response.text)
```

**Pre-configured singletons:**

```python
from wardy_utils.web import sync_client, async_client

# Sync client with default settings
response = sync_client.get("https://example.com")

# Or use async
async def fetch():
    response = await async_client.get("https://example.com")
```

Available singletons:

- `sync_client`: Default sync client (follows RFC 9111 cache headers)
- `sync_force_client`: Sync client that ignores origin cache headers
- `async_client`: Default async client (follows RFC 9111 cache headers)
- `async_force_client`: Async client that ignores origin cache headers

**Caching modes:**

- Default: the cache follows the origin's `Cache-Control` headers (RFC 9111).
- `force=True`: origin headers are ignored. Successful (2xx, except 206) GET and HEAD responses are stored for `ttl`. Errors and redirects are never stored, so they are retried against the origin.
- `force=True, cache_redirects=True`: also remembers 301/302/307/308 responses for `ttl`, so a repeat request to a redirecting URL sends nothing upstream. These are kept in process memory per client (up to 10,000), not in the sqlite cache, so they are lost on restart.

**Was it cached, and when was it fetched?**

```python
from wardy_utils.web import cache_info

response = client.get("https://example.com")
info = cache_info(response)
info.from_cache  # True if the cache answered
info.fetched_at  # epoch seconds the content came off the network, or None
```

Every response that reaches the network is stamped with an `X-Wardy-Fetched-At` header. The header is stored with the cache entry, so `fetched_at` is the original fetch time even on a cache hit. `cache_info` also works for each hop in `response.history`.

**Environment variables:**

| Variable                          | Description                                                        | Default             |
| --------------------------------- | ------------------------------------------------------------------ | ------------------- |
| `WARDY_UTILS_WEB_CACHE_DIR`       | Directory for the sqlite cache file                                | In-memory           |
| `WARDY_UTILS_WEB_CACHE_FILENAME`  | Filename for the sqlite cache file                                 | `wardy_cache_v2.db` |
| `WARDY_UTILS_WEB_CACHE_TTL`       | Cache TTL in seconds                                               | `1800` (30 min)     |
| `WARDY_UTILS_WEB_TIMEOUT`         | Per-operation request timeout in seconds                           | `45`                |
| `WARDY_UTILS_WEB_DEADLINE`        | Total wall-clock deadline in seconds (async only)                  | Off                 |
| `WARDY_UTILS_WEB_FORCE_CACHE`     | If truthy, ignore origin cache-control headers                     | Disabled            |
| `WARDY_UTILS_WEB_CACHE_REDIRECTS` | With force, also remember redirects                                | Disabled            |
| `WARDY_UTILS_WEB_BUST_EDGE_CACHE` | Add a unique `_=` query parameter to upstream requests (CDN bypass) | Disabled            |
| `WARDY_UTILS_WEB_HTTP1`           | Enable or disable HTTP/1.1                                         | Enabled             |
| `WARDY_UTILS_WEB_HTTP2`           | Enable or disable HTTP/2                                           | Enabled             |

**Proxy support:** The client inherits proxy settings from standard `http_proxy`, `https_proxy`, and `all_proxy` environment variables. Proxied requests get the same caching, `fetched_at` stamp, edge-cache busting and redirect memory as direct ones.

#### Upgrading from wardy-utils 1.x (hishel 1.x) to 2.x (hishel 2.x)

wardy-utils 2.0 moves `wardy_utils.web` to hishel 2, which is a redesign of hishel. `cached_client()`, its options and the singletons keep the same signatures. These things change:

| What                    | 1.x                                                  | 2.x                                                                                        |
| ----------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| Was it a cache hit?     | `response.extensions["hishel_from_cache"]`           | `cache_info(response).from_cache`                                                          |
| When was it fetched?    | `response.extensions["hishel_created_at"]`           | `cache_info(response).fetched_at` (hishel 2 no longer records this)                       |
| Force mode internals    | `client.policy` is a hishel `FilterPolicy`; `CacheOnlyOk` / `CacheOkOrRedirect` filters | `client.rfc is False`; the policy and filter classes are gone                              |
| What force mode stores  | 200 only                                             | Any 2xx except 206                                                                         |
| Redirect caching        | 3xx stored in the sqlite cache                       | 3xx remembered in process memory, lost on restart                                          |
| hishel types            | `SyncSqliteStorage`, `hishel.httpx.SyncCacheClient`  | `SqliteStorage`, `hishel.httpx.CacheClient` (`wardy_utils.web.SyncCacheClient` still works) |
| Default cache file      | `wardy_cache.db`                                     | `wardy_cache_v2.db`. hishel 2 refuses to open a 1.x file, so delete the old one.           |
| `timeout=` workaround   | wardy-utils re-injected the timeout hishel 1 dropped | Not needed: hishel 2 passes the request through intact                                     |
| Internal helpers        | Public names (`build_client`, `resolve_config`, ...) | Private (`_build_client`, ...). Use `cached_client()`.                                     |

If you set `WARDY_UTILS_WEB_CACHE_FILENAME` yourself, point it at a new file or delete the old one. Otherwise the first request raises hishel's "This database is a Hishel 1.x cache" error.

### Neon usage (`wardy-utils[neon]`)

Checks a [Neon](https://neon.tech/) project's compute usage against the free plan's monthly CU-hour allowance, and projects the month-end total from the rate since the 1st. Calling Neon's API does not wake the database. Nothing is logged; HTTP and parsing errors (`httpx.HTTPError`, `KeyError`, `ValueError`) propagate for the caller to handle.

```python
from wardy_utils.neon import get_usage

usage = await get_usage("my-project-id", api_key, allowance=100)
print(usage.cu_hours, usage.pct_used, usage.projected_cu_hours, usage.projected_pct)
```

With several worker processes, `claim_usage_lock(path)` lets only one of them call Neon: it returns an open lock file while held, or `None` if another process has it.

## Requirements

- Python 3.12 or higher
- Linux or macOS (`wardy_utils.neon` uses `fcntl` for its usage lock)

## License

This project is licensed under the MIT License.

## Author

Created by **Wardy**
Email: [wardy3+gitlab@gmail.com](mailto:wardy3+gitlab@gmail.com)
