ccproxy.core¶
ccproxy.core
¶
Core abstractions for the CCProxy API.
MiddlewareError
¶
Bases: ProxyError
Error raised during middleware execution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
The error message |
required |
middleware_name
|
str | None
|
The name of the middleware that failed |
None
|
cause
|
Exception | None
|
The underlying exception |
None
|
Source code in ccproxy/core/errors.py
ProxyAuthenticationError
¶
Bases: ProxyError
Error raised when proxy authentication fails.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
The error message |
required |
auth_type
|
str | None
|
The type of authentication that failed |
None
|
cause
|
Exception | None
|
The underlying exception |
None
|
Source code in ccproxy/core/errors.py
ProxyConnectionError
¶
Bases: ProxyError
Error raised when proxy connection fails.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
The error message |
required |
url
|
str | None
|
The URL that failed to connect |
None
|
cause
|
Exception | None
|
The underlying exception |
None
|
Source code in ccproxy/core/errors.py
ProxyError
¶
Bases: Exception
Base exception for all proxy-related errors.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
The error message |
required |
cause
|
Exception | None
|
The underlying exception that caused this error |
None
|
Source code in ccproxy/core/errors.py
ProxyTimeoutError
¶
Bases: ProxyError
Error raised when proxy operation times out.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
The error message |
required |
timeout
|
float | None
|
The timeout value in seconds |
None
|
cause
|
Exception | None
|
The underlying exception |
None
|
Source code in ccproxy/core/errors.py
TransformationError
¶
Bases: ProxyError
Error raised during data transformation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
message
|
str
|
The error message |
required |
data
|
Any
|
The data that failed to transform |
None
|
cause
|
Exception | None
|
The underlying exception |
None
|
Source code in ccproxy/core/errors.py
BaseProxyClient
¶
Generic proxy client with no business logic - pure forwarding.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
http_client
|
HTTPClient
|
The HTTP client to use for requests |
required |
Source code in ccproxy/core/http.py
forward
async
¶
Forward an HTTP request without any transformations.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
HTTP method |
required |
url
|
str
|
Target URL |
required |
headers
|
dict[str, str]
|
HTTP headers |
required |
body
|
bytes | None
|
Request body (optional) |
None
|
timeout
|
float | None
|
Request timeout in seconds (optional) |
None
|
Returns:
Type | Description |
---|---|
tuple[int, dict[str, str], bytes]
|
Tuple of (status_code, response_headers, response_body) |
Raises:
Type | Description |
---|---|
HTTPError
|
If the request fails |
Source code in ccproxy/core/http.py
HTTPClient
¶
Bases: ABC
Abstract HTTP client interface for generic HTTP operations.
request
abstractmethod
async
¶
Make an HTTP request.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
HTTP method (GET, POST, etc.) |
required |
url
|
str
|
Target URL |
required |
headers
|
dict[str, str]
|
HTTP headers |
required |
body
|
bytes | None
|
Request body (optional) |
None
|
timeout
|
float | None
|
Request timeout in seconds (optional) |
None
|
Returns:
Type | Description |
---|---|
tuple[int, dict[str, str], bytes]
|
Tuple of (status_code, response_headers, response_body) |
Raises:
Type | Description |
---|---|
HTTPError
|
If the request fails |
Source code in ccproxy/core/http.py
HTTPConnectionError
¶
HTTPError
¶
HTTPTimeoutError
¶
HTTPXClient
¶
Bases: HTTPClient
HTTPX-based HTTP client implementation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
float
|
Request timeout in seconds |
240.0
|
proxy
|
str | None
|
HTTP proxy URL (optional) |
None
|
verify
|
bool | str
|
SSL verification (True/False or path to CA bundle) |
True
|
Source code in ccproxy/core/http.py
request
async
¶
Make an HTTP request using HTTPX.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
HTTP method |
required |
url
|
str
|
Target URL |
required |
headers
|
dict[str, str]
|
HTTP headers |
required |
body
|
bytes | None
|
Request body (optional) |
None
|
timeout
|
float | None
|
Request timeout in seconds (optional) |
None
|
Returns:
Type | Description |
---|---|
tuple[int, dict[str, str], bytes]
|
Tuple of (status_code, response_headers, response_body) |
Raises:
Type | Description |
---|---|
HTTPError
|
If the request fails |
Source code in ccproxy/core/http.py
stream
async
¶
Create a streaming HTTP request.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
HTTP method |
required |
url
|
str
|
Target URL |
required |
headers
|
dict[str, str]
|
HTTP headers |
required |
content
|
bytes | None
|
Request body (optional) |
None
|
Returns:
Type | Description |
---|---|
Any
|
HTTPX streaming response context manager |
Source code in ccproxy/core/http.py
APIAdapter
¶
Bases: ABC
Abstract base class for API format adapters.
Combines all transformation interfaces to provide a complete adapter for converting between different API formats.
adapt_request
abstractmethod
¶
Convert a request from one API format to another.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
dict[str, Any]
|
The request data to convert |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The converted request data |
Raises:
Type | Description |
---|---|
ValueError
|
If the request format is invalid or unsupported |
Source code in ccproxy/core/interfaces.py
adapt_response
abstractmethod
¶
Convert a response from one API format to another.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response
|
dict[str, Any]
|
The response data to convert |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The converted response data |
Raises:
Type | Description |
---|---|
ValueError
|
If the response format is invalid or unsupported |
Source code in ccproxy/core/interfaces.py
adapt_stream
abstractmethod
¶
Convert a streaming response from one API format to another.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stream
|
AsyncIterator[dict[str, Any]]
|
The streaming response data to convert |
required |
Yields:
Type | Description |
---|---|
AsyncIterator[dict[str, Any]]
|
The converted streaming response chunks |
Raises:
Type | Description |
---|---|
ValueError
|
If the stream format is invalid or unsupported |
Source code in ccproxy/core/interfaces.py
MetricExporter
¶
Bases: ABC
Abstract interface for exporting metrics to external systems.
export_metrics
abstractmethod
async
¶
Export metrics to the target system.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
metrics
|
dict[str, Any]
|
Dictionary of metrics to export |
required |
Returns:
Type | Description |
---|---|
bool
|
True if export was successful, False otherwise |
Raises:
Type | Description |
---|---|
ConnectionError
|
If unable to connect to the metrics backend |
ValueError
|
If metrics format is invalid |
Source code in ccproxy/core/interfaces.py
StreamTransformer
¶
Bases: ABC
Abstract interface for stream transformers.
transform_stream
abstractmethod
async
¶
Transform a streaming response from one format to another.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
stream
|
AsyncIterator[dict[str, Any]]
|
The streaming response data to transform |
required |
Yields:
Type | Description |
---|---|
AsyncIterator[dict[str, Any]]
|
The transformed streaming response chunks |
Raises:
Type | Description |
---|---|
ValueError
|
If the stream format is invalid or unsupported |
Source code in ccproxy/core/interfaces.py
TokenStorage
¶
Bases: ABC
Abstract interface for token storage backends.
load
abstractmethod
async
¶
Load credentials from storage.
Returns:
Type | Description |
---|---|
ClaudeCredentials | None
|
Parsed credentials if found and valid, None otherwise |
save
abstractmethod
async
¶
Save credentials to storage.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
credentials
|
ClaudeCredentials
|
Credentials to save |
required |
Returns:
Type | Description |
---|---|
bool
|
True if saved successfully, False otherwise |
exists
abstractmethod
async
¶
Check if credentials exist in storage.
Returns:
Type | Description |
---|---|
bool
|
True if credentials exist, False otherwise |
delete
abstractmethod
async
¶
Delete credentials from storage.
Returns:
Type | Description |
---|---|
bool
|
True if deleted successfully, False otherwise |
IRequestTransformer
¶
Bases: ABC
Abstract interface for request transformers.
transform_request
abstractmethod
async
¶
Transform a request from one format to another.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
dict[str, Any]
|
The request data to transform |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The transformed request data |
Raises:
Type | Description |
---|---|
ValueError
|
If the request format is invalid or unsupported |
Source code in ccproxy/core/interfaces.py
IResponseTransformer
¶
Bases: ABC
Abstract interface for response transformers.
transform_response
abstractmethod
async
¶
Transform a response from one format to another.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response
|
dict[str, Any]
|
The response data to transform |
required |
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The transformed response data |
Raises:
Type | Description |
---|---|
ValueError
|
If the response format is invalid or unsupported |
Source code in ccproxy/core/interfaces.py
CompositeMiddleware
¶
Bases: BaseMiddleware
Middleware that combines multiple middleware into one.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
middleware
|
list[BaseMiddleware]
|
List of middleware to apply in order |
required |
Source code in ccproxy/core/middleware.py
MiddlewareChain
¶
Manages a chain of middleware.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
middleware
|
list[BaseMiddleware]
|
List of middleware to apply in order |
required |
Source code in ccproxy/core/middleware.py
BaseProxy
¶
Bases: ABC
Abstract base class for all proxy implementations.
forward
abstractmethod
async
¶
Forward a request and return the response.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
ProxyRequest
|
The proxy request to forward |
required |
Returns:
Type | Description |
---|---|
ProxyResponse
|
The proxy response |
Raises:
Type | Description |
---|---|
ProxyError
|
If the request cannot be forwarded |
Source code in ccproxy/core/proxy.py
HTTPProxy
¶
Bases: BaseProxy
HTTP proxy implementation using HTTPClient abstractions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
http_client
|
HTTPClient
|
The HTTP client to use for requests |
required |
Source code in ccproxy/core/proxy.py
forward
async
¶
Forward an HTTP request using the HTTP client.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
ProxyRequest
|
The proxy request to forward |
required |
Returns:
Type | Description |
---|---|
ProxyResponse
|
The proxy response |
Raises:
Type | Description |
---|---|
ProxyError
|
If the request cannot be forwarded |
Source code in ccproxy/core/proxy.py
BaseTransformer
¶
Bases: ABC
Abstract base class for all transformers.
Source code in ccproxy/core/transformers.py
transform
abstractmethod
async
¶
Transform the input data.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Any
|
The data to transform |
required |
context
|
TransformContext | None
|
Optional transformation context |
None
|
Returns:
Type | Description |
---|---|
Any
|
The transformed data |
Raises:
Type | Description |
---|---|
TransformationError
|
If transformation fails |
Source code in ccproxy/core/transformers.py
ChainedTransformer
¶
Bases: BaseTransformer
Transformer that chains multiple transformers together.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
transformers
|
list[BaseTransformer]
|
List of transformers to apply in sequence |
required |
Source code in ccproxy/core/transformers.py
transform
async
¶
Apply all transformers in sequence.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data
|
Any
|
The data to transform |
required |
context
|
TransformContext | None
|
Optional transformation context |
None
|
Returns:
Type | Description |
---|---|
Any
|
The result of applying all transformers |
Source code in ccproxy/core/transformers.py
RequestTransformer
¶
Bases: BaseTransformer
Base class for request transformers.
Source code in ccproxy/core/transformers.py
transform
async
¶
Transform a proxy request with metrics collection.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
request
|
ProxyRequest
|
The request to transform |
required |
context
|
TransformContext | None
|
Optional transformation context |
None
|
Returns:
Type | Description |
---|---|
ProxyRequest
|
The transformed request |
Source code in ccproxy/core/transformers.py
ResponseTransformer
¶
Bases: BaseTransformer
Base class for response transformers.
Source code in ccproxy/core/transformers.py
transform
async
¶
Transform a proxy response with metrics collection.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
response
|
ProxyResponse
|
The response to transform |
required |
context
|
TransformContext | None
|
Optional transformation context |
None
|
Returns:
Type | Description |
---|---|
ProxyResponse
|
The transformed response |
Source code in ccproxy/core/transformers.py
ProxyRequest
dataclass
¶
ProxyRequest(
method,
url,
headers=dict(),
params=dict(),
body=None,
protocol=HTTPS,
timeout=None,
metadata=dict(),
)
Represents a proxy request.
ProxyResponse
dataclass
¶
TransformContext
dataclass
¶
TransformContext(
request=None, response=None, metadata=dict()
)
Context passed to transformers during transformation.
get
¶
async_cache_result
async
¶
Cache the result of an async function call.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable[..., Awaitable[T]]
|
The async function to cache |
required |
cache_key
|
str
|
Unique key for caching |
required |
cache_duration
|
float
|
Cache duration in seconds |
300.0
|
*args
|
Any
|
Positional arguments to pass to the function |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Returns:
Type | Description |
---|---|
T
|
The cached or computed result |
Source code in ccproxy/core/async_utils.py
async_timer
async
¶
Context manager for timing async operations.
Yields:
Type | Description |
---|---|
AsyncIterator[Callable[[], float]]
|
Function that returns elapsed time in seconds |
Source code in ccproxy/core/async_utils.py
gather_with_concurrency
async
¶
Gather awaitables with concurrency limit.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
limit
|
int
|
Maximum number of concurrent operations |
required |
*awaitables
|
Awaitable[T]
|
Awaitables to execute |
()
|
return_exceptions
|
bool
|
Whether to return exceptions as results |
False
|
Returns:
Type | Description |
---|---|
list[T | BaseException] | list[T]
|
List of results from the awaitables |
Source code in ccproxy/core/async_utils.py
get_package_dir
¶
Get the package directory path.
Returns:
Type | Description |
---|---|
Path
|
Path to the package directory |
Source code in ccproxy/core/async_utils.py
get_root_package_name
¶
patched_typing
¶
Fix for typing.TypedDict not supported in older Python versions.
This patches typing.TypedDict to use typing_extensions.TypedDict.
Source code in ccproxy/core/async_utils.py
retry_async
async
¶
retry_async(
func,
*args,
max_retries=3,
delay=1.0,
backoff=2.0,
exceptions=(Exception,),
**kwargs,
)
Retry an async function with exponential backoff.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable[..., Awaitable[T]]
|
The async function to retry |
required |
*args
|
Any
|
Positional arguments to pass to the function |
()
|
max_retries
|
int
|
Maximum number of retries |
3
|
delay
|
float
|
Initial delay between retries |
1.0
|
backoff
|
float
|
Backoff multiplier |
2.0
|
exceptions
|
tuple[type[Exception], ...]
|
Exception types to catch and retry on |
(Exception,)
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Returns:
Type | Description |
---|---|
T
|
The result of the successful function call |
Source code in ccproxy/core/async_utils.py
run_in_executor
async
¶
Run a synchronous function in an executor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
func
|
Callable[..., T]
|
The synchronous function to run |
required |
*args
|
Any
|
Positional arguments to pass to the function |
()
|
**kwargs
|
Any
|
Keyword arguments to pass to the function |
{}
|
Returns:
Type | Description |
---|---|
T
|
The result of the function call |
Source code in ccproxy/core/async_utils.py
safe_await
async
¶
Safely await an awaitable with optional timeout.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
awaitable
|
Awaitable[T]
|
The awaitable to wait for |
required |
timeout
|
float | None
|
Optional timeout in seconds |
None
|
Returns:
Type | Description |
---|---|
T | None
|
The result of the awaitable or None if timeout/error |
Source code in ccproxy/core/async_utils.py
wait_for_condition
async
¶
Wait for a condition to become true.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
condition
|
Callable[[], bool | Awaitable[bool]]
|
Function that returns True when condition is met |
required |
timeout
|
float
|
Maximum time to wait in seconds |
30.0
|
interval
|
float
|
Check interval in seconds |
0.1
|
Returns:
Type | Description |
---|---|
bool
|
True if condition was met, False if timeout occurred |
Source code in ccproxy/core/async_utils.py
validate_choice
¶
Validate that value is one of the allowed choices.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Any
|
Value to validate |
required |
choices
|
list[Any]
|
List of allowed choices |
required |
name
|
str
|
Name of the field for error messages |
'value'
|
Returns:
Type | Description |
---|---|
Any
|
The validated value |
Raises:
Type | Description |
---|---|
ValidationError
|
If value is not in choices |
Source code in ccproxy/core/validators.py
validate_dict
¶
Validate dictionary and required keys.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Any
|
Value to validate as dictionary |
required |
required_keys
|
list[str] | None
|
List of required keys |
None
|
Returns:
Type | Description |
---|---|
dict[str, Any]
|
The validated dictionary |
Raises:
Type | Description |
---|---|
ValidationError
|
If not a dictionary or missing required keys |
Source code in ccproxy/core/validators.py
validate_email
¶
Validate email format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
email
|
str
|
Email address to validate |
required |
Returns:
Type | Description |
---|---|
str
|
The validated email address |
Raises:
Type | Description |
---|---|
ValidationError
|
If email format is invalid |
Source code in ccproxy/core/validators.py
validate_list
¶
Validate list and length constraints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
Any
|
Value to validate as list |
required |
min_length
|
int
|
Minimum list length |
0
|
max_length
|
int | None
|
Maximum list length |
None
|
Returns:
Type | Description |
---|---|
list[Any]
|
The validated list |
Raises:
Type | Description |
---|---|
ValidationError
|
If not a list or length constraints are violated |
Source code in ccproxy/core/validators.py
validate_non_empty_string
¶
Validate that a string is not empty.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
str
|
String value to validate |
required |
name
|
str
|
Name of the field for error messages |
'value'
|
Returns:
Type | Description |
---|---|
str
|
The validated string |
Raises:
Type | Description |
---|---|
ValidationError
|
If string is empty or not a string |
Source code in ccproxy/core/validators.py
validate_path
¶
Validate file system path.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path
|
str | Path
|
Path to validate |
required |
must_exist
|
bool
|
Whether the path must exist |
True
|
Returns:
Type | Description |
---|---|
Path
|
The validated Path object |
Raises:
Type | Description |
---|---|
ValidationError
|
If path is invalid |
Source code in ccproxy/core/validators.py
validate_port
¶
Validate port number.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
port
|
int | str
|
Port number to validate |
required |
Returns:
Type | Description |
---|---|
int
|
The validated port number |
Raises:
Type | Description |
---|---|
ValidationError
|
If port is invalid |
Source code in ccproxy/core/validators.py
validate_range
¶
Validate that a numeric value is within a specified range.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
value
|
float | int
|
Numeric value to validate |
required |
min_value
|
float | int | None
|
Minimum allowed value |
None
|
max_value
|
float | int | None
|
Maximum allowed value |
None
|
name
|
str
|
Name of the field for error messages |
'value'
|
Returns:
Type | Description |
---|---|
float | int
|
The validated value |
Raises:
Type | Description |
---|---|
ValidationError
|
If value is outside the allowed range |
Source code in ccproxy/core/validators.py
validate_timeout
¶
Validate timeout value.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
timeout
|
float | int | str
|
Timeout value to validate |
required |
Returns:
Type | Description |
---|---|
float
|
The validated timeout value |
Raises:
Type | Description |
---|---|
ValidationError
|
If timeout is invalid |
Source code in ccproxy/core/validators.py
validate_url
¶
Validate URL format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
url
|
str
|
URL to validate |
required |
Returns:
Type | Description |
---|---|
str
|
The validated URL |
Raises:
Type | Description |
---|---|
ValidationError
|
If URL format is invalid |
Source code in ccproxy/core/validators.py
validate_uuid
¶
Validate UUID format.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
uuid_str
|
str
|
UUID string to validate |
required |
Returns:
Type | Description |
---|---|
str
|
The validated UUID string |
Raises:
Type | Description |
---|---|
ValidationError
|
If UUID format is invalid |