dcnr-spring


Namedcnr-spring JSON
Version 1.0.2 PyPI version JSON
download
home_pageNone
SummaryScheduling python functions for execution.
upload_time2025-10-09 12:13:11
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT
keywords python scheduler
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # DCNR Spring API Documentation

The `dcnr_spring` is a comprehensive Python package providing utilities for application monitoring, database operations, security, subprocess management, and more. This package follows Spring Framework patterns and provides a robust foundation for enterprise Python applications.

## Package Overview

```python
import dcnr_spring

# Available modules
dcnr_spring.actuator      # Application health monitoring
dcnr_spring.coding        # Development utilities
dcnr_spring.database      # Database abstraction layer
dcnr_spring.monitor       # System monitoring and logging
dcnr_spring.notifications # Event notification system
dcnr_spring.requests      # Request handling utilities
dcnr_spring.security      # Security and encryption
dcnr_spring.subprocess    # Process management
dcnr_spring.utils         # General utilities
```

## spring.actuator

Provides monitoring status for application components. It maintains in-memory data that can be requested by external systems. It provides only the data backend - the interface with external systems (HTTP, RabbitMQ, etc.) must be implemented by the application.

### Functions

**`register_actuator_component(name: str, status_func: Callable[[], str], details_func: Callable[[], Dict] = None)`**
- Registers a component for health monitoring
- `name`: Component identifier
- `status_func`: Function returning component status (UP/DOWN/NA)
- `details_func`: Optional function returning additional component details

**`on_actuator_endpoint(name: str) -> Callable`**
- Decorator for registering actuator endpoints
- `name`: Endpoint name

**`on_actuator_root() -> Callable`**
- Decorator for the root actuator endpoint

**`is_ok(component_name: str) -> bool`**
- Checks if a component status is OK (UP)

**`get_actuator_components() -> Dict[str, Dict]`**
- Returns all registered components and their status

**`get_component_response(name: str) -> Dict`**
- Gets detailed response for a specific component

### Constants

- `STATUS_OK = "UP"` - Component is healthy
- `STATUS_FAIL = "DOWN"` - Component has issues
- `STATUS_UNKNOWN = "NA"` - Component status unknown

### Example

```python
from dcnr_spring.actuator import register_actuator_component, STATUS_OK, STATUS_FAIL

def database_health():
    try:
        # Check database connection
        return STATUS_OK
    except:
        return STATUS_FAIL

def database_details():
    return {"connection_pool": 5, "active_connections": 2}

register_actuator_component("database", database_health, database_details)
```

## spring.coding

Development utilities and decorators.

### Decorators

**`@deprecated(reason: str = None, version: str = None)`**
- Marks functions/classes as deprecated
- Issues warning when deprecated items are used
- `reason`: Optional deprecation reason
- `version`: Optional version when deprecated

### Example

```python
from dcnr_spring.coding import deprecated

@deprecated("Use new_function() instead", version="2.0")
def old_function():
    return "deprecated"
```

## spring.database

Database abstraction layer with ORM-like functionality supporting multiple backends.

### Core Classes

**`DatabaseEntity`**
- Base class for database entities
- Provides common database operations

**`Database`**
- Abstract base class for database implementations
- Defines standard interface for database operations

### Decorators

**`@dbtable(schema: str = None, table: str = None, repr: bool = True)`**
- Class decorator for database entities
- Automatically generates `__init__`, field metadata, and database operations
- `schema`: Database schema name
- `table`: Table name (defaults to class name)

**`dbfield(alias: str = None, primary: bool = False, nullable: bool = True, default: Any = None, dtype: str = None)`**
- Field descriptor for database columns
- `alias`: Database column name (if different from field name)
- `primary`: Mark as primary key
- `nullable`: Allow null values
- `default`: Default value
- `dtype`: Database data type

### Database Backends

**Memory Database**
```python
from dcnr_spring.database.memory import MemoryDatabase

db = MemoryDatabase()
```

**PostgreSQL Database**
```python
from dcnr_spring.database.postgres import PostgresDatabase

db = PostgresDatabase(connection_string="postgresql://...")
```

### Query Expressions

**`F(field_name: str)`**
- Creates field expressions for queries
- Supports comparison operators: `==`, `!=`, `>`, `<`, `>=`, `<=`
- Supports logical operators: `&` (AND), `|` (OR)

**`Q(**kwargs)`**
- Creates query expressions from keyword arguments
- Combines multiple conditions with AND logic

### Example

