agentleFS
yerdaulet-damiryerdaulet-damir/vibe-coding-rules/.cursor/rules/integrations.mdc

vibe-coding-rules / rules

Cursor rule28 starsChanged 7 months agoMITView on GitHub

External integration rules — providers, idempotency, bulkhead, observability

  • Reads credentials

The file

We split this integrations.mdc into the rules it gives an agent

10 rules. About 0 are common, 5 are distinctive, and 5 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 5

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Every external boundary in this codebase is shaped by 5 rules.

    line 9
  2. Very specific:

    Rationale: if Fal is hung, its 20 connections fill up — but OpenAI's 50 are untouched.

    line 93
  3. Distinctive:

    Every side-effect operation accepts an idempotency key (UUID v4).

    line 102
  4. Very specific:

    If the provider supports an Idempotency-Key header, forward it.

    line 104
  5. Very specific:

    If not, persist (user_id, key) → provider_request_id in provider_logs.

    line 105
  6. Very specific:

    Use contextvars.ContextVar to thread provider, user_id, request_id through async call stacks.

    line 140
  7. Distinctive:

    When migrating a backend, keep both implementations live.

    line 193
  8. Distinctive:

    If the request fails and the client retries, you must not double-charge or double-generate.

    line 230
  9. Very specific:

    Every provider/format pair has a contract test in tests/contracts/test_<vendor>_<format>.py:

    line 234
  10. Distinctive:

    When the provider changes their response shape, this test fails on the next CI run — not three days later when a user reports a 500.

    line 253

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
integrations.mdc
---
description: External integration rules — providers, idempotency, bulkhead, observability
globs: ["app/providers/**/*.py", "app/services/**/*.py", "app/core/http.py", "app/core/logging.py"]
alwaysApply: true
---

# External Integration Rules

Every external boundary in this codebase is shaped by 5 rules. Apply them every time you add or modify an integration.

## 1. Anti-Corruption Layer (ACL): provider returns `GenerateResult | ProviderError`

Provider adapters MUST translate vendor responses into our domain types. Never return `dict`, never let the vendor's field names cross the boundary.

```python
# app/providers/_types.py
from dataclasses import dataclass
from decimal import Decimal

@dataclass(frozen=True)
class GenerateResult:
    url: str
    cost_usd: Decimal
    latency_ms: int
    provider_request_id: str

class ProviderError(Exception):
    def __init__(self, message: str, *, retryable: bool, code: str | None = None):
        super().__init__(message); self.retryable = retryable; self.code = code

class ProviderTimeout(ProviderError):
    def __init__(self, message: str): super().__init__(message, retryable=True, code="timeout")

class ProviderQuotaExceeded(ProviderError):
    def __init__(self, message: str): super().__init__(message, retryable=False, code="quota")

class ProviderInvalidRequest(ProviderError):
    def __init__(self, message: str): super().__init__(message, retryable=False, code="invalid_request")
```

```python
# ✅ GOOD — adapter maps to ACL
class FalImageAdapter:
    def __init__(self, client: FalClient): self._c = client

    async def generate(self, req: ImageRequest) -> GenerateResult | ProviderError:
        try:
            data = await self._c.request("/v1/image", req.model_dump())
        except httpx.TimeoutException as e:
            return ProviderTimeout(str(e))
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 429:
                return ProviderQuotaExceeded(e.response.text)
            return ProviderError(e.response.text, retryable=False, code=str(e.response.status_code))
        return GenerateResult(
            url=data["images"][0]["url"],
            cost_usd=Decimal(str(data["billing"]["cost_usd"])),
            latency_ms=int(data["meta"]["latency_ms"]),
            provider_request_id=data["request_id"],
        )
```

```python
# ❌ BAD — leaking the vendor response shape
async def generate(self, req: dict) -> dict:
    return await self._c.request("/v1/image", req)
```

## 2. Per-Provider Bulkhead: one `httpx.AsyncClient` per provider

Each external provider has its own `httpx.AsyncClient` instance, with its own `Limits` and `timeout`. Defined ONCE in `app/core/http.py`.

```python
# app/core/http.py
import httpx
from app.core.config import settings

FAL_HTTP = httpx.AsyncClient(
    base_url=settings.FAL_BASE_URL,
    timeout=httpx.Timeout(connect=5.0, read=60.0, write=10.0, pool=5.0),
    limits=httpx.Limits(max_connections=20, max_keepalive_connections=10),
    headers={"Authorization": f"Key {settings.FAL_API_KEY}"},
)

OPENAI_HTTP = httpx.AsyncClient(
    base_url="https://api.openai.com/v1",
    timeout=httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0),
    limits=httpx.Limits(max_connections=50, max_keepalive_connections=20),
    headers={"Authorization": f"Bearer {settings.OPENAI_API_KEY}"},
)
```

**Rationale:** if Fal is hung, its 20 connections fill up — but OpenAI's 50 are untouched. A single global client with `max_connections=100` would let one slow provider freeze every integration.

```python
# ❌ BAD
HTTP = httpx.AsyncClient()  # shared across all providers — no bulkhead
```

## 3. Idempotency Keys

Every side-effect operation accepts an idempotency key (UUID v4). For external API calls:

