Metadata-Version: 2.5
Name: aw3-sdk
Version: 1.0.0
Summary: Python client for AW3 Host, the multi-cloud deployment control plane: deploy to 17 clouds from one API.
Project-URL: Homepage, https://aw3.host
Project-URL: Documentation, https://aw3.host/docs
Project-URL: Source, https://github.com/aw3-technology/aw3-sdk
Project-URL: Issues, https://github.com/aw3-technology/aw3-sdk/issues
Author-email: "AW3 Technology, Inc." <contact@aw3.tech>
License-Expression: MIT
License-File: LICENSE
Keywords: aw3,aws,blue-green,canary,cloudflare,deployment,devops,multi-cloud,railway,vercel
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Build Tools
Classifier: Topic :: System :: Systems Administration
Classifier: Typing :: Typed
Requires-Python: >=3.8
Requires-Dist: httpx>=0.24
Description-Content-Type: text/markdown

# aw3-sdk — AW3 Python SDK

The official Python client for the [AW3](https://aw3.host) multi-cloud deployment control plane.

## Requirements

- Python 3.8+
- `httpx` (installed automatically)

## Installation

```bash
pip install aw3-sdk
```

## Quick Start

```python
from aw3_sdk import AW3Client

client = AW3Client(
    base_url="https://app.aw3.host/api",
    token="aw3_abc123...",  # or set AW3_TOKEN env var
)

# Deploy a service (blocks until terminal state)
deployment = client.deploy("svc-abc123", commit_sha="a1b2c3d", wait=True)
print(f"Status: {deployment.status}")
print(f"URL: {deployment.deploy_url}")
```

## Configuration

```python
client = AW3Client(
    base_url="https://app.aw3.host/api",  # or AW3_BASE_URL env var
    token="aw3_abc123...",           # or AW3_TOKEN env var
    timeout=30.0,                    # default: 30s
    max_retries=3,                   # default: 3 (exponential backoff on 5xx)
)
```

The client can also be used as a context manager:

```python
with AW3Client(token="aw3_...") as client:
    deployment = client.deploy("svc-abc123", wait=True)
```

## API Reference

### Deployments

#### `deploy(service_id, **kwargs)`

Trigger a deployment.

```python
deployment = client.deploy(
    service_id="svc-abc123",
    commit_sha="a1b2c3d",           # optional git commit SHA
    commit_message="fix: auth bug", # optional audit message
    branch="main",                  # optional branch override
    strategy="canary",              # "standard" | "blue-green" | "canary"
    canary_percent=5,               # initial canary traffic %
    wait=True,                      # block until terminal state
    poll_interval=2.0,              # polling interval in seconds
    timeout_minutes=30.0,           # max wait time
)
print(deployment.id)       # "dep-abc123"
print(deployment.status)   # "RUNNING"
print(deployment.deploy_url)
```

**Deployment statuses:** `PENDING`, `BUILDING`, `DEPLOYING`, `RUNNING`, `FAILED`, `CANCELLED`, `ROLLED_BACK`

#### `get_deployment(deployment_id)`

```python
deployment = client.get_deployment("dep-abc123")
```

#### `list_deployments(service_id=None, limit=20, status=None)`

```python
deployments = client.list_deployments(service_id="svc-abc123", limit=10)
for d in deployments:
    print(f"{d.id}: {d.status}")
```

#### `rollback(service_id, target_deployment_id=None)`

```python
# Roll back to the last successful deployment
deployment = client.rollback("svc-abc123")

# Roll back to a specific deployment
deployment = client.rollback("svc-abc123", target_deployment_id="dep-xyz789")
```

### Logs

#### `get_logs(service_id, deployment_id=None, lines=100)`

```python
logs = client.get_logs("svc-abc123", lines=50)
for log in logs:
    print(f"[{log.timestamp}] {log.level.upper()}: {log.message}")
```

#### `stream_logs(service_id, deployment_id=None, follow=True)`

Streams logs as a generator. Uses SSE when available, falls back to polling.

```python
for log in client.stream_logs("svc-abc123"):
    print(f"[{log.timestamp}] {log.message}")
    if log.message == "Deployment complete":
        break
```

### Services

#### `list_services(project_id=None, limit=50)`

```python
services = client.list_services(project_id="proj-abc123")
for svc in services:
    print(f"{svc.name} ({svc.id}): {svc.status}")
```

#### `get_service(service_id)`

```python
service = client.get_service("svc-abc123")
print(service.deploy_url)
```

#### `get_status(service_id)`

```python
status = client.get_status("svc-abc123")
print(status["status"])      # "RUNNING"
print(status["deployUrl"])   # the provider URL of the latest deploy
```

## Error Handling

```python
from aw3_sdk import AW3Client, AW3Error

client = AW3Client(token="aw3_...")

try:
    deployment = client.deploy("svc-abc123", wait=True)
except AW3Error as e:
    print(f"API error {e.status_code}: {e.message}")
    if e.status_code == 401:
        print("Invalid or expired token")
    elif e.status_code == 404:
        print("Service not found")
    elif e.status_code == 429:
        print("Rate limit exceeded")
except TimeoutError as e:
    print(f"Deployment timed out: {e}")
```

The client automatically retries on `5xx` server errors and network failures up to `max_retries` times with exponential backoff (`1s`, `2s`, `4s`, ...). Client errors (`4xx`) are never retried.

## Data Classes

```python
@dataclass
class Deployment:
    id: str
    service_id: str
    status: str
    created_at: str
    deploy_url: Optional[str]
    commit_sha: Optional[str]
    commit_message: Optional[str]
    image_tag: Optional[str]
    error: Optional[str]
    branch: Optional[str]
    raw: Dict[str, Any]          # original API response

@dataclass
class Service:
    id: str
    name: str
    type: str
    status: Optional[str]
    deploy_url: Optional[str]
    last_deployed_at: Optional[str]
    raw: Dict[str, Any]

@dataclass
class LogLine:
    timestamp: str
    message: str
    level: str                   # "info" | "warn" | "error" | "debug"
    service_id: Optional[str]
```

## CI/CD Example

```python
import os
from aw3_sdk import AW3Client, AW3Error

client = AW3Client(token=os.environ["AW3_TOKEN"])

try:
    # Deploy as canary at 5%
    deployment = client.deploy(
        service_id=os.environ["SERVICE_ID"],
        commit_sha=os.environ.get("GITHUB_SHA"),
        strategy="canary",
        canary_percent=5,
        wait=True,
    )
    print(f"Canary deployed: {deployment.id}")

    # Stream logs
    print("Streaming logs...")
    for log in client.stream_logs(os.environ["SERVICE_ID"], follow=False):
        print(f"  {log.message}")

except AW3Error as e:
    print(f"Deployment failed: {e}")
    # Optionally roll back
    rollback = client.rollback(os.environ["SERVICE_ID"])
    print(f"Rolled back to: {rollback.id}")
    raise SystemExit(1)
```

## Environment Variables

| Variable | Description |
|----------|-------------|
| `AW3_TOKEN` | API authentication token |
| `AW3_BASE_URL` | API base URL (default: `https://app.aw3.host/api`) |

## License

MIT