```python
from dcnr_spring.database import DatabaseEntity, dbtable, dbfield
from dcnr_spring.database.memory import MemoryDatabase
from dcnr_spring.database.base.query_expression import F, Q

@dbtable(schema="app", table="users")
class User(DatabaseEntity):
    name: str = dbfield()
    email: str = dbfield(alias="email_address")
    age: int = dbfield(default=0)

# Database operations
db = MemoryDatabase()

# Insert
user = User(name="John", email="john@example.com", age30)
db.insert(user)

# Query with expressions
adults = db.find(User, F('age') >= 18)
active_users = db.find(User, F('status') == 'active', F('last_login') > yesterday)

# Complex queries
engineers = db.find(User, 
                   (F('department') == 'Engineering') & (F('experience') > 2))

# Delete operations
deleted_count = db.delete(User, F('age') < 18)

# Chaining with order and limit
top_users = db.find(User, F('score') > 100).order(score='desc').limit(10)
```

## spring.monitor

System monitoring and application telemetry.

### Client Monitoring

**PodHub Sync Functions**
- `set_application_name(name: str)` - Set application identifier
- `set_server_url(url: str)` - Set monitoring server URL  
- `start_pod_hub()` - Start monitoring client
- `stop_pod_hub()` - Stop monitoring client

**Live Data Logging**
- `livedata_log(tag: str, level: str, message: str, exception: Exception = None)` - Log application events
- `livedata_page()` - Get current live data page
- `livedata_setlimit(tag: str, limit: int)` - Set log retention limit

**Instance Management**
- `set_instance_status(status: str)` - Update instance status
- `get_instance_status() -> str` - Get current instance status

**System Information**
- `get_pip_packages()` - Get installed Python packages
- `get_logger_list()` - Get available loggers

**Performance Monitoring**
- `codepoint_log(point: str, message: str)` - Log performance checkpoint
- `codepoints_get_tree()` - Get performance data tree
- `codepoints_get_list()` - Get performance data list

### Server Monitoring

**PodHub Server Classes**
- `PodHubApplication` - Main monitoring application
- `PodHubInfo` - Information management
- `PodHubData` - Data storage and retrieval

**Server Functions**
- `register_endpoints(app)` - Register monitoring endpoints
- `get_app_pips(app_name: str)` - Get application packages
- `get_live_services()` - Get live service list
- `ai_get_app(query: str)` - AI-powered app information
- `get_app_instances(app_name: str)` - Get application instances

### Memory Monitoring

- `start_memory_watch()` - Start memory monitoring
- `stop_memory_watch()` - Stop memory monitoring  
- `add_threshold(threshold: int, callback: Callable)` - Add memory threshold
- `get_memory_usage() -> MemoryUsage` - Get current memory usage
- `hist_memory_max()` - Get historical memory maximum

### Thread Database

- `get_thread_record(thread_id: str)` - Get thread information
- `get_live_threads()` - Get active threads
- `save_thread_data(data: Dict)` - Save thread correlation data
- `get_thread_data(thread_id: str)` - Retrieve thread data

### Example

```python
from dcnr_spring.monitor.client import (
    set_application_name, start_pod_hub, livedata_log, 
    set_instance_status, codepoint_log
)

# Setup monitoring
set_application_name("my-app")
start_pod_hub()

# Log events
livedata_log("app", "INFO", "Application started")
set_instance_status("running")

# Performance monitoring
codepoint_log("startup", "Application initialization complete")
```

## spring.notifications

Event notification and messaging system with thread-safe operations.

### Notification Center

**`send(message: str, category: str = None, **kwargs)`**
- Send notification to registered handlers
- `message`: Notification message
- `category`: Optional message category
- `**kwargs`: Additional message data

**`register(handler: Callable, category: str = None)`**
- Register notification handler
- `handler`: Function to handle notifications
- `category`: Optional category filter

**`unregister(handler: Callable, category: str = None)`**
- Unregister notification handler

### Service Management

**`shutdown_service()`**
- Initiate graceful service shutdown
- Sends shutdown notifications to registered handlers

**`is_shutting_down() -> bool`**
- Check if service shutdown is in progress

### Test Mode

**`set_test_mode(enabled: bool)`**
- Enable/disable test mode
- Affects shutdown behavior and logging

**`get_test_mode() -> bool`**
- Check if test mode is enabled

### Thread-Safe Utilities

**`LockedValue[T]`**
- Thread-safe value container
- Provides atomic read/write operations with locking

