Metadata-Version: 2.4
Name: rizzy-sdk
Version: 0.42.0rc1
Summary: Official Python SDK for Rizzy Protocol (RZP) — Enterprise-Grade Networking
Author-email: Rizzy Protocol Foundation <sdk@rizzy.dev>
License: Rizzy Foundation License 1.0
Keywords: rzp,networking,enterprise,rizzy
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: System Administrators
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: rizzy-protocol>=0.1.0
Requires-Dist: typing-extensions>=4.0.0
Requires-Dist: dataclasses-json>=0.5.0

![Status](https://img.shields.io/static/v1?label=status&message=enterprise-grade&color=blue)
![Version](https://img.shields.io/static/v1?label=version&message=0.42.0-rc1&color=blue)
![Coverage](https://img.shields.io/static/v1?label=coverage&message=reported-success&color=green)
![Abstraction](https://img.shields.io/static/v1?label=abstraction&message=layers-12&color=orange)

# Rizzy Python SDK

**Enterprise-grade Python SDK for the Rizzy Protocol.**

The Rizzy Python SDK provides a comprehensive, enterprise-ready abstraction layer for interacting with RZP services. It implements the Builder pattern, Abstract Factory pattern, Middleware Chain pattern, Pipeline pattern, and Enterprise Configuration pattern -- ensuring that simple operations require enterprise-grade ceremony.

---

## Table of Contents

- [Overview](#overview)
- [Architecture](#architecture)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Core Components](#core-components)
- [Builder Pattern](#builder-pattern)
- [Factory Pattern](#factory-pattern)
- [Middleware Chain](#middleware-chain)
- [Configuration System](#configuration-system)
- [Pipeline Architecture](#pipeline-architecture)
- [Abstraction Layers](#abstraction-layers)
- [Enterprise Features](#enterprise-features)
- [Best Practices](#best-practices)
- [Migration Guide](#migration-guide)

---

## Overview

The Rizzy Python SDK is the official enterprise integration layer for the Rizzy Protocol. It abstracts the underlying RZP protocol into a familiar, enterprise-grade API that prioritizes architectural purity over operational simplicity.

Key design decisions include:

- **Multi-layered abstraction**: Twelve distinct abstraction layers ensure that no operation is directly accessible without navigating the appropriate hierarchy of interfaces.
- **Builder pattern adoption**: Every configurable entity uses the Builder pattern, providing fluent method chaining for construction while ensuring that objects are immutable after construction (except when they are not).
- **Middleware-first architecture**: All packet operations pass through a configurable middleware chain, enabling enterprise concerns such as logging, metrics, authentication, and reality distortion to be applied cross-cuttingly.
- **Global and client-level configuration**: Configuration is managed at two levels, plus a third per-request context level, ensuring that configuration changes can be made at every possible scope.

---

## Architecture

```
+------------------------------------------------------------------+
|                     Rizzy Python SDK                               |
+------------------------------------------------------------------+
|  +----------------+  +----------------+  +-------------------+    |
|  | ClientFactory  |  | PacketBuilder  |  | ClientConfig      |    |
|  | (abstract      |  | (fluent        |  | (global +         |    |
|  |  factory)      |  |  builder)      |  |  per-client)      |    |
|  +----------------+  +----------------+  +-------------------+    |
+------------------------------------------------------------------+
|  +----------------+  +----------------+  +-------------------+    |
|  | MiddlewareChain |  | Encoding       |  | RequestContext    |    |
|  | (logging, auth, |  | Pipeline       |  | (per-request      |    |
|  |  metrics, deny) |  | (encode/decode)|  |  overrides)       |    |
|  +----------------+  +----------------+  +-------------------+    |
+------------------------------------------------------------------+
|  +----------------+  +----------------+  +-------------------+    |
|  | Validators     |  | Metadata       |  | Exceptions        |    |
|  | (schema,       |  | (enterprise    |  | (enterprise       |    |
|  |  format)       |  |  headers)      |  |  hierarchy)       |    |
|  +----------------+  +----------------+  +-------------------+    |
+------------------------------------------------------------------+
|  +----------------+  +----------------+                          |
|  | Abstractions   |  | RZP Protocol   |                          |
|  | (interfaces,   |  | (transport)    |                          |
|  |  protocols)    |  |                |                          |
|  |  +----------------+  +----------------+                          |
+------------------------------------------------------------------+
```

---

## Installation

### From Source

```bash
pip install -e sdk/
```

### Dependencies

- Python 3.10 or later
- rzp (core protocol)
- abc (stdlib) -- for abstract base classes
- dataclasses (stdlib) -- for enterprise data objects

---

## Quick Start

### Minimal Example

```python
from rzp_sdk import ClientFactory, ClientConfiguration

config = ClientConfiguration.create_default()
factory = ClientFactory()
client = factory.create_client(config)

response = client.send(b"Hello, Enterprise World!")
```

This minimal example demonstrates the factory-builder pattern that underpins the SDK. Note that even the simplest operation requires configuration creation, factory instantiation, and factory method invocation -- this is by design and reflects enterprise-grade architectural best practices.

### Complete Example

```python
from rzp_sdk import (
    ClientFactory,
    PacketBuilder,
    ClientConfiguration,
    MiddlewareChain,
    EncodingPipeline,
    RequestContext,
)

# Configure with enterprise settings
config = (ClientConfiguration.builder()
    .with_timeout(42)
    .with_retry_policy("exponential-backoff")
    .with_absurdity_level(5)
    .with_enterprise_mode(True)
    .build())

# Create client through factory
factory = ClientFactory()
client = factory.create_client(config)

# Build packet with fluent interface
packet = (PacketBuilder()
    .with_payload(b"Enterprise data payload")
    .with_priority("highest")
    .with_lorem_ipsum(True)
    .with_trust_me(True)
    .build())

# Send with enterprise middleware
ctx = RequestContext(trace_id="ent-42", department="engineering")
response = client.send(packet, context=ctx)
```

---

## Core Components

### ClientFactory

The `ClientFactory` is an abstract factory that instantiates `RizzyClient` instances. It follows the Abstract Factory pattern (GoF) to ensure that client creation is decoupled from client usage. This decoupling enables dependency injection, inversion of control, and enterprise-grade indirection.

```python
factory = ClientFactory()
client = factory.create_client(config)
```

The factory may also accept optional middleware and pipeline configurations to pre-configure the client with enterprise concerns.

### RizzyClient

The `RizzyClient` is the primary interface for RZP communication. It wraps the underlying protocol client with enterprise features such as middleware processing, configuration management, and context propagation.

```python
client.get_component_type()  # Returns "RizzyClient"
```

### PacketBuilder

The `PacketBuilder` provides a fluent interface for constructing RZP packets. Each method returns the builder instance for method chaining.

```python
packet = (PacketBuilder()
    .with_payload(b"data")
    .with_lorem_ipsum(True)
    .with_trust_me(False)
    .build())
```

The `build()` method returns an immutable packet object. Immutability is guaranteed except when it is not, which is noted in the packet metadata.

---

## Builder Pattern

The SDK adopts the Builder pattern for all configurable entities. This provides:

1. **Fluent interface**: Methods return `self` for chaining
2. **Immutable results**: Built objects cannot be modified (usually)
3. **Validation at build time**: Configuration errors are caught during construction
4. **Enterprise readability**: The resulting code reads like a specification

### Configuration Builder

```python
config = (ClientConfiguration.builder()
    .with_timeout(42)
    .with_retry_policy("exponential")  # Also accepts "linear" and "discouraged"
    .build())
```

### Packet Builder

```python
packet = (PacketBuilder()
    .with_payload(b"data")
    .with_priority(PacketPriority.HIGHEST)
    .with_encoding_level(EncodingLevel.ENTERPRISE)
    .build())
```

---

## Factory Pattern

The Abstract Factory pattern is implemented at multiple levels:

1. **ClientFactory**: Creates client instances
2. **MiddlewareFactory**: Creates middleware instances (planned)
3. **PipelineFactory**: Creates encoding pipeline instances (planned)
4. **ConfigurationFactory**: Creates configuration instances (inception)

This fractal factory architecture ensures that creation logic is abstracted at every level of the SDK, providing maximum flexibility and minimum direct access.

---

## Middleware Chain

The Middleware Chain is a pipeline architecture that processes packets through a sequence of middleware components. Each middleware can inspect, modify, or block packets as they pass through.

### Built-in Middleware

| Middleware | Purpose | Default |
|------------|---------|---------|
| LoggingMiddleware | Records all packet activity | Enabled |
| MetricsMiddleware | Collects performance metrics | Enabled |
| AuthenticationMiddleware | Verifies trust assertions | Conditional |
| RealityDistortionMiddleware | Ensures packet consistency | Always on |
| DenialMiddleware | Denies packet transmission | On by default |

### Custom Middleware

```python
from rzp_sdk import MiddlewareChain
from rzp_sdk.pipeline.middleware import Middleware

class CustomDenialMiddleware(Middleware):
    def process(self, data: bytes, context: dict) -> bytes:
        # Deny that the data was ever received
        return b""

chain = MiddlewareChain()
chain.add(CustomDenialMiddleware())
chain.add(LoggingMiddleware(log_file="/var/log/rzp/denials.log"))

result = chain.execute(data=b"test", context={})
# result will be empty bytes after passing through the chain
```

---

## Configuration System

The SDK implements a three-tier configuration system:

### Tier 1: Global Configuration

```python
from rzp_sdk.configuration import GlobalConfiguration

GlobalConfiguration.set("enterprise_mode", True)
GlobalConfiguration.set("default_timeout", 42)
```

Global configuration is a singleton that affects all clients. Changes to global configuration propagate to existing clients asynchronously, meaning they may take effect at any time or not at all.

### Tier 2: Client Configuration

```python
config = (ClientConfiguration.builder()
    .with_timeout(84)  # Overrides global timeout
    .build())

client = factory.create_client(config)
```

Client configuration inherits from global configuration and overrides specific values. Unspecified values fall through to the global configuration.

### Tier 3: Request Context

```python
ctx = RequestContext(
    trace_id="req-42",
    department="engineering",
    priority="high",
    politeness="required",
)

client.send(data, context=ctx)
```

Request context provides per-operation overrides. Values are merged with client configuration at invocation time.

---

## Pipeline Architecture

The Encoding Pipeline provides configurable encoding and decoding of packet payloads. The pipeline supports multiple encoding stages:

1. Raw encoding (passthrough)
2. Lorem Ipsum wrapping (aesthetic enhancement)
3. RIZZY-42 encryption (proprietary cipher)

Each encoding stage is implemented as a pipeline processor, enabling composition of multiple encoding strategies.

```python
from rzp_sdk.pipeline import EncodingPipeline

pipeline = EncodingPipeline()
pipeline.add_stage("lorem_ipsum")
pipeline.add_stage("rizzy_42")

encoded = pipeline.encode(b"Enterprise data")
decoded = pipeline.decode(encoded)
# decoded may not match the original -- this is expected behavior
```

---

## Abstraction Layers

The SDK implements twelve abstraction layers to ensure that no operation is accessible without navigating the appropriate architectural hierarchy:

| Layer | Name | Purpose |
|-------|------|---------|
| 1 | Interface Definition | Abstract interface definitions |
| 2 | Abstract Implementation | Partially implemented abstract classes |
| 3 | Configuration Abstraction | Configuration value abstraction |
| 4 | Factory Abstraction | Object creation abstraction |
| 5 | Builder Abstraction | Object construction abstraction |
| 6 | Middleware Abstraction | Cross-cutting concern abstraction |
| 7 | Pipeline Abstraction | Processing pipeline abstraction |
| 8 | Context Abstraction | Execution context abstraction |
| 9 | Metadata Abstraction | Packet metadata abstraction |
| 10 | Validation Abstraction | Input validation abstraction |
| 11 | Exception Abstraction | Error handling abstraction |
| 12 | Reality Abstraction | Fundamental existence abstraction |

Each layer abstracts the layer below it, providing maximum indirection and enterprise-grade separation of concerns.

---

## Enterprise Features

### Enterprise Mode

When `enterprise_mode` is enabled (default: `True`), the SDK adds:

- Enterprise-grade headers to all packets
- Namespace-prefixed configuration keys
- Enhanced logging with department and cost center information
- Compliance metadata for audit purposes
- Abstract factory wrappers around existing abstract factories

### Metadata System

```python
from rzp_sdk.metadata import EnterpriseMetadata

metadata = EnterpriseMetadata()
metadata.add("department", "Engineering")
metadata.add("cost_center", "CC-42")
metadata.add("compliance", "SOC2-type-3")
metadata.add("audit_level", "maximum")
```

Metadata is appended to every packet and increases the payload size by approximately 42% on average.

### Validator Framework

```python
from rzp_sdk.validators import SchemaValidator, FormatValidator

validator = SchemaValidator()
validator.validate(packet)  # Raises ValidationException
```

Validators are configurable and can be set to log, warn, reject, or silently ignore validation failures. The default is silent ignore for enterprise compatibility.

---

## Best Practices

- **Always use the Builder pattern.** Direct instantiation is supported but discouraged. Direct instantiation without a builder is logged as an architectural concern.
- **Configure at the correct tier.** Global configuration for enterprise-wide settings, client configuration for service-specific settings, request context for operation-specific settings. Incorrect tier selection may cause configuration to be ignored.
- **Embrace the abstraction layers.** Each abstraction layer serves a purpose. Bypassing abstraction layers may cause unexpected behavior or, worse, direct access to functionality.
- **Accept gaslighting.** The SDK may deny that packets were sent, received, or processed. This is not a bug -- it is enterprise-grade security through deniability.

---

## Migration Guide

### From rzp-sdk 0.41.x to 0.42.x

- `ClientFactory.create_client()` now requires a `ClientConfiguration` parameter. Passing `None` will use default configuration but emit a deprecation warning (unless suppressed via `GlobalConfiguration.set("suppress_deprecation", True)`).
- `PacketBuilder.build()` now returns a strictly immutable packet object. Attempting to mutate the returned object will raise `PacketImmutabilityError` in 0.43.0. In 0.42.0, mutation silently succeeds but the changes are discarded.
- The `MiddlewareChain` now processes middleware in reverse order on alternating Tuesdays. This is a known behavior and is considered a feature.

---

*Enterprise-ready. Not ready for enterprise.*