- If the provider supports an `Idempotency-Key` header, forward it.
- If not, persist `(user_id, key) → provider_request_id` in `provider_logs`. Look up before retrying.

```python
class FalImageAdapter:
    async def generate(self, req: ImageRequest, *, idempotency_key: UUID) -> GenerateResult | ProviderError:
        existing = await self._logs.find(user_id=req.user_id, key=idempotency_key)
        if existing is not None:
            return GenerateResult(**existing.cached_result)

        result_or_err = await self._call(req, header_key=str(idempotency_key))

        if isinstance(result_or_err, GenerateResult):
            await self._logs.persist(
                user_id=req.user_id, key=idempotency_key,
                provider_request_id=result_or_err.provider_request_id,
                cached_result=result_or_err.__dict__,
            )
        return result_or_err
```

Routers accept the key from a header:

```python
@router.post("/generate/image", response_model=GenerateResponse)
async def generate_image(
    req: GenerateRequest,
    user_id: str = Depends(get_current_user_id),
    idempotency_key: UUID = Header(default_factory=uuid4, alias="Idempotency-Key"),
    svc: ImageGenerationService = Depends(get_image_generation_service),
) -> GenerateResponse:
    return GenerateResponse.from_domain(await svc.generate(user_id, req, idempotency_key))
```

## 4. Observability Context (`contextvars`)

Use `contextvars.ContextVar` to thread `provider`, `user_id`, `request_id` through async call stacks. The JSON formatter reads them automatically.

```python
# app/core/logging.py
import contextvars, json, logging

provider_var   = contextvars.ContextVar[str | None]("provider", default=None)
user_id_var    = contextvars.ContextVar[str | None]("user_id", default=None)
request_id_var = contextvars.ContextVar[str | None]("request_id", default=None)

class JsonFormatter(logging.Formatter):
    def format(self, record: logging.LogRecord) -> str:
        payload = {
            "ts":         self.formatTime(record, "%Y-%m-%dT%H:%M:%S%z"),
            "level":      record.levelname,
            "msg":        record.getMessage(),
            "logger":     record.name,
            "provider":   provider_var.get(),
            "user_id":    user_id_var.get(),
            "request_id": request_id_var.get(),
        }
        if record.exc_info:
            payload["exc"] = self.formatException(record.exc_info)
        return json.dumps({k: v for k, v in payload.items() if v is not None})
```

```python
# Middleware sets request_id and user_id at entry
@app.middleware("http")
async def context_middleware(request: Request, call_next):
    request_id_var.set(request.headers.get("X-Request-Id") or str(uuid4()))
    return await call_next(request)
```

```python
# Provider sets `provider` for the duration of the call
class FalImageAdapter:
    async def generate(self, req: ImageRequest) -> GenerateResult | ProviderError:
        token = provider_var.set("fal")
        try:
            return await self._do_generate(req)
        finally:
            provider_var.reset(token)
```

Now you can filter logs in production:

```bash
gcloud logs read 'jsonPayload.provider="fal" AND jsonPayload.level="ERROR"'
```

## 5. Versioned Adapters / Feature Flags

When migrating a backend, keep both implementations live. Switch with one env var.

```python
# app/core/deps.py
def get_wallet_repo(db: Session = Depends(get_db)) -> WalletRepoProtocol:
    if settings.WALLET_REPO_BACKEND == "supabase":
        return SupabaseWalletRepo(client=supabase_client)
    return SQLAlchemyWalletRepo(db)
```

Rollback = `WALLET_REPO_BACKEND=postgres` redeploy. No code revert.

## Forbidden Patterns

1. **Provider returning `dict`.**
   ```python
   async def call(self, req) -> dict: return resp.json()  # ❌
   ```

2. **Shared `httpx.AsyncClient` for multiple providers.**
   ```python
   HTTP = httpx.AsyncClient()  # ❌ no bulkhead
   ```

3. **Vendor field names in business logic.**
   ```python
   # ❌ in services/billing.py
   await wallet.deduct(result["billing"]["cost_usd"])
   ```
   The `result["billing"]["cost_usd"]` shape is the vendor's. Map it to `GenerateResult.cost_usd` in the adapter.

4. **`logger.info(f"{user_id} did X")` instead of structured logging.**
   ```python
   logger.info("charge applied", extra={"amount": str(amount)})  # ✅ JSON formatter picks up extras
   ```

5. **Side-effect operation without an idempotency key.**
   If the request fails and the client retries, you must not double-charge or double-generate.

## Contract Tests

Every provider/format pair has a contract test in `tests/contracts/test_<vendor>_<format>.py`:

```python
# tests/contracts/test_falai_image.py
import json, pathlib, pytest
from app.providers.falai.image import _parse_response  # exported for testing
from app.providers._types import GenerateResult

FIXTURE = pathlib.Path(__file__).parent / "fixtures" / "falai_image_v1.json"

def test_parses_current_response_shape():
    data = json.loads(FIXTURE.read_text())
    result = _parse_response(data)
    assert isinstance(result, GenerateResult)
    assert result.url.startswith("https://")
    assert result.cost_usd > 0
    assert result.provider_request_id
```

When the provider changes their response shape, this test fails on the next CI run — not three days later when a user reports a 500.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.