### Example

```python
from dcnr_spring.notifications import send, register, shutdown_service

def error_handler(message, category=None, **kwargs):
    print(f"Error: {message}")

def info_handler(message, category=None, **kwargs):
    print(f"Info: {message}")

# Register handlers
register(error_handler, "error")
register(info_handler, "info")

# Send notifications
send("Application started", "info")
send("Database connection failed", "error", details={"host": "localhost"})

# Graceful shutdown
shutdown_service()
```

## spring.requests

Request handling and message service utilities.

### Request Logging

**`StreamLogger`**
- Logger that writes to string stream
- Useful for capturing log output in memory

### Message Services

**`MessageServiceClient`**
- Base class for message service implementations
- Provides common patterns for request/response handling

**`EmptyMessageService`**
- No-op implementation for testing
- Safe fallback when no real service is available

### Request Counting

**`@message_counter(name: str = None)`**
- Decorator for counting method calls
- `name`: Optional counter name (defaults to method name)

**`counter.get_count(name: str) -> int`**
- Get current count for named counter

**`counter.wait_for_empty(name: str, timeout: float = None) -> bool`**
- Wait for counter to reach zero
- Useful for ensuring all requests are processed

### Example

```python
from dcnr_spring.requests import StreamLogger, message_counter, counter

# Stream logging
logger = StreamLogger()
logger.info("Test message")
output = logger.getvalue()

# Request counting
@message_counter("api_calls")
def handle_request():
    # Process request
    pass

# Check counts
current_count = counter.get_count("api_calls")
counter.wait_for_empty("api_calls", timeout=30.0)
```

## spring.security

Security utilities and encryption functions.

### Encryption

**`ciphering.cipher(data: str, key: str) -> str`**
- Encrypt data using XOR cipher
- `data`: String to encrypt
- `key`: Encryption key
- Returns: Encrypted string

**`ciphering.decipher(encrypted: str, key: str) -> str`**
- Decrypt data using XOR cipher
- `encrypted`: Encrypted string
- `key`: Decryption key (must match encryption key)
- Returns: Decrypted string

### Example

```python
from dcnr_spring.security.ciphering import cipher, decipher

# Encrypt sensitive data
secret = "sensitive information"
key = "my-secret-key"
encrypted = cipher(secret, key)

# Decrypt when needed
decrypted = decipher(encrypted, key)
assert decrypted == secret
```

## spring.subprocess

Process management and subprocess utilities.

### Process Arguments

**`SubprocessArguments`**
- Container for subprocess arguments
- Handles serialization of complex data types

### Process Communication

**`SubprocessPickleRunner`**
- Executes functions in subprocess using pickle serialization
- Handles bidirectional communication

**`SubprocessPickle`**
- Manages pickle-based subprocess communication
- Provides high-level interface for process management

### Process Results

**`SubprocessResult`**
- Container for subprocess execution results
- Includes return value, stdout, stderr, and exit code

### Environment Detection

**`is_subprocess() -> bool`**
- Detect if current process is a subprocess
- Uses environment variable `SUBPROCESS_ENV_NAME`

**`SUBPROCESS_ENV_NAME = "DCNR_SPRING_SUBPROCESS"`**
- Environment variable name used for subprocess detection

### Example

```python
from dcnr_spring.subprocess import SubprocessPickleRunner, is_subprocess

def worker_function(data):
    # Process data in subprocess
    return data * 2

if not is_subprocess():
    runner = SubprocessPickleRunner()
    result = runner.execute(worker_function, args=[5])
    print(result.return_value)  # 10
```

## spring.utils

General utilities and helper classes.

### Thread-Safe Counter

**`SafeCounter`**
- Thread-safe counter implementation
- Supports increment, decrement, and atomic operations
- Methods:
  - `increment() -> int` - Increment and return new value
  - `decrement() -> int` - Decrement and return new value
  - `get() -> int` - Get current value
  - `set(value: int)` - Set value
  - `reset()` - Reset to zero

### Application Lifecycle

**`waitloop_start()`**
- Initialize application wait loop
- Used for graceful application lifecycle management

**`waitloop_is_at_exit() -> bool`**
- Check if application is in exit state
- Returns True when shutdown has been initiated

### File System Utilities

**`WorkingFileSpace`**
- Context manager for temporary directory management
- Automatically creates and cleans up working directories
- Methods:
  - `get_file_name(filename: str) -> str` - Get full path for file
  - `mkdir(dirname: str) -> str` - Create subdirectory
  - `exists(path: str) -> bool` - Check if path exists
  - `cleanup()` - Manual cleanup (automatic on exit)

