Metadata-Version: 2.3
Name: spakky-fastapi
Version: 12.2.0
Summary: FastAPI plugin for Spakky framework
Author: Spakky
Author-email: Spakky <sejong418@icloud.com>
License: MIT
Requires-Dist: fastapi[standard]>=0.135.3
Requires-Dist: orjson>=3.11.8
Requires-Dist: pydantic-settings>=2.13.1
Requires-Dist: spakky>=12.2.0
Requires-Dist: spakky-actuator>=12.2.0
Requires-Dist: spakky-auth>=12.2.0
Requires-Dist: spakky-tracing>=12.2.0
Requires-Dist: websockets>=16.0
Requires-Python: >=3.12
Description-Content-Type: text/markdown

# Spakky FastAPI

> [Spakky Framework](https://github.com/E5presso/spakky-framework)를 위한 FastAPI 통합 플러그인입니다.
> 플러그인이 제공하거나 사용자가 등록한 FastAPI 앱에 `@ApiController` route, context middleware, lifespan binding, actuator endpoint를 연결합니다.

## 설치

```bash
pip install spakky-fastapi
```

Spakky extras로도 설치할 수 있습니다.

```bash
pip install spakky[fastapi]
```

## 주요 기능

- **자동 route 등록**: `@ApiController` 클래스에서 route를 등록합니다.
- **모든 HTTP 메서드**: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, WebSocket
- **Server-Sent Events**: generator 메서드나 async iterator를 돌려주는 coroutine 메서드를 `@sse`로 `text/event-stream` 응답으로 등록(FastAPI `fastapi.sse` 사용)
- **OpenAPI 통합**: tag와 documentation 자동 설정
- **에러 처리 middleware**: debug mode를 포함한 built-in exception handling
- **Context 관리**: request-scoped 의존성 주입 지원
- **Auth 경계 통합**: `spakky-auth` 보호 handler용 `AuthContext` seeding
- **Actuator endpoint**: `spakky-actuator` 로드 시 선택적 `/actuator/*` HTTP endpoint 제공

## 사용법

### 기본 Controller

```python
from spakky.plugins.fastapi.stereotypes.api_controller import ApiController
from spakky.plugins.fastapi.routes import get, post

@ApiController("/users", tags=["users"])
class UserController:
    def __init__(self, user_service: UserService) -> None:
        self.user_service = user_service

    @get("/{user_id}")
    async def get_user(self, user_id: int) -> User:
        return await self.user_service.get(user_id)

    @post("")
    async def create_user(self, request: CreateUserRequest) -> User:
        return await self.user_service.create(request)
```

### 사용 가능한 route decorator

```python
from spakky.plugins.fastapi.routes import (
    get,
    post,
    put,
    delete,
    patch,
    head,
    options,
    websocket,
)

@ApiController("/api")
class MyController:
    @get("/items")
    async def list_items(self) -> list[Item]:
        ...

    @post("/items")
    async def create_item(self, item: CreateItemRequest) -> Item:
        ...

    @put("/items/{item_id}")
    async def update_item(self, item_id: int, item: UpdateItemRequest) -> Item:
        ...

    @delete("/items/{item_id}")
    async def delete_item(self, item_id: int) -> None:
        ...

    @websocket("/ws")
    async def websocket_endpoint(self, websocket: WebSocket) -> None:
        await websocket.accept()
        while True:
            data = await websocket.receive_text()
            await websocket.send_text(f"Echo: {data}")
```

### Server-Sent Events

`@sse`는 컨트롤러의 (async) generator 메서드를 `text/event-stream` 응답으로 등록합니다. async iterator를
돌려주는 coroutine 메서드도 등록합니다(아래).
FastAPI의 `fastapi.sse`를 그대로 사용하므로 keep-alive comment와 연결 종료 시 generator 취소는
FastAPI가 처리합니다. 기본 HTTP 메서드는 GET이며 `methods`로 바꿀 수 있습니다.

```python
from collections.abc import AsyncIterator

from fastapi.sse import ServerSentEvent
from spakky.plugins.fastapi.routes import sse
from spakky.plugins.fastapi.routes.route import HTTPMethod


@ApiController("/jobs")
class JobController:
    @sse("/{job_id}/events")
    async def events(self, job_id: str) -> AsyncIterator[ServerSentEvent]:
        yield ServerSentEvent(data={"job": job_id}, event="started", id="1")
        yield ServerSentEvent(data={"job": job_id}, event="finished", id="2")

    @sse("/search", methods=[HTTPMethod.POST])
    async def search(self, query: SearchRequest) -> AsyncIterator[SearchHit]:
        for hit in find(query):
            yield hit  # JSON으로 직렬화되어 data: 이벤트가 됩니다
```

컨트롤러 resolve, context 초기화, `AuthContext` seeding은 일반 route와 같고 stream이 시작되기
전에 실행됩니다. 보호된 SSE 메서드에 credential이 없으면 stream 대신 `401`이 응답됩니다.
stream을 열기 전에 판정하고 실패를 HTTP 오류로 답하려면, async iterator를 돌려주는 coroutine
메서드에 `@sse`를 붙입니다. 응답이 시작되기 전에 coroutine을 `await`하므로 그 예외는 일반 route와
같은 HTTP 오류 응답이 되고, 돌려준 async iterator가 stream으로 전송됩니다.
generator도 coroutine도 아닌 메서드에 `@sse`를 붙이면 `SseEndpointNotGeneratorError`가 발생합니다.
자세한 동작은 [FastAPI 심화 가이드](../../docs/guides/fastapi-advanced.md#sse)를 참고하세요.

### FastAPI 앱 접근

```python
from fastapi import FastAPI
from spakky.core.application.application import SpakkyApplication
from spakky.core.application.application_context import ApplicationContext

import apps
import spakky.plugins.fastapi


application = (
    SpakkyApplication(ApplicationContext())
    .load_plugins(include={spakky.plugins.fastapi.PLUGIN_NAME})
    .scan(apps)
    .start()
)

fast_api: FastAPI = application.container.get(FastAPI)
```

`spakky-fastapi`는 기본 `FastAPI` 앱을 Pod로 제공합니다. 앱 title, description,
version, debug는 `SPAKKY_FASTAPI_*` 환경변수로 설정합니다.

### TestClient 테스트

```python
from fastapi.testclient import TestClient

def test_get_user(application: SpakkyApplication) -> None:
    fast_api = application.container.get(FastAPI)
    client = TestClient(fast_api)
    response = client.get("/users/1")
    assert response.status_code == 200
```

## 분산 트레이싱

`spakky-tracing`은 필수 의존성으로 자동 설치됩니다. `TracingMiddleware`가 자동으로 등록되어 모든 HTTP 요청에 대해 `TraceContext`를 전파합니다.

- 수신 요청의 `traceparent` 헤더에서 `TraceContext`를 추출하여 자식 스팬을 생성합니다
- 헤더가 없으면 새로운 루트 트레이스를 시작합니다
- 요청 완료 후 `TraceContext`를 자동으로 정리합니다

## Actuator endpoint

`spakky-actuator` 플러그인을 함께 로드하면 FastAPI 앱에 표준 actuator route가 등록됩니다.
HTTP payload는 transport-neutral core result shape를 그대로 반영합니다.

| Endpoint | 정상 | 비정상 |
|----------|---------|-----------|
| `GET /actuator/health` | `200 OK` | `503 Service Unavailable` |
| `GET /actuator/readiness` | `200 OK` | `503 Service Unavailable` |
| `GET /actuator/liveness` | `200 OK` | `503 Service Unavailable` |
| `GET /actuator/info` | `200 OK` | N/A |

FastAPI actuator route는 기본적으로 인증을 자동 적용하지 않습니다. 운영 환경에서는
내부망, API 게이트웨이, 리버스 프록시 허용 목록, 또는 별도의 접근 제어 계층 뒤에서만
노출하세요. 신뢰 경계 밖으로 actuator traffic을 허용하기 전에는 필요 없는 endpoint를 끄고
`SPAKKY_ACTUATOR_INCLUDE_DETAILS=false`를 설정하세요.

Endpoint 노출과 base path는 플러그인이 등록하는 `FastAPIActuatorConfig` `@Configuration` Pod가 읽습니다.
Component detail 노출은 `spakky.actuator.ActuatorConfig`가 읽습니다.
`readiness`는 traffic/work readiness용이며, `liveness`는 process-local check로 남아 외부 의존성 실패와 독립적이어야 합니다.

```bash
export SPAKKY_ACTUATOR_INCLUDE_DETAILS=false
export SPAKKY_FASTAPI_ACTUATOR_BASE_PATH=/internal/actuator
export SPAKKY_FASTAPI_ACTUATOR_READINESS_ENABLED=false
```

FastAPI adapter는 플러그인별 상세 check를 자동 등록하지 않습니다.
데이터베이스, broker, worker readiness가 actuator 출력에 영향을 줘야 한다면 애플리케이션에 `spakky.actuator.AbstractHealthProbe` Pod를 등록하세요.

## Auth 경계 통합

`spakky-fastapi`는 HTTP/WebSocket 경계에서 `spakky-auth`의 `AuthContext`를 seed합니다.
FastAPI wrapper가 Spakky request context를 clear한 뒤 credential 전달체를 추출하고,
사용자 handler 호출 전에 인증 provider로 `AuthContext`를 저장합니다. 보호된 handler는
인증만을 위해 FastAPI `Request`, `WebSocket`, 또는 `AuthContext` 파라미터를 선언할 필요가 없습니다.

- HTTP는 `Authorization: Bearer <token>`을 지원합니다.
- WebSocket은 `Authorization: Bearer <token>`과 `access_token=<token>` connection query를 지원합니다.
- HTTP auth failure는 CHALLENGE 401, DENY 403, ERROR 500으로 매핑됩니다.
- WebSocket auth failure는 보호된 handler 호출 전에 connection close로 처리됩니다.
- 요청마다 `AuthInvocation`을 `ApplicationContext`에 저장합니다. 속성은 `handler`, `http.header.<소문자 이름>`, `http.path.<이름>`, `http.query.<이름>`이며 `authorization`·`cookie`·`proxy-authorization` 헤더와 `access_token` query는 담지 않습니다. `@require_role("member", tenant=AuthDynamicRef.tenant("http.header.x-workspace"))`처럼 요청에서 정해지는 tenant는 이 속성에서 해석되고, 해석하지 못하면 403입니다.

## 구성 요소

| 컴포넌트 | 설명 |
|-----------|-------------|
| `ApiController` | prefix와 tag를 가진 REST API controller용 stereotype |
| `get`, `post`, `put`, etc. | HTTP method용 route decorator |
| `websocket` | WebSocket endpoint decorator |
| `sse` | generator 메서드나 async iterator를 돌려주는 coroutine 메서드를 Server-Sent Events stream으로 등록하는 decorator |
| `ErrorHandlingMiddleware` | built-in exception handling middleware |
| `TracingMiddleware` | trace context propagation middleware (`spakky-tracing` 필수 의존) |
| `FastAPIConfig` | 플러그인 제공 기본 FastAPI 앱 설정 |
| `FastAPIActuatorConfig` | FastAPI actuator endpoint 노출 설정 |
| `RegisterActuatorPostProcessor` | 자동 actuator endpoint 등록 post-processor |
| `RegisterRoutesPostProcessor` | 자동 route 등록 post-processor |

## 설정

기본 앱 설정은 환경변수로 조정합니다:

```bash
export SPAKKY_FASTAPI_TITLE="My API"
export SPAKKY_FASTAPI_VERSION="1.0.0"
export SPAKKY_FASTAPI_DEBUG=false
```

커스텀 `FastAPI` 인스턴스가 필요하면 플러그인 로드 전에 Pod로 등록합니다.
이 경우 플러그인은 기본 앱을 중복 등록하지 않고, 등록된 앱에 route, middleware,
lifespan hook을 연결합니다:

```python
from fastapi import FastAPI
from spakky.core.application.application import SpakkyApplication
from spakky.core.application.application_context import ApplicationContext
from spakky.core.pod.annotations.pod import Pod

import spakky.plugins.fastapi


@Pod()
def custom_fastapi() -> FastAPI:
    return FastAPI(
        title="My API",
        description="Custom API configuration",
        version="1.0.0",
    )

application = (
    SpakkyApplication(ApplicationContext())
    .add(custom_fastapi)
    .load_plugins(include={spakky.plugins.fastapi.PLUGIN_NAME})
    .start()
)
```

## 개발 검증

패키지 단위 검증은 해당 패키지 디렉토리에서 실행합니다.

```bash
uv run ruff format .
uv run ruff check .
uv run pyrefly check
uv run pytest
```

`pytest`는 각 패키지 `pyproject.toml`의 coverage 설정을 사용합니다.

## 라이선스

MIT
