Metadata-Version: 2.5
Name: cc-platform-sdk
Version: 2.0.0
Summary: Conscious Clouds Platform SDK for Python
License: Apache-2.0
License-File: LICENSE
Requires-Python: >=3.11
Requires-Dist: email-validator<3.0.0,>=2.0.0
Requires-Dist: httpx<1.0.0,>=0.27.0
Requires-Dist: prometheus-client<1.0.0,>=0.20.0
Requires-Dist: pydantic-settings<3.0.0,>=2.0.0
Requires-Dist: pydantic<3.0.0,>=2.0.0
Requires-Dist: pyjwt[crypto]<3.0.0,>=2.8.0
Requires-Dist: redis[hiredis]<6.0.0,>=5.0.0
Requires-Dist: structlog<25.0.0,>=23.2.0
Provides-Extra: all
Requires-Dist: aiokafka<1.0.0,>=0.10.0; extra == 'all'
Requires-Dist: grpcio-health-checking<2.0.0,>=1.60.0; extra == 'all'
Requires-Dist: grpcio-reflection<2.0.0,>=1.60.0; extra == 'all'
Requires-Dist: grpcio<2.0.0,>=1.60.0; extra == 'all'
Requires-Dist: jsonschema<5.0.0,>=4.0.0; extra == 'all'
Requires-Dist: opentelemetry-api<2.0.0,>=1.27.0; extra == 'all'
Requires-Dist: opentelemetry-exporter-otlp<2.0.0,>=1.27.0; extra == 'all'
Requires-Dist: opentelemetry-sdk<2.0.0,>=1.27.0; extra == 'all'
Requires-Dist: pytest-asyncio<1.0.0,>=0.23.0; extra == 'all'
Requires-Dist: pytest<9.0.0,>=8.0.0; extra == 'all'
Requires-Dist: starlette<1.0.0,>=0.27.0; extra == 'all'
Provides-Extra: grpc
Requires-Dist: grpcio-health-checking<2.0.0,>=1.60.0; extra == 'grpc'
Requires-Dist: grpcio-reflection<2.0.0,>=1.60.0; extra == 'grpc'
Requires-Dist: grpcio<2.0.0,>=1.60.0; extra == 'grpc'
Provides-Extra: kafka
Requires-Dist: aiokafka<1.0.0,>=0.10.0; extra == 'kafka'
Provides-Extra: test
Requires-Dist: jsonschema<5.0.0,>=4.0.0; extra == 'test'
Requires-Dist: pytest-asyncio<1.0.0,>=0.23.0; extra == 'test'
Requires-Dist: pytest<9.0.0,>=8.0.0; extra == 'test'
Provides-Extra: tracing
Requires-Dist: opentelemetry-api<2.0.0,>=1.27.0; extra == 'tracing'
Requires-Dist: opentelemetry-exporter-otlp<2.0.0,>=1.27.0; extra == 'tracing'
Requires-Dist: opentelemetry-sdk<2.0.0,>=1.27.0; extra == 'tracing'
Provides-Extra: web
Requires-Dist: starlette<1.0.0,>=0.27.0; extra == 'web'
Description-Content-Type: text/markdown

# cc-platform-sdk -- Conscious Clouds Platform SDK for Python

A framework-agnostic SDK providing standardized patterns for microservice
development: error handling, protocol envelopes, observability, authentication,
transport, and infrastructure utilities.

This SDK contains zero product-specific references. Products extend it with
their own defaults, event catalogs, and framework plugins.

## Resource-v2 evidence conformance (local implementation; not published)

`cc_platform_sdk.auth` exports `sign_resource_v2`, `verify_resource_v2`,
`resource_input_digest`, `ResourceV2Verification`, and `ResourceEvidenceError`.
Legacy acting-user APIs and service transport adapters remain unchanged.
The conformance tests consume the frozen 42 envelope and six input cases in
`platform/contracts/auth/v2/resource-actor-cases.json`, with independently fixed
Go/Node canonical bytes, signatures, digests, and refusal codes.