### Example

```python
from dcnr_spring.utils import SafeCounter, WorkingFileSpace, waitloop_start

# Thread-safe counting
counter = SafeCounter()
counter.increment()  # Returns 1
current = counter.get()  # Returns 1

# Temporary workspace
with WorkingFileSpace(dirname="temp_work") as ws:
    file_path = ws.get_file_name("data.txt")
    subdir = ws.mkdir("subdirectory")
    # Directory automatically cleaned up on exit

# Application lifecycle
waitloop_start()
```

## Error Handling and Best Practices

### Exception Handling
All modules provide appropriate exception handling and error propagation. Use try-catch blocks for operations that may fail.

### Thread Safety
Components marked as thread-safe (SafeCounter, LockedValue, notification system) can be safely used in multi-threaded applications.

### Resource Management
Use context managers (WorkingFileSpace) and proper cleanup patterns. The package provides automatic resource management where possible.

### Testing
All modules include test mode support and utilities for unit testing. Use the test utilities in `dcnr_spring.notifications.testmode` for testing scenarios.

## Integration Examples

### Complete Application Setup

```python
from dcnr_spring.actuator import register_actuator_component, STATUS_OK
from dcnr_spring.database.memory import MemoryDatabase
from dcnr_spring.database import DatabaseEntity, dbtable, dbfield
from dcnr_spring.monitor.client import set_application_name, start_pod_hub
from dcnr_spring.notifications import register, send

# Database setup
@dbtable("app", "users")
class User(DatabaseEntity):
    name: str = dbfield()
    email: str = dbfield()

db = MemoryDatabase()

# Health monitoring
def db_health():
    return STATUS_OK if db else STATUS_FAIL

register_actuator_component("database", db_health)

# Application monitoring
set_application_name("my-application")
start_pod_hub()

# Event handling
def audit_handler(message, **kwargs):
    print(f"Audit: {message}")

register(audit_handler, "audit")

# Application ready
send("Application initialized", "audit")
```

