Common utilities for X-Scanner microservices
Project description
X-Scanner Commons
Common utilities and infrastructure components for X-Scanner microservices.
Overview
X-Scanner Commons is a Python package that provides reusable components for building microservices in the X-Scanner security scanning platform. It includes infrastructure components (cache, vault, database), configuration management, logging, and utility functions.
Features
-
Infrastructure Layer
- Cache abstraction with Redis and in-memory implementations
- HashiCorp Vault integration for secret management
- Database session management with async SQLAlchemy support
-
Configuration Management
- Pydantic-based configuration with environment variable support
- Common configuration patterns for microservices
- Built-in validators for common configuration types
-
Logging & Monitoring
- Structured JSON logging
- Request ID tracking for distributed tracing
- Configurable log levels and formats
-
Utilities
- Common helper functions
- Password hashing and verification
- Retry decorators for async functions
- Data manipulation utilities
Installation
Basic Installation
pip install x-scanner-commons
With Optional Dependencies
Install with specific features:
# Cache support (Redis)
pip install "x-scanner-commons[cache]"
# Vault support (HashiCorp Vault)
pip install "x-scanner-commons[vault]"
# Database support (SQLAlchemy, AsyncPG)
pip install "x-scanner-commons[database]"
# All features
pip install "x-scanner-commons[all]"
Development Installation
# Clone the repository
git clone https://github.com/x-scanner/x-scanner-commons.git
cd x-scanner-commons
# Install with Poetry
poetry install --all-extras
# Or with pip
pip install -e ".[all]"
Quick Start
Basic Configuration
from x_scanner_commons import BaseConfig, get_logger
# Create configuration
class ServiceConfig(BaseConfig):
custom_setting: str = "default_value"
config = ServiceConfig()
logger = get_logger(__name__)
logger.info(f"Starting {config.service_name} on port {config.port}")
Using Cache
from x_scanner_commons.infrastructure.cache import MemoryCache, RedisCache
# In-memory cache (no dependencies)
cache = MemoryCache()
await cache.set("key", "value", ttl=60)
value = await cache.get("key")
# Redis cache (requires redis extra)
cache = RedisCache(host="localhost", port=6379)
await cache.set("user:123", {"name": "John", "email": "john@example.com"})
Secret Management with Vault
from x_scanner_commons.infrastructure.vault import VaultClient
# Initialize Vault client (requires vault extra)
vault = VaultClient(
url="http://localhost:8200",
token="your-token"
)
# Store and retrieve secrets
await vault.set_secret("api/keys", {"api_key": "secret123"})
secret = await vault.get_secret("api/keys")
api_key = secret.get("api_key")
Database Sessions
from x_scanner_commons.infrastructure.database import AsyncSessionManager, get_async_session
# Option 1: Manual session manager
db = AsyncSessionManager(
database_url="postgresql+asyncpg://user:pass@localhost/db"
)
# Option 2: Use the cached get_async_session function (recommended)
# This function is decorated with @alru_cache for efficient connection pooling
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Annotated
@app.get("/users")
async def get_users(
db: Annotated[AsyncSession, Depends(get_async_session)]
):
# Use database session
pass
Structured Logging
from x_scanner_commons import get_logger, setup_logging
# Setup logging
setup_logging(
level="INFO",
format_type="json",
service_name="my-service"
)
# Get logger
logger = get_logger(__name__)
# Log with structured data
logger.info("User logged in", extra_fields={
"user_id": 123,
"ip_address": "192.168.1.1"
})
Module Documentation
Configuration Layer
Base Configuration
BaseConfig: Base configuration class with common settingsEnvironment: Environment enum (development, testing, staging, production)LogLevel: Log level enum
Validators
validate_port: Port number validationvalidate_database_url: Database URL validationvalidate_redis_url: Redis URL validationvalidate_email: Email address validation
Core Layer
Logging
get_logger: Get configured logger instancesetup_logging: Configure logging systemJSONFormatter: JSON log formatterget_request_id,set_request_id: Request ID tracking
Exceptions
BaseError: Base exception class with error codesConfigurationError: Configuration-related errorsValidationError: Validation errors with field informationNotFoundError: Resource not found errorsAuthenticationError: Authentication failures
Utilities
Helper Functions
generate_id: Generate unique identifiersgenerate_token: Generate secure random tokenshash_password,verify_password: Password hashingdeep_merge: Deep merge dictionarieschunk_list: Split lists into chunksretry_async: Retry decorator for async functions
Development
Running Tests
# Run all tests
make test
# Run with coverage
pytest --cov=x_scanner_commons --cov-report=html
# Run specific test module
pytest tests/infrastructure/test_cache.py
Code Quality
# Format code
make format
# Run linters
make lint
# Type checking
mypy x_scanner_commons/
Building Package
# Build distribution
make build
# Clean build artifacts
make clean
Version History
0.1.0 (Initial Release)
- Infrastructure layer with cache, vault, and database modules
- Configuration management with Pydantic
- Structured logging with JSON support
- Common utilities and helpers
- Comprehensive test coverage
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
For issues and questions, please open an issue on the GitHub repository.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file x_scanner_commons-0.1.1.tar.gz.
File metadata
- Download URL: x_scanner_commons-0.1.1.tar.gz
- Upload date:
- Size: 66.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.11.11 Darwin/25.0.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
7af6ed777c5ff6e5bd5bee88c91ec9f55c98feeb52f027f92f36ebe5b7393cd7
|
|
| MD5 |
db5709d45bc992afd31842aa7d0a324e
|
|
| BLAKE2b-256 |
651e972d2d9b09e6999a4d7422ff270b7d3d99b1213d0c5d14d7e7d34103475e
|
File details
Details for the file x_scanner_commons-0.1.1-py3-none-any.whl.
File metadata
- Download URL: x_scanner_commons-0.1.1-py3-none-any.whl
- Upload date:
- Size: 89.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.11.11 Darwin/25.0.0
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d1e9ca917c33d2290852272637a4c5c1b54a660ab1aa68c0a4b9547cfce2f94c
|
|
| MD5 |
4d0ae5c42151c58d36ba406107c5cdf5
|
|
| BLAKE2b-256 |
ef80268d72ea691f147958a810ac51d0619da1b5b315244b0573176fb18caff4
|