Pass raw JSON as `str` or UTF-8 `bytes` (also accepts `bytearray`), never a parsed
dictionary. Duplicate decoded keys, malformed UTF-8, lone surrogates, U+FFFD,
nesting beyond 64 containers, non-finite numbers, and decimal values changed by
binary64 canonicalization are refused before signing or digesting. Canonical
serialization follows the certified Go exact profile, including UTF-16 key
ordering and ECMAScript number formatting. Exact decimal preservation does not
mean every input integer must fit the safe-integer range; envelope timestamps
and version additionally require safe integers.

`sign_resource_v2(raw_envelope, key_bytes)` returns immutable `encoded` and
`signature` fields (unpadded base64url and hexadecimal HMAC). Verification takes
those fields and a `ResourceV2Verification` with explicit Unix-seconds `now`,
`key_id`, `key`, independently authenticated `executor`, trusted
`initiator_issuers`, and `expected` binding. The binding contains `target`,
`capability_id`, `action`, `intent`, `input`, `execution`, and `receiver`, derived
from trusted receiver state, not copied from the presented evidence. Noncanonical
wire bytes are rejected, not repaired. Failures raise `ResourceEvidenceError`
whose `code` is the certified refusal code. The verified result exposes a
canonical-envelope `digest` and an `envelope()` method returning a fresh copy.

A valid signature proves provenance, not resource permission. Products must
validate/default input before `resource_input_digest(raw_input)`, execute that
same input, independently authenticate their peer, enforce replay protection,
and re-prove live authority before dispatch. This module provides no policy
engine, replay store, Access SDK decision API, or live execution integration.

## Installation

```bash
pip install cc-platform-sdk
```

With optional extras:

```bash
pip install cc-platform-sdk[grpc]      # gRPC transport support
pip install cc-platform-sdk[kafka]     # Kafka transport support
pip install cc-platform-sdk[tracing]   # OpenTelemetry tracing
pip install cc-platform-sdk[web]       # ASGI middleware (Starlette)
pip install cc-platform-sdk[all]       # All optional dependencies
```

## Requirements

- Python >= 3.11

## Quick Start

```python
from cc_platform_sdk.core.errors import ErrorCode, PlatformException, get_http_status
from cc_platform_sdk.core.config import BaseServiceSettings
from cc_platform_sdk.core.context import context_scope, get_correlation_id
from cc_platform_sdk.observability.logging import get_logger

# Configure service settings
class MySettings(BaseServiceSettings):
    database_url: str = "postgresql://localhost/mydb"

settings = MySettings(service_name="order-service", environment="dev")

# Use structured logging
logger = get_logger(__name__)
logger.info("service_starting", service=settings.service_name)

# Error handling with platform error codes
http_status = get_http_status(ErrorCode.RESOURCE_NOT_FOUND)  # 404

# Context propagation
with context_scope(correlation_id="req_abc123def456", tenant_id="t_acme"):
    cid = get_correlation_id()  # "req_abc123def456"
    logger.info("request_received", correlation_id=cid)
```

## Modules

