socketflow 1.0.0
An asynchronous networking library for Python with advanced features
License: MIT
Requires Python: >=3.8
Keywords: networking, tcp, socket, server, client, async, asyncio, websocket, real-time, messaging, clustering, ssl, tls, encryption, compression, middleware, events, blueprint, failover, load-balancing, redis, distributed

# SocketFlow

[![PyPI version](https://badge.fury.io/py/socketflow.svg)](https://badge.fury.io/py/socketflow)
[![Python Support](https://img.shields.io/pypi/pyversions/socketflow.svg)](https://pypi.org/project/socketflow/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Build Status](https://github.com/socketflow/socketflow/workflows/CI/badge.svg)](https://github.com/socketflow/socketflow/actions)

**SocketFlow** is a comprehensive asynchronous networking library for Python that provides both server and client functionality with advanced features like clustering, compression, middleware, event handling, SSL/TLS encryption, and more.

## 🚀 Features

- **🔒 SSL/TLS Encryption** - Secure communication with both self-signed and CA-signed certificates
- **🌐 Clustering Support** - Multi-server clustering with Redis or local file storage
- **📦 Compression** - Multiple compression algorithms (zlib, gzip, bz2, lzma, zstandard, brotli)
- **🔄 Failover & Load Balancing** - Automatic failover and load balancing strategies
- **📡 Event System** - Comprehensive event handling with custom events
- **🛡️ Middleware Support** - Global and path-specific middleware
- **📋 Blueprint System** - Flask-like blueprint organization for routes and handlers
- **📊 Connection Pooling** - Efficient connection management with pooling
- **🔍 Configuration Validation** - Comprehensive parameter validation with fail-fast approach
- **📝 Logging System** - Configurable logging with color support and file output
- **⚡ High Performance** - Built on asyncio for high-performance async operations

## 📦 Installation

### Installation

```bash
pip install socketflow
```

This installs SocketFlow with all core features including:
- SSL/TLS encryption support
- Redis clustering support  
- Advanced compression (zlib, gzip, bz2, lzma, zstandard, brotli)
- Cross-platform colored logging

## 🎯 Quick Start

### Basic Server

```python
import asyncio
from socketflow import SocketFlowServer, EventType, LogLevel

# Create server
server = SocketFlowServer(
    host='localhost',
    port=8080,
    log_level=LogLevel.INFO
)

# Add path handlers
@server.path('/api/status')
async def status_handler(event_data):
    return {"status": "healthy", "version": "1.0.0"}

@server.path('/api/users/<user_id>')
async def get_user(event_data, user_id):
    return {"user_id": user_id, "name": "John Doe"}

# Add event handlers
@server.event(EventType.Server.CLIENT_CONNECTED)
async def on_client_connected(event_data):
    print(f"Client connected: {event_data.client_addr}")

# Start server
async def main():
    await server.start_server()

if __name__ == "__main__":
    asyncio.run(main())
```

### Basic Client

```python
import asyncio
from socketflow import SocketFlowClient, EventType, LogLevel

# Create client
client = SocketFlowClient(
    host='localhost',
    port=8080,
    log_level=LogLevel.INFO
)

# Add path handlers
@client.path('/api/status')
async def on_status(event_data):
    print(f"Server status: {event_data.data}")

# Add event handlers
@client.event(EventType.Client.CONNECTED)
async def on_connected(event_data):
    print("Connected to server!")

# Connect and send messages
async def main():
    await client.connect()
    
    # Send messages
    await client.send_message("Hello from client!")
    await client.send_message("Get status", path="/api/status")
    
    # Keep running
    await client.run_forever()

if __name__ == "__main__":
    asyncio.run(main())
```

### SSL/TLS Server

```python
from socketflow import SocketFlowServer, LogLevel

# SSL server with auto-generated certificates
server = SocketFlowServer(
    host='localhost',
    port=8080,
    ssl_enabled=True,
    ssl_auto_generate=True,  # Auto-generates self-signed certificate
    log_level=LogLevel.INFO
)

@server.path('/secure')
async def secure_handler(event_data):
    return {"message": "This is a secure connection!", "encrypted": True}

await server.start_server()
```

### SSL/TLS Client

```python
import ssl
from socketflow import SocketFlowClient, LogLevel

# SSL client
client = SocketFlowClient(
    host='localhost',
    port=8080,
    ssl_enabled=True,
    ssl_verify_mode=ssl.CERT_NONE,  # For self-signed certificates
    log_level=LogLevel.INFO
)

await client.connect()
```

### Clustering

```python
from socketflow import SocketFlowServer, LogLevel

# Clustered server
server = SocketFlowServer(
    port=8080,
    enable_cluster=True,
    cluster_storage_type='redis',
    cluster_storage_path='redis://localhost:6379',
    node_id='node-1',
    load_balancing_strategy='round-robin',
    log_level=LogLevel.INFO
)

await server.start_server()
```

### Blueprint System

```python
from socketflow import SocketFlowServer, Blueprint, EventType

# Create blueprint
api_bp = Blueprint('api')

@api_bp.path('/users')
async def list_users(event_data):
    return {"users": ["john", "jane", "bob"]}

@api_bp.path('/users/<user_id>')
async def get_user(event_data, user_id):
    return {"user_id": user_id, "name": "John Doe"}

# Register blueprint
server = SocketFlowServer(port=8080)
server.register_blueprint(api_bp, url_prefix='/api/v1')
# Routes become: /api/v1/users, /api/v1/users/<user_id>

await server.start_server()
```

## 📚 Documentation

- [Complete Feature Documentation](features.md)
- [API Reference](https://socketflow.readthedocs.io/)
- [Examples](examples/)

## 🔧 Configuration

SocketFlow supports extensive configuration options:

### Server Configuration

```python
server = SocketFlowServer(
    host='0.0.0.0',                    # Server host
    port=8080,                        # Server port
    buffer_size=65536,                # Buffer size
    keepalive_interval=5.0,           # Keepalive ping interval
    keepalive_timeout=10.0,           # Keepalive timeout
    keepalive_max_missed=3,           # Max missed pongs before disconnect
    compression_type='zlib',          # Compression algorithm
    compression_level=6,              # Compression level (1-9)
    compression_min_size=1024,        # Minimum size to compress
    enable_pool=True,                 # Enable connection pooling
    pool_size=100,                    # Max connections in pool
    pool_idle_timeout=300,            # Idle connection timeout
    enable_cluster=True,              # Enable clustering
    cluster_storage_type='redis',     # 'redis' or 'local'
    cluster_storage_path='redis://localhost:6379',
    node_id='server-1',               # Unique node identifier
    load_balancing_strategy='round-robin',
    ssl_enabled=True,                 # Enable SSL/TLS
    ssl_certfile='./certs/server.pem',
    ssl_keyfile='./certs/server.key',
    ssl_auto_generate=True,           # Auto-generate certificates
    log_level=LogLevel.INFO           # Logging level
)
```

### Client Configuration

```python
client = SocketFlowClient(
    host='localhost',                 # Server host
    port=8080,                        # Server port
    buffer_size=65536,                # Buffer size
    keepalive_interval=30.0,          # Keepalive ping interval
    keepalive_timeout=10.0,           # Keepalive timeout
    keepalive_max_missed=3,           # Max missed pongs before disconnect
    compression_type='zlib',          # Compression algorithm
    compression_level=6,              # Compression level (1-9)
    compression_min_size=1024,       # Minimum size to compress
    enable_failover=True,             # Enable failover
    fallback_nodes=[                  # Fallback servers
        ('backup1', 8080),
        ('backup2', 8080)
    ],
    ssl_enabled=True,                 # Enable SSL/TLS
    ssl_certfile='./certs/client.pem',
    ssl_keyfile='./certs/client.key',
    ssl_ca_certs='./certs/ca.pem',
    ssl_verify_mode=ssl.CERT_REQUIRED,
    log_level=LogLevel.INFO           # Logging level
)
```

## 🧪 Testing

```bash
# Run tests
pytest

# Run with coverage
pytest --cov=socketflow

# Run specific test categories
pytest -m unit
pytest -m integration
pytest -m "not slow"
```

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- Built on Python's `asyncio` framework
- Inspired by modern web frameworks like Flask and FastAPI
- Uses industry-standard libraries for SSL/TLS and compression

## 📞 Support

- 📧 Email: contact@socketflow.dev
- 🐛 Issues: [GitHub Issues](https://github.com/socketflow/socketflow/issues)
- 📖 Documentation: [Read the Docs](https://socketflow.readthedocs.io/)
- 💬 Discussions: [GitHub Discussions](https://github.com/socketflow/socketflow/discussions)

---

**SocketFlow** - Making async networking simple, secure, and scalable! 🚀