Skip to main content

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

pip install cc-platform-sdk

With optional extras:

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

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.

License

Apache 2.0 -- see LICENSE.

Universal event envelope v2

cc_platform_sdk.eventenvelope provides create_envelope, encode_envelope, decode_envelope and decode_and_admit. Use the supplied origin time to make a first emission. Encoding checks the governed event catalog. Decode checks the closed JSON shape and 64-level depth rule. Before dispatch, pass the bytes and an authorized subscription with an exact project, classification, tenant, owner and family to decode_and_admit. An absent tenant or owner matches absence only. A v2 event's nonempty correlation is the ledger handle.

The shared canonical fixtures pin bytes, nanosecond timestamps and safe-integer payload values. Replays preserve the event ID and occurrence time. Retain the original bytes when available. The codec makes no byte-equality claim for arbitrary noncanonical input or for full Go float and escaping parity.

The existing raw Kafka consumer routes v1 product records as dictionaries and bypasses the v2 event codec and verify trusted tenant scope. The v2 helpers do not add broker authorization, deduplication or offset policy.

Technology installation management v1

Import TechnologyManagementClient and the contract types from cc_platform_sdk.technology_management. Pass the existing SDK HTTP client configured for the Operator Gateway or an enrolled product gateway. The binding exposes get_installation and get_operation for reading installation state and receipts, and stage, activate, and rollback for changes. Changes require matching route and body scopes and a caller-supplied idempotency_key. An executor refusal is represented on its receipt. A closed contract error is exposed as TechnologyManagementError, with the original HTTP status when supplied by the gateway.

Metadata

Release files for cc-platform-sdk 2.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cc-platform-sdk 2.3.0
File Size Uploaded Provenance Actions
cc_platform_sdk-2.3.0.tar.gz 306.1 kB Without provenance Details for cc_platform_sdk-2.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cc-platform-sdk 2.3.0
File Interpreter ABI Platform Actions
cc_platform_sdk-2.3.0-py3-none-any.whl Python 3 none any Details for cc_platform_sdk-2.3.0-py3-none-any.whl

Total release size: 492.0 kB

Release files / cc_platform_sdk-2.3.0.tar.gz

Download URL cc_platform_sdk-2.3.0.tar.gz
Size 306.1 kB
Tags Source
SHA-256 checksum
How to use checksums
80772060b4f1e93b5127bf94ec971229bb755c3a242b669c92deffc304f7e891
BLAKE2b-256 checksum
How to use checksums
5624b53ee5f86776091db1a8228d262a29463c71a89079202589e102ab426949
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.19

Release files / cc_platform_sdk-2.3.0-py3-none-any.whl

Download URL cc_platform_sdk-2.3.0-py3-none-any.whl
Size 186.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab30d8a2b7c38406f616a69cef216b5d969789dde7973265bf8b4f916036195f
BLAKE2b-256 checksum
How to use checksums
ddbaea188d8de27948222c8c88b7b1aa1a68ad07d57463b9f793bcc544b07769
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.7.19

Security for cc-platform-sdk 2.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page