| Module | Description |
|--------|-------------|
| `cc_platform_sdk.auth` | JWT/JWKS validation, SecurityIdentity (frozen dataclass, immutable), CredentialProvider protocol (runtime_checkable, outbound credential injection), acting-user HMAC signing and verification, auth middleware hooks (framework-agnostic) |
| `cc_platform_sdk.core.config` | BaseServiceSettings (Pydantic-based) with environment detection, StandardConfig model with timeouts, retry policy, transport, auth, and observability sections |
| `cc_platform_sdk.core.context` | RequestContext propagation via contextvars (correlation ID, trace ID, span ID, tenant, user, security identity, session, environment), context scope manager, ASGI middleware |
| `cc_platform_sdk.core.errors` | Error codes (50 codes, 10 categories), error catalog with HTTP/gRPC status mappings, typed exception hierarchy (PlatformException and 9 category subclasses), retryability classification |
| `cc_platform_sdk.core.feature_flags` | FeatureFlagProvider protocol, InMemoryFeatureFlagProvider, fail-closed semantics (unknown flags return false/default), EvaluationContext for targeting |
| `cc_platform_sdk.core.protocol` | Request/response envelopes, service tier definitions with retry configs, standard header propagation (correlation ID, trace ID, tenant ID, etc.) |
| `cc_platform_sdk.events` | Event envelope creation and validation, event type format enforcement |
| `cc_platform_sdk.infra.cache` | Async Redis cache helpers with connection pooling, JSON get/set, key deletion, health checks |
| `cc_platform_sdk.infra.ratelimit` | Rate limiting with sliding window algorithm, configurable rules, environment-based multipliers |
| `cc_platform_sdk.lifecycle` | Hook-based lifecycle management (asyncio): ordered startup, reverse-order shutdown, health aggregation, startup rollback, observer pattern with 7 event types |
| `cc_platform_sdk.observability` | Vendor-neutral observability interfaces (Logger, MetricsRecorder, Tracer, Span) with noop defaults, observability envelope, correlation propagation, diagnostics collector, instrumentation hooks |
| `cc_platform_sdk.observability.logging` | Structured logging via structlog (JSON format), correlation ID integration |
| `cc_platform_sdk.observability.metrics` | Prometheus metrics via MetricRegistry with auto-injected service/env labels, bounded cardinality helpers |
| `cc_platform_sdk.observability.tracing` | OpenTelemetry tracing with OTLP exporter, span management, function decorator |
| `cc_platform_sdk.transport.grpc` | gRPC server/client interceptors for context propagation, logging, metrics, and error handling; interceptor chain builders |
| `cc_platform_sdk.transport.http` | HTTP client (httpx-based) with circuit breaker, retry with lifecycle gate, retry classification (5 categories: retryable, non_retryable, rate_limited, transient, permanent) |
| `cc_platform_sdk.transport.kafka` | Kafka producer/consumer (aiokafka-based) with DLQ support, event envelope serialization, compression, configurable acks |
| `cc_platform_sdk.transport.serviceclient` | Transport-agnostic service client with service discovery (env-based, static), token provider protocol, HTTP/gRPC/Kafka transport adapters, 7 canonical error categories |
| `cc_platform_sdk.utils` | ID generation (UUID, correlation ID), UTC time helpers (ISO 8601), JSON serialization utilities |

## Optional Dependencies

The following extras install additional dependencies for specific transport and
observability features:

### `grpc`

gRPC transport support. Required for `cc_platform_sdk.transport.grpc`.

- `grpcio >= 1.60.0`
- `grpcio-health-checking >= 1.60.0`
- `grpcio-reflection >= 1.60.0`

### `kafka`

Kafka transport support. Required for `cc_platform_sdk.transport.kafka`.

- `aiokafka >= 0.10.0`

### `tracing`

OpenTelemetry tracing. Required for `cc_platform_sdk.observability.tracing`.

- `opentelemetry-api >= 1.27.0`
- `opentelemetry-sdk >= 1.27.0`
- `opentelemetry-exporter-otlp >= 1.27.0`

### `web`

ASGI middleware support for `cc_platform_sdk.core.context.ContextMiddleware`.

- `starlette >= 0.27.0`

### `test`

Test runner dependencies for running the SDK's own test suite.

- `pytest >= 8.0.0`
- `pytest-asyncio >= 0.23.0`

### `all`

Installs all optional dependencies: `grpc`, `kafka`, `tracing`, `web`, `test`.

## Testing

For test harnesses and mock utilities used to test services built on this SDK,
see the companion package
[`cc-platform-sdk-testing`](https://github.com/consciousclouds/cc-platform-sdk-testing).

## License

Apache 2.0 -- see [LICENSE](./LICENSE).