This comprehensive API provides everything needed to build robust, monitorable, and maintainable Python applications following enterprise patterns.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "dcnr-spring",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "python, scheduler",
    "author": null,
    "author_email": "Peter Kollath <peter.kollath@gopal.home.sk>",
    "download_url": "https://files.pythonhosted.org/packages/cd/78/8eb8b92b72f565d245c2edf46f824f13fd862607f6873fc095c9def33de0/dcnr_spring-1.0.2.tar.gz",
    "platform": null,
    "description": "# DCNR Spring API Documentation\n\nThe `dcnr_spring` is a comprehensive Python package providing utilities for application monitoring, database operations, security, subprocess management, and more. This package follows Spring Framework patterns and provides a robust foundation for enterprise Python applications.\n\n## Package Overview\n\n```python\nimport dcnr_spring\n\n# Available modules\ndcnr_spring.actuator      # Application health monitoring\ndcnr_spring.coding        # Development utilities\ndcnr_spring.database      # Database abstraction layer\ndcnr_spring.monitor       # System monitoring and logging\ndcnr_spring.notifications # Event notification system\ndcnr_spring.requests      # Request handling utilities\ndcnr_spring.security      # Security and encryption\ndcnr_spring.subprocess    # Process management\ndcnr_spring.utils         # General utilities\n```\n\n## spring.actuator\n\nProvides monitoring status for application components. It maintains in-memory data that can be requested by external systems. It provides only the data backend - the interface with external systems (HTTP, RabbitMQ, etc.) must be implemented by the application.\n\n### Functions\n\n**`register_actuator_component(name: str, status_func: Callable[[], str], details_func: Callable[[], Dict] = None)`**\n- Registers a component for health monitoring\n- `name`: Component identifier\n- `status_func`: Function returning component status (UP/DOWN/NA)\n- `details_func`: Optional function returning additional component details\n\n**`on_actuator_endpoint(name: str) -> Callable`**\n- Decorator for registering actuator endpoints\n- `name`: Endpoint name\n\n**`on_actuator_root() -> Callable`**\n- Decorator for the root actuator endpoint\n\n**`is_ok(component_name: str) -> bool`**\n- Checks if a component status is OK (UP)\n\n**`get_actuator_components() -> Dict[str, Dict]`**\n- Returns all registered components and their status\n\n**`get_component_response(name: str) -> Dict`**\n- Gets detailed response for a specific component\n\n### Constants\n\n- `STATUS_OK = \"UP\"` - Component is healthy\n- `STATUS_FAIL = \"DOWN\"` - Component has issues\n- `STATUS_UNKNOWN = \"NA\"` - Component status unknown\n\n### Example\n\n```python\nfrom dcnr_spring.actuator import register_actuator_component, STATUS_OK, STATUS_FAIL\n\ndef database_health():\n    try:\n        # Check database connection\n        return STATUS_OK\n    except:\n        return STATUS_FAIL\n\ndef database_details():\n    return {\"connection_pool\": 5, \"active_connections\": 2}\n\nregister_actuator_component(\"database\", database_health, database_details)\n```\n\n## spring.coding\n\nDevelopment utilities and decorators.\n\n### Decorators\n\n**`@deprecated(reason: str = None, version: str = None)`**\n- Marks functions/classes as deprecated\n- Issues warning when deprecated items are used\n- `reason`: Optional deprecation reason\n- `version`: Optional version when deprecated\n\n### Example\n\n```python\nfrom dcnr_spring.coding import deprecated\n\n@deprecated(\"Use new_function() instead\", version=\"2.0\")\ndef old_function():\n    return \"deprecated\"\n```\n\n## spring.database\n\nDatabase abstraction layer with ORM-like functionality supporting multiple backends.\n\n### Core Classes\n\n**`DatabaseEntity`**\n- Base class for database entities\n- Provides common database operations\n\n**`Database`**\n- Abstract base class for database implementations\n- Defines standard interface for database operations\n\n### Decorators\n\n**`@dbtable(schema: str = None, table: str = None, repr: bool = True)`**\n- Class decorator for database entities\n- Automatically generates `__init__`, field metadata, and database operations\n- `schema`: Database schema name\n- `table`: Table name (defaults to class name)\n\n**`dbfield(alias: str = None, primary: bool = False, nullable: bool = True, default: Any = None, dtype: str = None)`**\n- Field descriptor for database columns\n- `alias`: Database column name (if different from field name)\n- `primary`: Mark as primary key\n- `nullable`: Allow null values\n- `default`: Default value\n- `dtype`: Database data type\n\n### Database Backends\n\n**Memory Database**\n```python\nfrom dcnr_spring.database.memory import MemoryDatabase\n\ndb = MemoryDatabase()\n```\n\n**PostgreSQL Database**\n```python\nfrom dcnr_spring.database.postgres import PostgresDatabase\n\ndb = PostgresDatabase(connection_string=\"postgresql://...\")\n```\n\n### Query Expressions\n\n**`F(field_name: str)`**\n- Creates field expressions for queries\n- Supports comparison operators: `==`, `!=`, `>`, `<`, `>=`, `<=`\n- Supports logical operators: `&` (AND), `|` (OR)\n\n**`Q(**kwargs)`**\n- Creates query expressions from keyword arguments\n- Combines multiple conditions with AND logic\n\n### Example\n\n```python\nfrom dcnr_spring.database import DatabaseEntity, dbtable, dbfield\nfrom dcnr_spring.database.memory import MemoryDatabase\nfrom dcnr_spring.database.base.query_expression import F, Q\n\n@dbtable(schema=\"app\", table=\"users\")\nclass User(DatabaseEntity):\n    name: str = dbfield()\n    email: str = dbfield(alias=\"email_address\")\n    age: int = dbfield(default=0)\n\n# Database operations\ndb = MemoryDatabase()\n\n# Insert\nuser = User(name=\"John\", email=\"john@example.com\", age30)\ndb.insert(user)\n\n# Query with expressions\nadults = db.find(User, F('age') >= 18)\nactive_users = db.find(User, F('status') == 'active', F('last_login') > yesterday)\n\n# Complex queries\nengineers = db.find(User, \n                   (F('department') == 'Engineering') & (F('experience') > 2))\n\n# Delete operations\ndeleted_count = db.delete(User, F('age') < 18)\n\n# Chaining with order and limit\ntop_users = db.find(User, F('score') > 100).order(score='desc').limit(10)\n```\n\n## spring.monitor\n\nSystem monitoring and application telemetry.\n\n### Client Monitoring\n\n**PodHub Sync Functions**\n- `set_application_name(name: str)` - Set application identifier\n- `set_server_url(url: str)` - Set monitoring server URL  \n- `start_pod_hub()` - Start monitoring client\n- `stop_pod_hub()` - Stop monitoring client\n\n**Live Data Logging**\n- `livedata_log(tag: str, level: str, message: str, exception: Exception = None)` - Log application events\n- `livedata_page()` - Get current live data page\n- `livedata_setlimit(tag: str, limit: int)` - Set log retention limit\n\n**Instance Management**\n- `set_instance_status(status: str)` - Update instance status\n- `get_instance_status() -> str` - Get current instance status\n\n**System Information**\n- `get_pip_packages()` - Get installed Python packages\n- `get_logger_list()` - Get available loggers\n\n**Performance Monitoring**\n- `codepoint_log(point: str, message: str)` - Log performance checkpoint\n- `codepoints_get_tree()` - Get performance data tree\n- `codepoints_get_list()` - Get performance data list\n\n### Server Monitoring\n\n**PodHub Server Classes**\n- `PodHubApplication` - Main monitoring application\n- `PodHubInfo` - Information management\n- `PodHubData` - Data storage and retrieval\n\n**Server Functions**\n- `register_endpoints(app)` - Register monitoring endpoints\n- `get_app_pips(app_name: str)` - Get application packages\n- `get_live_services()` - Get live service list\n- `ai_get_app(query: str)` - AI-powered app information\n- `get_app_instances(app_name: str)` - Get application instances\n\n### Memory Monitoring\n\n- `start_memory_watch()` - Start memory monitoring\n- `stop_memory_watch()` - Stop memory monitoring  \n- `add_threshold(threshold: int, callback: Callable)` - Add memory threshold\n- `get_memory_usage() -> MemoryUsage` - Get current memory usage\n- `hist_memory_max()` - Get historical memory maximum\n\n### Thread Database\n\n- `get_thread_record(thread_id: str)` - Get thread information\n- `get_live_threads()` - Get active threads\n- `save_thread_data(data: Dict)` - Save thread correlation data\n- `get_thread_data(thread_id: str)` - Retrieve thread data\n\n### Example\n\n```python\nfrom dcnr_spring.monitor.client import (\n    set_application_name, start_pod_hub, livedata_log, \n    set_instance_status, codepoint_log\n)\n\n# Setup monitoring\nset_application_name(\"my-app\")\nstart_pod_hub()\n\n# Log events\nlivedata_log(\"app\", \"INFO\", \"Application started\")\nset_instance_status(\"running\")\n\n# Performance monitoring\ncodepoint_log(\"startup\", \"Application initialization complete\")\n```\n\n## spring.notifications\n\nEvent notification and messaging system with thread-safe operations.\n\n### Notification Center\n\n**`send(message: str, category: str = None, **kwargs)`**\n- Send notification to registered handlers\n- `message`: Notification message\n- `category`: Optional message category\n- `**kwargs`: Additional message data\n\n**`register(handler: Callable, category: str = None)`**\n- Register notification handler\n- `handler`: Function to handle notifications\n- `category`: Optional category filter\n\n**`unregister(handler: Callable, category: str = None)`**\n- Unregister notification handler\n\n### Service Management\n\n**`shutdown_service()`**\n- Initiate graceful service shutdown\n- Sends shutdown notifications to registered handlers\n\n**`is_shutting_down() -> bool`**\n- Check if service shutdown is in progress\n\n### Test Mode\n\n**`set_test_mode(enabled: bool)`**\n- Enable/disable test mode\n- Affects shutdown behavior and logging\n\n**`get_test_mode() -> bool`**\n- Check if test mode is enabled\n\n### Thread-Safe Utilities\n\n**`LockedValue[T]`**\n- Thread-safe value container\n- Provides atomic read/write operations with locking\n\n### Example\n\n```python\nfrom dcnr_spring.notifications import send, register, shutdown_service\n\ndef error_handler(message, category=None, **kwargs):\n    print(f\"Error: {message}\")\n\ndef info_handler(message, category=None, **kwargs):\n    print(f\"Info: {message}\")\n\n# Register handlers\nregister(error_handler, \"error\")\nregister(info_handler, \"info\")\n\n# Send notifications\nsend(\"Application started\", \"info\")\nsend(\"Database connection failed\", \"error\", details={\"host\": \"localhost\"})\n\n# Graceful shutdown\nshutdown_service()\n```\n\n## spring.requests\n\nRequest handling and message service utilities.\n\n### Request Logging\n\n**`StreamLogger`**\n- Logger that writes to string stream\n- Useful for capturing log output in memory\n\n### Message Services\n\n**`MessageServiceClient`**\n- Base class for message service implementations\n- Provides common patterns for request/response handling\n\n**`EmptyMessageService`**\n- No-op implementation for testing\n- Safe fallback when no real service is available\n\n### Request Counting\n\n**`@message_counter(name: str = None)`**\n- Decorator for counting method calls\n- `name`: Optional counter name (defaults to method name)\n\n**`counter.get_count(name: str) -> int`**\n- Get current count for named counter\n\n**`counter.wait_for_empty(name: str, timeout: float = None) -> bool`**\n- Wait for counter to reach zero\n- Useful for ensuring all requests are processed\n\n### Example\n\n```python\nfrom dcnr_spring.requests import StreamLogger, message_counter, counter\n\n# Stream logging\nlogger = StreamLogger()\nlogger.info(\"Test message\")\noutput = logger.getvalue()\n\n# Request counting\n@message_counter(\"api_calls\")\ndef handle_request():\n    # Process request\n    pass\n\n# Check counts\ncurrent_count = counter.get_count(\"api_calls\")\ncounter.wait_for_empty(\"api_calls\", timeout=30.0)\n```\n\n## spring.security\n\nSecurity utilities and encryption functions.\n\n### Encryption\n\n**`ciphering.cipher(data: str, key: str) -> str`**\n- Encrypt data using XOR cipher\n- `data`: String to encrypt\n- `key`: Encryption key\n- Returns: Encrypted string\n\n**`ciphering.decipher(encrypted: str, key: str) -> str`**\n- Decrypt data using XOR cipher\n- `encrypted`: Encrypted string\n- `key`: Decryption key (must match encryption key)\n- Returns: Decrypted string\n\n### Example\n\n```python\nfrom dcnr_spring.security.ciphering import cipher, decipher\n\n# Encrypt sensitive data\nsecret = \"sensitive information\"\nkey = \"my-secret-key\"\nencrypted = cipher(secret, key)\n\n# Decrypt when needed\ndecrypted = decipher(encrypted, key)\nassert decrypted == secret\n```\n\n## spring.subprocess\n\nProcess management and subprocess utilities.\n\n### Process Arguments\n\n**`SubprocessArguments`**\n- Container for subprocess arguments\n- Handles serialization of complex data types\n\n### Process Communication\n\n**`SubprocessPickleRunner`**\n- Executes functions in subprocess using pickle serialization\n- Handles bidirectional communication\n\n**`SubprocessPickle`**\n- Manages pickle-based subprocess communication\n- Provides high-level interface for process management\n\n### Process Results\n\n**`SubprocessResult`**\n- Container for subprocess execution results\n- Includes return value, stdout, stderr, and exit code\n\n### Environment Detection\n\n**`is_subprocess() -> bool`**\n- Detect if current process is a subprocess\n- Uses environment variable `SUBPROCESS_ENV_NAME`\n\n**`SUBPROCESS_ENV_NAME = \"DCNR_SPRING_SUBPROCESS\"`**\n- Environment variable name used for subprocess detection\n\n### Example\n\n```python\nfrom dcnr_spring.subprocess import SubprocessPickleRunner, is_subprocess\n\ndef worker_function(data):\n    # Process data in subprocess\n    return data * 2\n\nif not is_subprocess():\n    runner = SubprocessPickleRunner()\n    result = runner.execute(worker_function, args=[5])\n    print(result.return_value)  # 10\n```\n\n## spring.utils\n\nGeneral utilities and helper classes.\n\n### Thread-Safe Counter\n\n**`SafeCounter`**\n- Thread-safe counter implementation\n- Supports increment, decrement, and atomic operations\n- Methods:\n  - `increment() -> int` - Increment and return new value\n  - `decrement() -> int` - Decrement and return new value\n  - `get() -> int` - Get current value\n  - `set(value: int)` - Set value\n  - `reset()` - Reset to zero\n\n### Application Lifecycle\n\n**`waitloop_start()`**\n- Initialize application wait loop\n- Used for graceful application lifecycle management\n\n**`waitloop_is_at_exit() -> bool`**\n- Check if application is in exit state\n- Returns True when shutdown has been initiated\n\n### File System Utilities\n\n**`WorkingFileSpace`**\n- Context manager for temporary directory management\n- Automatically creates and cleans up working directories\n- Methods:\n  - `get_file_name(filename: str) -> str` - Get full path for file\n  - `mkdir(dirname: str) -> str` - Create subdirectory\n  - `exists(path: str) -> bool` - Check if path exists\n  - `cleanup()` - Manual cleanup (automatic on exit)\n\n### Example\n\n```python\nfrom dcnr_spring.utils import SafeCounter, WorkingFileSpace, waitloop_start\n\n# Thread-safe counting\ncounter = SafeCounter()\ncounter.increment()  # Returns 1\ncurrent = counter.get()  # Returns 1\n\n# Temporary workspace\nwith WorkingFileSpace(dirname=\"temp_work\") as ws:\n    file_path = ws.get_file_name(\"data.txt\")\n    subdir = ws.mkdir(\"subdirectory\")\n    # Directory automatically cleaned up on exit\n\n# Application lifecycle\nwaitloop_start()\n```\n\n## Error Handling and Best Practices\n\n### Exception Handling\nAll modules provide appropriate exception handling and error propagation. Use try-catch blocks for operations that may fail.\n\n### Thread Safety\nComponents marked as thread-safe (SafeCounter, LockedValue, notification system) can be safely used in multi-threaded applications.\n\n### Resource Management\nUse context managers (WorkingFileSpace) and proper cleanup patterns. The package provides automatic resource management where possible.\n\n### Testing\nAll modules include test mode support and utilities for unit testing. Use the test utilities in `dcnr_spring.notifications.testmode` for testing scenarios.\n\n## Integration Examples\n\n### Complete Application Setup\n\n```python\nfrom dcnr_spring.actuator import register_actuator_component, STATUS_OK\nfrom dcnr_spring.database.memory import MemoryDatabase\nfrom dcnr_spring.database import DatabaseEntity, dbtable, dbfield\nfrom dcnr_spring.monitor.client import set_application_name, start_pod_hub\nfrom dcnr_spring.notifications import register, send\n\n# Database setup\n@dbtable(\"app\", \"users\")\nclass User(DatabaseEntity):\n    name: str = dbfield()\n    email: str = dbfield()\n\ndb = MemoryDatabase()\n\n# Health monitoring\ndef db_health():\n    return STATUS_OK if db else STATUS_FAIL\n\nregister_actuator_component(\"database\", db_health)\n\n# Application monitoring\nset_application_name(\"my-application\")\nstart_pod_hub()\n\n# Event handling\ndef audit_handler(message, **kwargs):\n    print(f\"Audit: {message}\")\n\nregister(audit_handler, \"audit\")\n\n# Application ready\nsend(\"Application initialized\", \"audit\")\n```\n\nThis comprehensive API provides everything needed to build robust, monitorable, and maintainable Python applications following enterprise patterns.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Scheduling python functions for execution.",
    "version": "1.0.2",
    "project_urls": {
        "Homepage": "https://dcnr-utilities.com"
    },
    "split_keywords": [
        "python",
        " scheduler"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "bcfca48d1a15f3023dbce345c5fc2b76662b4baf7b43ff9ea85ac6c3a1a145b6",
                "md5": "1263b0d00363ae552d16e8cfec2c69af",
                "sha256": "a24bb26d74c92bd7818543395addddb360f2e99e30f07e93ce03f47011d5012e"
            },
            "downloads": -1,
            "filename": "dcnr_spring-1.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1263b0d00363ae552d16e8cfec2c69af",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 67861,
            "upload_time": "2025-10-09T12:13:10",
            "upload_time_iso_8601": "2025-10-09T12:13:10.334656Z",
            "url": "https://files.pythonhosted.org/packages/bc/fc/a48d1a15f3023dbce345c5fc2b76662b4baf7b43ff9ea85ac6c3a1a145b6/dcnr_spring-1.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "cd788eb8b92b72f565d245c2edf46f824f13fd862607f6873fc095c9def33de0",
                "md5": "1f6bf8ac9573a6c51e81993f5379371b",
                "sha256": "1f22a3a6a919c390293fbad6d43c344e7db16b9e8a95e864cde714f0ce386154"
            },
            "downloads": -1,
            "filename": "dcnr_spring-1.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "1f6bf8ac9573a6c51e81993f5379371b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 79008,
            "upload_time": "2025-10-09T12:13:11",
            "upload_time_iso_8601": "2025-10-09T12:13:11.892089Z",
            "url": "https://files.pythonhosted.org/packages/cd/78/8eb8b92b72f565d245c2edf46f824f13fd862607f6873fc095c9def33de0/dcnr_spring-1.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-09 12:13:11",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "dcnr-spring"
}
        
Elapsed time: 2.38428s