Metadata-Version: 2.4
Name: vs-server
Version: 0.2.2
Summary: HTTP server abstraction for Viveka Sutra — FastAPI wrapper with lifecycle, routing, and middleware
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and derivative works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of discussing and
              improving the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and incorporated
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any
              Contribution embodied within the Work constitutes direct or
              contributory patent infringement, then any patent licenses granted to
              You under this License for that Work shall terminate as of the date
              such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" file as part of its distribution,
                  You must include a readable copy of the attribution notices
                  contained within such NOTICE file, in at least one of the
                  following places: within a NOTICE text file distributed as part
                  of the Derivative Works; within the Source form or documentation,
                  if provided along with the Derivative Works; or, within a display
                  generated by the Derivative Works, if and wherever such
                  third-party notices normally appear. The contents of the NOTICE
                  file are for informational purposes only and do not modify the
                  License. You may add Your own attribution notices within
                  Derivative Works that You distribute, alongside or as an addendum
                  to the NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, modify, and distribute
              Your modifications.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any conditions of TITLE,
              NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
              PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 VivekaSutra. All rights reserved.
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied. See the License for the specific language governing
           permissions and limitations under the License.
        
Project-URL: Homepage, https://vivekasutra.com/
Project-URL: Source, https://github.com/vivekasutra/viveka-mula
Keywords: fastapi,server,http,api,viveka,vs
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: vs-common>=0.2.3
Requires-Dist: pydantic>=2.0
Provides-Extra: security
Requires-Dist: vs-security>=0.1.17; extra == "security"
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == "fastapi"
Requires-Dist: uvicorn>=0.23; extra == "fastapi"
Provides-Extra: flask
Requires-Dist: flask>=3.0; extra == "flask"
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: fastapi>=0.110; extra == "dev"
Requires-Dist: uvicorn>=0.23; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Dynamic: license-file

# vs-server

Multi-protocol server framework for Viveka Sutra — HTTP, WebSocket, and SSE on the same class, with pluggable server implementations, lifecycle hooks, and declarative auth guards.

---

## Overview

`vs-server` is the network layer every VS service is built on. It eliminates framework boilerplate — no manual `FastAPI()` setup, no router wiring, no middleware calls. Controllers are plain classes annotated with `@controller`. WebSocket and SSE handlers follow the same pattern with `@websocket` and `@sse`. A single class can carry all three protocols at once by stacking decorators.

Server implementations are pluggable via `VsServerFactory` — register any `VsServer` subclass under a key and retrieve it at startup. `VsFastApiServer` ships as the built-in implementation and auto-registers as `"fastapi"` on import.

---

## The Problem It Solves

Every service needs routing, middleware, exception handling, and lifecycle management. Without `vs-server`, each service repeats the same boilerplate.

### Without vs-server

```python
from fastapi import FastAPI, APIRouter
from fastapi.middleware.cors import CORSMiddleware
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app):
    await create_tables()
    yield

app = FastAPI(title="my-service", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

router = APIRouter(prefix="/users")

@router.get("")
async def list_users(): ...

@router.post("")
async def create_user(body: UserRequest): ...

app.include_router(router)
uvicorn.run(app, host="0.0.0.0", port=8000)
```

### With vs-server

```python
from vs_server.decorator.vs_controller_decorator import controller, get, post

@controller("/users")
class UserController:

    @get("")
    async def list_users(self): ...

    @post("")
    async def create_user(self, body: UserRequest): ...
```

```python
from vs_common.config.vs_ini_config import VsIniConfig
from vs_server.lifecycle.vs_lifecycle import startup
from vs_db.session.vs_db_session_factory import VsDbSessionFactory

config = VsIniConfig("config.ini")
db = VsDbSessionFactory(config)

@startup
async def create_tables():
    await db.create_tables()
```

```python
server = VsServerFactory.get("fastapi", config)
server.add_controller(UserController())
server.run()
```

One pattern, every service, zero drift.

---

## Installation

```bash
pip install vs-server
```

With FastAPI support:

```bash
pip install vs-server[fastapi]
```

---

## Dependencies

| Package | Version              | Required | Purpose |
|---|----------------------|---|---|
| `vs-common` | `>=0.2.3`            | Yes | Config, logging, base exceptions |
| `pydantic` | `>=2.0`              | Yes | Request/response schema validation |
| `fastapi` | `>=0.100`            | No — install with `[fastapi]` extra | FastAPI HTTP server implementation |
| `uvicorn` | `>=0.23`             | No — install with `[fastapi]` extra | ASGI server |
| `starlette` | pulled in by FastAPI | No | CORS middleware |
| `vs-security` | any                  | No — lazy import | JWT auth, filter enrichment |
| `vs-db` | `>=0.3.0`            | No — install separately | Database sessions, transactions, and the per-request `VsDbMiddleware`. See [Using with vs-db](#using-with-vs-db) |

---

## Configuration

All server config lives under the `[server]` section of `config.ini`.

| Key | Default | Description |
|---|---|---|
| `server.name` | `vs-server` | Server name shown in logs, `/`, and Swagger |
| `server.version` | `0.1.0` | Version shown in logs, `/`, and Swagger |
| `server.description` | `App server developed by Viveka Sutra` | Description shown in Swagger |
| `server.base_url` | `""` | Base URL prefix for all core routes (`/`, `/health`, `/stream-docs`) |
| `server.host` | `127.0.0.1` | Host to bind |
| `server.allow_unauthenticated` | `false` | A server bound to a non-loopback address (e.g. `0.0.0.0`) refuses to start unless `enable_security()` was called. Set to `true` when another layer (gateway, mesh, mTLS) handles authentication. Loopback-only servers start either way, with a warning. |
| `server.port` | `8000` | Port to bind |
| `server.docs_enabled` | `true` | Expose `/docs`, `/redoc`, `/openapi.json`, and `/stream-docs`. Set to `false` in production to hide all documentation endpoints. |
| `server.ssl_certfile` | — | Path to TLS certificate file |
| `server.ssl_keyfile` | — | Path to TLS private key file |
| `server.ssl_keyfile_password` | — | Password for encrypted private key |
| `server.ws_reauth_interval_seconds` | `300` | With `enable_security()` on, how often an open WebSocket's credentials are re-validated with the original handshake headers. A failed or broken check closes the connection with `1008`. `0` turns rechecks off. |
| `server.docs_public` | `false` | Once `enable_security()` is on, the documentation endpoints need credentials like any other route. Set to `true` to let them skip authentication. No effect when security is off or `server.docs_enabled = false`. |
| `server.max_auth_payload_bytes` | `10485760` (10 MB) | Largest JSON body read for an authenticator or `request_enricher`. Larger bodies get `413` before authentication runs. `0` removes the limit. |
| `api.cors_origins` | — (none) | Comma-separated origins allowed to call cross-origin. Empty means same-origin only. `*` allows any origin but disables credentialed (cookie) requests. Also used as the WebSocket `Origin` allow-list when security is enabled. |

These keys apply to all `VsServer` implementations. Framework-specific config lives in its own section.

### FastAPI-specific config (`[fastapi]`)

| Key | Default | Description |
|---|---|---|
| `fastapi.workers` | `1` | Number of worker processes. Requires `fastapi.app_import` to be set. |
| `fastapi.reload` | `false` | Enable hot reload (dev only). Requires `fastapi.app_import` to be set. |
| `fastapi.log_level` | `info` | Uvicorn log level (`debug`, `info`, `warning`, `error`) |
| `fastapi.app_import` | — | Import string for multi-worker or reload mode, e.g. `my_service.app:server`. Required when `workers > 1` or `reload = true`. |

**`config.ini` example for multi-worker production:**

```ini
[server]
name = my-service
version = 1.0.0
host = 0.0.0.0
port = 8000
docs_enabled = false

[fastapi]
workers = 4
log_level = warning
app_import = my_service.app:server

[api]
cors_origins = https://app.example.com
```

**What is `app_import`?**

When running multiple workers, uvicorn forks child processes that each need to reconstruct the app independently. They can't share the in-memory object from the parent process — they need an import path to build their own copy.

`app_import` is `module.path:variable_name` where `variable_name` is whatever you assigned `VsServerFactory.get()` to:

```python
# my_service/app.py
server = VsServerFactory.get("fastapi", config)  # → app_import = my_service.app:server
server.run()
```

If `app_import` is not set, vs-server will attempt to auto-detect it and log it at startup. Copy the logged value into your config to make it explicit.

**Custom server implementations** follow the same pattern — add a `[my_framework]` section in `config.ini` for any framework-specific keys and read them in your `VsServer` subclass.

**`config.ini` example:**

```ini
[server]
name = my-service
version = 1.0.0
host = 0.0.0.0
port = 8000
workers = 2
ssl_certfile = certs/server.crt
ssl_keyfile = certs/server.key

[api]
cors_origins = https://app.example.com,https://admin.example.com

[logging]
level = INFO
file_path = ./logs/service.log
```

---

## Quick Start

```python
from vs_common.config.vs_ini_config import VsIniConfig
from vs_common.log.vs_log_manager import VsLogManager
from vs_server.server.vs_fast_api_server import VsFastApiServer  # noqa — auto-registers "fastapi"
from vs_server.factory.vs_server_factory import VsServerFactory
from vs_server.decorator.vs_server_registry import server_registry

import my_service.controllers  # noqa — triggers @controller registration


@server_registry(hooks="my_service.lifecycle")
def main():
    config = VsIniConfig("config.ini")
    VsLogManager.init_from_config(config)  # reads the [logging] section

    server = VsServerFactory.get("fastapi", config)
    server.add_controller(UserController())
    server.run()


if __name__ == "__main__":
    main()
```

**Logging in worker processes:** vs-common does not set up logging on its own. With `fastapi.workers > 1` or `fastapi.reload = true`, Uvicorn imports the app afresh in each worker, and `main()` never runs there. To cover that, the server's startup calls `VsLogManager.init_from_config(config)` in any process where logging is not set up yet. An explicit `VsLogManager.init(...)` made earlier in the same process always wins.

---

## How It All Fits Together

```
Application Startup
    └── import VsFastApiServer          # auto-registers "fastapi" into VsServerFactory

@server_registry(hooks="my_service.lifecycle")
    └── imports my_service.lifecycle    # @startup / @shutdown self-register into hook lists

VsServerFactory.get("fastapi", config)
    ├── reads name/version/host/port/TLS from config.ini
    ├── wires CORS, exception handlers, lifespan
    └── exposes /, /health  (+ /stream-docs once a WS/SSE handler is registered)

server.get_app().add_middleware(VsDbMiddleware)   # register manually if using vs-db

server.add_controller(UserController())
    └── reads @controller + @get/@post/... → wires FastAPI router

server.run()
    ├── calls @startup hooks in order
    ├── starts uvicorn
    └── calls @shutdown hooks on stop
```

---

## Standalone Route Functions

HTTP verb decorators can be applied to plain functions outside any class. Decorate the function and place it in a package passed to `server_registry(routes=[...])` — no manual registration needed.

```python
# my_service/routes.py
from vs_server.decorator.vs_controller_decorator import get, post, delete

@get("/users", response_model=list[UserResponse])
async def list_users():
    ...

@post("/users", status_code=201, response_model=UserResponse)
async def create_user(body: UserRequest):
    ...

@delete("/users/{user_id}", status_code=204)
async def delete_user(user_id: str):
    ...
```

```python
@server_registry(
    hooks="my_service.lifecycle",
    routes=["my_service.routes", "my_service.admin.routes"],
)
def main():
    server = VsServerFactory.get("fastapi", config)
    server.run()
```

The scanner walks each package in `routes`, finds all functions decorated with `@get`/`@post`/`@put`/`@delete`/`@patch`, and wires them into the server automatically at startup.

Guards work the same way as on controller methods:

```python
@get("/admin/report", guards=[require_admin_role])
async def get_report():
    ...
```

---

## Request and Response Models

All request bodies and response models must be Pydantic models — not SQLAlchemy entities or plain dicts. This is a hard requirement of FastAPI and applies to all server implementations built on vs-server.

```python
from pydantic import BaseModel

class UserRequest(BaseModel):
    name: str
    email: str

class UserResponse(BaseModel):
    id: str
    name: str
    email: str

    model_config = {"from_attributes": True}
```

The mapping between your SQLAlchemy entity and your Pydantic schema is your responsibility:

```
Request (Pydantic) → Service → Entity (SQLAlchemy) → DB
DB → Entity (SQLAlchemy) → Service → Response (Pydantic)
```

Never pass a SQLAlchemy entity as `response_model` — FastAPI will reject it at startup. Never return a SQLAlchemy entity directly from a route — serialize it first.

Keeping schemas separate from entities is intentional: the DB schema and API schema can evolve independently, and sensitive fields (e.g. `password`) are excluded from responses by default.

---

## HTTP Controllers

Annotate a class with `@controller` and methods with HTTP verb decorators.

```python
from vs_server.decorator.vs_controller_decorator import controller, get, post, put, delete, patch
from pydantic import BaseModel

class UserRequest(BaseModel):
    name: str
    email: str

@controller("/users", description="User management endpoints")
class UserController:

    @get("", response_model=list[UserResponse])
    async def list_users(self): ...

    @get("/{user_id}", response_model=UserResponse)
    async def get_user(self, user_id: str): ...

    @post("", status_code=201, response_model=UserResponse)
    async def create_user(self, body: UserRequest): ...

    @put("/{user_id}", response_model=UserResponse)
    async def update_user(self, user_id: str, body: UserRequest): ...

    @delete("/{user_id}", status_code=204)
    async def delete_user(self, user_id: str): ...
```

Register via `server.add_controller()`:

```python
server.add_controller(UserController())
```

All FastAPI route parameters (`response_model`, `status_code`, `tags`, `summary`, etc.) pass through via `**kwargs`.

### @controller parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `path` | `str` | Yes | — | URL prefix for all routes in this controller |
| `description` | `str` | No | `""` | Tag description shown in Swagger |
| `guards` | `List[Callable]` | No | `[]` | Applied to every route in this controller |

### HTTP verb decorators

| Decorator | HTTP Method |
|---|---|
| `@get(path, summary, description, guards=[], **kwargs)` | GET |
| `@post(path, summary, description, guards=[], **kwargs)` | POST |
| `@put(path, summary, description, guards=[], **kwargs)` | PUT |
| `@delete(path, summary, description, guards=[], **kwargs)` | DELETE |
| `@patch(path, summary, description, guards=[], **kwargs)` | PATCH |

Guards on a method are merged with controller-level guards — both run.

---

## WebSocket

Annotate a class with `@websocket` and message handlers with `@on_message`.

```python
from vs_server.decorator.vs_websocket_decorator import websocket, on_message

@websocket("/ws/chat", description="Real-time chat over WebSocket")
class ChatHandler:

    @on_message(
        description="Handle incoming chat message",
        args={"text": "Message text", "room": "Target room ID"},
    )
    async def handle_message(self, data: dict):
        text = data.get("text")
        # process and send response

    @on_message(description="Handle ping")
    async def handle_ping(self, data: dict):
        ...
```

Register via `server.add_websocket()`:

```python
server.add_websocket(ChatHandler())
```

**Connection lifecycle:** Guards run at connect time. If any guard raises or returns `False`, the connection is closed with code `1008` before `accept()`. Message guards run per-message before the handler; one that raises or returns `False` closes the connection with `1008` and the handler does not run. Guards may be sync or async. With `enable_security()` on, the handshake credentials are re-validated every `server.ws_reauth_interval_seconds` (default 300); once they fail, or the check itself errors, the connection is closed with `1008`. A client cannot refresh its token on an open socket: it reconnects with the new one.

**Handshake checks:** With `enable_security()` on, the handshake's `Origin` must be listed in `api.cors_origins` or match the server's own host, and the security filter authenticates the handshake headers. Either failure refuses the connection with `1008`. Browsers cannot set `Authorization` on a WebSocket, so they offer the token as a subprotocol instead; the server reads it as `Authorization: Bearer <token>` and echoes `bearer` back on accept:

```javascript
const socket = new WebSocket("wss://api.example.com/ws/chat", ["bearer", accessToken]);
```

### @websocket parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `path` | `str` | Yes | — | WebSocket URL path |
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run at connection time — signature: `async guard(websocket)` |

### @on_message parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `args` | `dict` | No | `{}` | Argument descriptions shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run per-message — signature: `async guard(websocket, data)` |

---

## Server-Sent Events (SSE)

Annotate a class with `@sse` and the stream method with `@sse_stream`.

```python
from fastapi import Request
from vs_server.decorator.vs_sse_decorator import sse, sse_stream

@sse("/events/notifications", description="Notification stream")
class NotificationStream:

    @sse_stream(
        description="Stream live notifications",
        args={"user_id": "Filter notifications for this user"},
    )
    async def stream(self, request: Request):
        while not await request.is_disconnected():
            event = await notification_queue.get()
            yield event
```

Register via `server.add_sse()`:

```python
server.add_sse(NotificationStream())
```

The stream method must be an async generator. Each value yielded is sent as a `data: <value>\n\n` SSE event.

### VsSseEvent — named events and resumable streams

A bare `yield` sends a lone `data:` line, which is all most streams need. Yield a `VsSseEvent` instead when the client has to **dispatch on the kind of frame**, or reconnect without losing its place.

```python
from vs_server.decorator.vs_sse_decorator import sse, sse_stream
from vs_server.schema.vs_sse_event import VsSseEvent

@sse("/v1/agent/stream", description="Agent analysis and answers")
class AgentStream:

    @sse_stream(description="Everything this user's agents are saying")
    async def stream(self, request: Request):
        async for frame in read_user_stream(request):
            yield VsSseEvent(
                data=frame.payload,     # dict or list — JSON-encoded for you
                event=frame.kind,       # "analysis" or "response"
                id=frame.stream_id,     # what Last-Event-ID sends back on reconnect
            )
```

| Field | Type | Sent as | Purpose |
|---|---|---|---|
| `data` | `Any` | `data:` | The payload. Strings go as-is, anything else is JSON-encoded. Multi-line payloads become one `data:` line each, per the spec; `\r`, `\n` and `\r\n` all count as line breaks, so streamed text cannot forge a field or a frame. Line breaks are removed from `event` and `id`. A bare `yield` is rendered the same way. |
| `event` | `str` | `event:` | Names the frame, so `addEventListener("analysis", ...)` works |
| `id` | `str` | `id:` | The browser echoes the last one back as `Last-Event-ID` when it reconnects |
| `retry_ms` | `int` | `retry:` | How long the client waits before reconnecting |
| `comment` | `str` | `:` | Ignored by clients — used for keep-alives |

On the client, the frames arrive already separated:

```javascript
const stream = new EventSource("/v1/agent/stream");
stream.addEventListener("analysis", e => showThinking(JSON.parse(e.data)));
stream.addEventListener("response", e => showAnswer(JSON.parse(e.data)));
```

**Keep-alives.** `VsSseEvent.keep_alive()` yields a comment-only frame. Proxies close connections that look idle, and a stream waiting on a slow agent looks exactly like one — send one every 15–30 seconds:

```python
try:
    frame = await asyncio.wait_for(queue.get(), timeout=20)
    yield VsSseEvent(data=frame.payload, event=frame.kind, id=frame.id)
except asyncio.TimeoutError:
    yield VsSseEvent.keep_alive()
```

**Resuming.** Give each frame an `id` and a reconnecting browser sends `Last-Event-ID` automatically. Read it off the request and replay from that point rather than from the beginning:

```python
async def stream(self, request: Request):
    resume_from = request.headers.get("Last-Event-ID")
    async for frame in read_user_stream(request, after=resume_from):
        yield VsSseEvent(data=frame.payload, event=frame.kind, id=frame.id)
```

Mixing the two styles is fine — a stream can yield plain strings and `VsSseEvent`s in the same generator.

### @sse parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `path` | `str` | Yes | — | SSE endpoint URL path |
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run before the stream starts |

### @sse_stream parameters

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `args` | `dict` | No | `{}` | Argument descriptions shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run before the stream starts |

---

## Multi-Protocol Classes

A single class can carry HTTP, WebSocket, and SSE by stacking decorators:

```python
from vs_server.decorator.vs_controller_decorator import controller, get
from vs_server.decorator.vs_websocket_decorator import websocket, on_message
from vs_server.decorator.vs_sse_decorator import sse, sse_stream

@controller("/chat", description="Chat HTTP endpoints")
@websocket("/ws/chat", description="Chat WebSocket")
@sse("/events/chat", description="Chat event stream")
class ChatHandler:

    @get("/history")
    async def get_history(self): ...

    @on_message(description="Send a message")
    async def handle_message(self, data: dict): ...

    @sse_stream(description="Live chat events")
    async def stream(self, request): ...
```

Register each protocol separately:

```python
handler = ChatHandler()
server.add_controller(handler)
server.add_websocket(handler)
server.add_sse(handler)
```

---

## Guards

Guards are async callables that run before a route, WebSocket connection, or SSE stream. If a guard raises, the request is rejected.

```python
from vs_security.guard.vs_security_factory import VsSecurityFactory

# controller-level guard — applies to all routes
@controller("/admin", guards=[VsSecurityFactory.get()])
class AdminController:

    # route-level guard — merged with controller guards
    @get("/report", guards=[require_admin_role])
    async def get_report(self): ...
```

**Guard signature by protocol:**

| Protocol | Point | Guard signature |
|---|---|---|
| HTTP | Per-request | `async def guard() -> None` (FastAPI `Depends`) |
| WebSocket | At connect | `async def guard(websocket: WebSocket) -> None` |
| WebSocket | Per-message | `async def guard(websocket: WebSocket, data: dict) -> None` |
| SSE | Before stream | `async def guard() -> None` (FastAPI `Depends`) |

Guards that raise `PermissionError` are handled by the built-in exception handler and return a `403` response on HTTP, with the fixed message `Access denied` — the guard's own text is logged, not sent. To give the client a reason, raise `ForbiddenException("...")` from the guard instead. On WebSocket, the connection is closed with code `1008`; a WebSocket guard may also deny by returning `False` (returning nothing or `True` allows).

---

## Lifecycle Hooks

Use `@startup` and `@shutdown` to run code when the server starts and stops.

```python
from vs_common.config.vs_ini_config import VsIniConfig
from vs_server.lifecycle.vs_lifecycle import startup, shutdown
from vs_db.session.vs_db_session_factory import VsDbSessionFactory

config = VsIniConfig("config.ini")
db = VsDbSessionFactory(config)

@startup
async def create_tables():
    await db.create_tables()

@shutdown
async def close_connections():
    await db.dispose()
```

Hooks self-register into global lists at import time. They run in registration order. Both sync and async hooks are supported.

Register hook modules with `server_registry` so they are imported before the server starts:

```python
from vs_server.decorator.vs_server_registry import server_registry

@server_registry(hooks="my_service.lifecycle")
def main():
    ...
```

`VsServer.startup()` iterates `_startup_hooks`. `VsServer.shutdown()` iterates `_shutdown_hooks`.

---

## VsServerFactory and @server

`VsServerFactory` maps string keys to `VsServer` subclasses. Register once, retrieve by key anywhere.

```python
from vs_server.factory.vs_server_factory import VsServerFactory
from vs_server.server.vs_fast_api_server import VsFastApiServer  # noqa — auto-registers "fastapi"

server = VsServerFactory.get("fastapi", config)
```

### Adding a custom server implementation

```python
from vs_server.server.vs_server import VsServer
from vs_server.decorator.vs_server_decorator import server
from vs_server.factory.vs_server_factory import VsServerFactory


@server("flask")
class VsFlaskServer(VsServer):

    def add_controller(self, instance, guards=None): ...
    def add_router(self, router, prefix=""): ...
    def add_websocket(self, instance): ...
    def add_sse(self, instance): ...
    def get_app(self): ...
    def run(self): ...


VsServerFactory.register("flask", VsFlaskServer)
```

Or scan the package automatically with `server_registry`:

```python
@server_registry(server="my_pkg.server")
def main():
    server = VsServerFactory.get("flask", config)
    server.run()
```

---

## server_registry

Scans packages for `@server`-decorated classes, `@startup`/`@shutdown` hook functions, standalone route functions, and `@controller` classes. Works as a decorator on `main()` or as a plain call.

```python
from vs_server.decorator.vs_server_registry import server_registry

@server_registry(
    hooks="my_service.lifecycle",
    routes=["my_service.api"],          # every controller and route function under my_service.api
)
def main():
    server = VsServerFactory.get("fastapi", config)
    server.run()
```

| Parameter | Type | Description |
|---|---|---|
| `server` | `str` | Package path to scan for `@server`-decorated classes. Not needed for `"fastapi"` — it auto-registers on import. |
| `hooks` | `str` | Package path to import for `@startup`/`@shutdown` registration. |
| `routes` | `List[str]` | Packages or glob patterns to scan for standalone `@get`/`@post`/... functions and `@controller` classes. Both are wired into the server when it is created. |
| `controller_factory` | `Callable[[type], object]` | Optional. Builds each scanned controller, e.g. `lambda cls: container.resolve(cls)`. Without it, controllers are built with no arguments. |

**Package or pattern.** A plain entry such as `"my_service.api"` scans that package and everything under it. An entry with `*`, `?` or `[...]` is a glob on the dotted module name, matched one segment at a time:

| Entry | Scans |
|---|---|
| `"my_service.api"` | `my_service.api` and every module below it |
| `"my_service.api.*"` | Direct children of `my_service.api` only |
| `"my_service.*.controllers"` | Every `controllers` module one level below `my_service` |
| `"my_service.api.*_controller"` | Only modules named like `user_controller` |

A pattern must start with a package name, and one that matches no modules raises `ImportError`, so a typo is not mistaken for an empty API.

**How scanned controllers are built.**

- A controller counts only in the module that defines it. Importing it into another module does not register it twice.
- Without `controller_factory`, a controller whose constructor can be called with no arguments, including one whose parameters all have defaults, is built and added automatically.
- A controller that needs constructor arguments is left for you: call `server.add_controller(UserController(repo))`. If you don't, `run()`, `run_async()` and worker startup raise `RuntimeError` naming the class, instead of serving without its routes.
- With `controller_factory`, every scanned controller is built by the factory.
- Calling `add_controller()` for a class the scan already added logs a warning and is skipped, so no route is served twice.

---

## HTTPS / TLS

Set `ssl_certfile` and `ssl_keyfile` in `config.ini`. No code changes required.

```ini
[server]
ssl_certfile = certs/server.crt
ssl_keyfile = certs/server.key
ssl_keyfile_password = optional-passphrase
```

TLS is enabled when both `ssl_certfile` and `ssl_keyfile` are present. The startup banner prints `TLS: enabled`.

---

## Built-in Endpoints

Every `VsFastApiServer` instance exposes three endpoints automatically:

| Endpoint | Description |
|---|---|
| `GET /` | Returns `{"service": name, "version": version, "status": "running"}` |
| `GET /health` | Returns `VsServerHealth` with overall status, uptime, cache, and dependency health |
| `GET /docs` | Swagger UI — hidden when `server.docs_enabled = false` |
| `GET /redoc` | ReDoc UI — hidden when `server.docs_enabled = false` |
| `GET /stream-docs` | Custom HTML docs page for WebSocket and SSE endpoints — registered only once at least one `@websocket` or `@sse` handler is added, and hidden when `server.docs_enabled = false` |

If `server.base_url` is set in `config.ini`, `/`, `/health`, and `/stream-docs` are prefixed with it.

Set `server.docs_enabled = false` in production to disable all four documentation endpoints at once.

With `enable_security()` on, these endpoints require credentials. They describe every route, so they are only exempt from authentication when `server.docs_public = true`.

### /health response

```json
{
  "status": "healthy",
  "name": "my-service",
  "version": "1.0.0",
  "uptime_seconds": 142.3,
  "cache": "healthy",
  "instance_id": "hostname",
  "dependencies": {
    "database": "healthy"
  },
  "timestamp": "2026-01-01T00:00:00Z"
}
```

**Overall status logic:**

| Condition | Status |
|---|---|
| All dependencies healthy | `healthy` |
| Some healthy, some unhealthy | `degraded` |
| All unhealthy | `unhealthy` |

Override `_check_dependencies()` in a `VsServer` subclass to include custom dependency checks:

```python
async def _check_dependencies(self) -> dict:
    try:
        await db.execute("SELECT 1")
        return {"database": "healthy"}
    except Exception:
        return {"database": "unhealthy"}
```

---

## Documentation

| URL | Content |
|---|---|
| `/docs` | Swagger UI — HTTP endpoints only (FastAPI native) |
| `/stream-docs` | Custom HTML page — WebSocket and SSE endpoints |

HTTP endpoints are documented automatically via FastAPI's Swagger UI. WebSocket and SSE endpoints are not supported by OpenAPI — they appear in `/stream-docs` instead, generated by `VsDocsRenderer`.

`get_docs_url()` returns the framework-native docs URL (`"/docs"` for FastAPI). Override to change or suppress it.

---

## Security

`vs-server` provides the HTTP-side of security — token extraction, middleware wiring, and request abstraction. The auth logic (session validation, JWT, user loading) lives in `vs-security`.

### enable_security()

Call `enable_security()` after creating the server. It registers a middleware that runs before every request, and automatically configures Swagger UI with a Bearer token "Authorize" button. Only secured endpoints show the lock icon — excluded paths do not.

```python
server = VsServerFactory.get("fastapi", config)
server.enable_security()   # default: VsBearerTokenFilter, all routes secured
server.run()
```

With excluded paths (always public, no auth required):

```python
server.enable_security(VsBearerTokenFilter(exclude_paths=["/health", "/auth/login", "/auth/refresh"]))
```

With a custom filter:

```python
server.enable_security(MyFilter(exclude_paths=["/health"]))
```

With a request enricher, which runs after the filter and before dispatch:

```python
server.enable_security(VsBearerTokenFilter(), request_enricher=my_enricher)
```

`/docs`, `/redoc`, `/openapi.json`, and `/stream-docs` need credentials like any other route. They are added to the filter's `exclude_paths` only when `server.docs_public = true` and docs are enabled. Authentication failures return `401` with `{"detail": "Authentication failed"}`.

### enable_request_context()

Binds a fresh auth context for each request and optionally runs a `request_enricher`, without authenticating. Use it when a service has no auth but still needs request-scoped context. `enable_security()` calls this internally.

```python
server.enable_request_context(request_enricher=my_enricher)
```

To disable Swagger UI entirely (e.g. in production), set `server.docs_enabled = false` in `config.ini`.

### VsSecurityFilter

Extend this to implement your own auth mechanism — API key, session cookie, mTLS, anything. Call `set_auth_context(context)` when done.

```python
from vs_server.filter.vs_security_filter import VsSecurityFilter
from vs_server.filter.vs_request import VsRequest
from vs_security.guard.vs_security import set_auth_context

class ApiKeyFilter(VsSecurityFilter):

    async def do_filter(self, request: VsRequest) -> None:
        key = request.get_header("X-Api-Key")
        if not key:
            raise VsAuthenticationError("Missing API key")
        context = await key_repo.validate(key)
        set_auth_context(context)

server.enable_security(ApiKeyFilter(exclude_paths=["/health"]))
```

`process()` in the base class handles `exclude_paths` — your `do_filter()` only sees requests that need auth.

### VsBearerTokenFilter

Built-in filter that builds a `VsAuthRequest` (headers, path, method — no payload, so the body is not read before the token is checked), authenticates it with `VsBearerTokenAuthenticator` backed by `VsAuthManager.get_instance().session`, runs `enrich()`, and sets the context. Used by default when `enable_security()` is called with no argument. `enrich()` must return a `VsAuthContext`, or a `TypeError` is raised.

Requires `vs-security` and `VsAuthManager.init()` to be called at startup.

Override `enrich()` to fetch fresh user details from DB after token validation and add them to the context — without touching every handler:

```python
from vs_server.filter.vs_bearer_token_filter import VsBearerTokenFilter

class MyFilter(VsBearerTokenFilter):

    def __init__(self, user_repo):
        super().__init__(exclude_paths=["/health", "/auth/login"])
        self._user_repo = user_repo

    async def enrich(self, context: AppAuthContext) -> AppAuthContext:
        user = await self._user_repo.find_by_id(context.user_id)
        context.metadata["email"] = user.email
        context.metadata["plan"] = user.plan
        return context

server.enable_security(MyFilter(user_repo=UserRepo()))
```

`enrich()` default is a no-op — only override when you need live data beyond what's in the JWT.

### VsRequest / VsFastApiRequest

`VsRequest` is the framework-agnostic request abstraction passed to `do_filter()`. `VsFastApiRequest` wraps FastAPI's `Request`.

| Method | Returns | Description |
|---|---|---|
| `get_header(name)` | `Optional[str]` | Returns the header value, case-insensitive |
| `headers` | `Dict[str, str]` | All request headers |
| `get_path()` | `str` | Request URL path (e.g. `/users/me`) |
| `get_method()` | `str` | HTTP method. Base default is `""` |
| `await get_payload()` | `Any` | Parsed JSON body, or `None`. Base default is `None`; `VsFastApiRequest` parses `application/json` and `+json` bodies |

Implement `VsRequest` when adding a non-FastAPI server — wrap the native request object and pass it to `VsSecurityFilter.process()`. Only `get_header`, `headers`, and `get_path` are abstract.

### VsRequestAuthFilter

Generic filter that delegates to any `vs-security` `VsRequestAuthenticator`. Use it to plug in a custom authenticator without writing a filter subclass.

```python
from vs_server.filter.vs_request_auth_filter import VsRequestAuthFilter

server.enable_security(VsRequestAuthFilter(my_authenticator, exclude_paths=["/health"]))
```

It builds a `VsAuthRequest` (headers, path, method, payload), calls `authenticator.authenticate()`, and sets the returned context. A non-`VsAuthContext` result raises `TypeError`. Requires `vs-security`.

---

## Using with vs-db

`vs-server` does not depend on `vs-db`; install it alongside when a service needs a database. This section describes **vs-db 0.3.0 or later**, which needs `vs-common` 0.2.0 or later.

```bash
pip install "vs-db[mysql]>=0.3.0"
```

Initialize `VsDbSessionFactory` before creating the server, then register `VsDbMiddleware` explicitly:

```python
from vs_common.config.vs_ini_config import VsIniConfig
from vs_db.session.vs_data_source import VsDataSource
from vs_db.session.vs_db_session_factory import VsDbSessionFactory
from vs_db.middleware.vs_db_middleware import VsDbMiddleware
from vs_server.lifecycle.vs_lifecycle import startup, shutdown
from vs_server.server.vs_fast_api_server import VsFastApiServer  # noqa — auto-registers "fastapi"
from vs_server.factory.vs_server_factory import VsServerFactory

config = VsIniConfig("config.ini")
db = VsDbSessionFactory(config, entities=["my_service.models"])

@startup
async def prepare_database():
    await db.create_tables()
    await db.populate_data()        # only if you use @db_install data versions

@shutdown
async def close_database():
    await VsDataSource.close_all()

def main():
    server = VsServerFactory.get("fastapi", config)
    server.get_app().add_middleware(VsDbMiddleware)
    server.add_controller(UserController())
    server.run()
```

`VsDbMiddleware` must be registered before `server.run()` — middleware cannot be added after the server starts accepting requests. The `[database]` settings it reads are described in the vs-db documentation.

### Error responses roll back the request

`VsDbMiddleware` gives each request one transaction and decides by the **response status**: below 400 it commits, 400 or above it rolls back. vs-server's exception handlers turn exceptions into ordinary JSON responses before the middleware sees them, so every handled error rolls back what the request wrote:

| Raised in a controller | vs-server response | Request's writes |
|---|---|---|
| Nothing — normal return | 2xx | Committed |
| `NotFoundException`, `ValidationException`, `ForbiddenException`, other `VsAPIException` | Its status (4xx / 5xx) | Rolled back |
| Any `VsBaseException`, e.g. vs-security auth errors | `exc.status_code`, default 500 (message sent only for 4xx) | Rolled back |
| `ValueError` / `PermissionError` / request validation error | 400 / 403 / 400 | Rolled back |
| Any other exception | 500 | Rolled back |

```python
@controller("/projects")
class ProjectController:

    @post("/{project_id}/members")
    async def add_member(self, project_id: int, body: AddMember):
        await member_repo.create(Member(project_id=project_id, user_id=body.user_id))
        project = await project_repo.get_by_id(project_id)
        if project.owner_id != body.requested_by:
            raise ForbiddenException()        # 403 — the member row is rolled back
        return {"added": True}
```

> With vs-db versions before 0.3.0 the middleware committed whenever no exception escaped the handler. Because vs-server converts exceptions into responses, every error path above used to **commit** its partial writes.

**Keeping a write on a failed request** — a failed-login counter before a 401, an audit record of a rejected action — needs its own transaction:

```python
from vs_db.decorator.vs_db_decorator import transactional, Propagation

@transactional(propagation=Propagation.REQUIRES_NEW)
async def record_failed_login(self, email: str) -> None:
    await self.attempt_repo.create(LoginAttempt(email=email, ok=False))   # commits even on a 401
```

To change the rule for a whole service, pass `commit_on_status`:

```python
server.get_app().add_middleware(VsDbMiddleware, commit_on_status=lambda status: status < 500)
```

### Long-running handlers

A request's transaction holds a pooled database connection from its first query until the response. A controller that calls an LLM or another slow service after querying keeps that connection idle, and a handful of such requests can exhaust the pool. Either commit before the slow call, or let each `@transactional` call own its transaction:

```python
from vs_db.transaction.vs_transaction_manager import VsTransactionManager

conversation = await conversation_repo.get_by_id(conversation_id)
await VsTransactionManager.commit()                 # releases the connection
answer = await llm.complete(conversation.messages)
```

```python
server.get_app().add_middleware(VsDbMiddleware, transaction_scope="call")
```

With `transaction_scope="call"` a failed request no longer rolls back calls that already finished. vs-db logs a warning when a connection is held longer than `database.connection_hold_warning_seconds` (default 5), which shows which endpoints need this.

### Middleware order with security

Starlette runs the middleware added **last** as the outermost layer. If `server.get_app().add_middleware(VsDbMiddleware)` is called after `enable_security()` / `enable_request_context()`, the database session wraps authentication: a request enricher's queries join the request's transaction, and a request rejected with 401 rolls them back. If it is called before, authentication runs first and an enricher's queries get their own short transactions.

Prefer registering `VsDbMiddleware` **before** enabling security when a controller uses `@transactional(isolation=...)`. A transaction's isolation level can only be set before its first query, so an enricher query inside the request transaction makes such a controller fail with `IsolationLevelError` (a 500 response).

---

## Error Handling

`vs-server` has two tiers of exception handling, both producing the same JSON shape:

- **`VsAPIException`** — server-owned exceptions with an explicit `error_code` and `details` dict. Use these when you want full control over the error code and extra context.
- **`VsBaseException`** subclasses — any exception from any VS library (e.g. `VsAuthenticationError` from `vs-security`) is handled automatically via duck-typing. The handler reads `status_code` if present (defaults to 500) and derives the error code from the class name. Only a 4xx exception's message is sent to the client; see below.

`vs-server` has no direct dependency on `vs-security` — the duck-typing approach means all VS library exceptions work automatically.

Raise exceptions from `vs_server.schema.exceptions` inside controllers — the built-in handlers convert them to structured JSON responses automatically.

```python
from vs_server.schema.exceptions import NotFoundException, ValidationException

@controller("/users")
class UserController:

    @get("/{user_id}")
    async def get_user(self, user_id: str):
        user = await repo.find(user_id)
        if user is None:
            raise NotFoundException(f"User '{user_id}' not found")
        return user
```

**Error response format:**

```json
{
  "success": false,
  "error": {
    "code": "NOT_FOUND",
    "message": "User 'abc' not found",
    "details": {}
  }
}
```

**Built-in exception types:**

| Exception | HTTP Status | Error Code | Default Message |
|---|---|---|---|
| `NotFoundException` | 404 | `NOT_FOUND` | `Resource not found` |
| `ValidationException` | 400 | `VALIDATION_ERROR` | `Invalid request` |
| `UnauthorizedException` | 401 | `UNAUTHORIZED` | `Authentication required` |
| `ForbiddenException` | 403 | `FORBIDDEN` | `Access denied` |
| `InternalServerException` | 500 | `INTERNAL_ERROR` | `Internal server error` |
| `ServiceUnavailableException` | 503 | `SERVICE_UNAVAILABLE` | `Service unavailable` |
| `RateLimitException` | 429 | `RATE_LIMIT_EXCEEDED` | `Rate limit exceeded` |
| `TimeoutException` | 504 | `TIMEOUT_ERROR` | `Request timed out` |

All extend `VsAPIException`, which extends `VsBaseException`. Catch by either base type to handle errors uniformly.

**`VsBaseException` subclasses are handled automatically:**

Any exception that extends `VsBaseException` (from `vs-common`) is caught and converted to a JSON error response. The handler uses `getattr(exc, 'status_code', 500)` — if the exception carries a `status_code` (e.g. auth errors from `vs-security`), that is used; otherwise it defaults to 500. An exception with a 4xx `status_code` is treated as written for the caller and its message is sent. Any other `VsBaseException` is an internal failure: the client gets `INTERNAL_ERROR` with a fixed message and the original text is logged, because it can carry connection strings, paths or SQL. To send a 5xx message on purpose, raise a `VsAPIException`. For 4xx exceptions the error code is derived from the class name — e.g. `VsInvalidCredentialsError` → `INVALID_CREDENTIALS`, `VsTokenExpiredError` → `TOKEN_EXPIRED`.

`vs-server` does not depend on `vs-security` — the duck-typing approach means any library's exceptions work automatically as long as they extend `VsBaseException` and optionally set `status_code`.

```python
@post("/auth/login", response_model=LoginResponse)
async def login(body: LoginRequest):
    # VsInvalidCredentialsError → 401 INVALID_CREDENTIALS automatically
    session = await VsAuthManager.get_instance().authenticate(body.type, body)
    return LoginResponse(access_token=session.access_token, refresh_token=session.refresh_token)
```

**Automatically handled Python exceptions:**

| Exception | HTTP Status | Message sent to the client |
|---|---|---|
| `VsBaseException` (and subclasses) | Derived from `exc.status_code` | The exception's message for 4xx; a fixed message otherwise |
| `PermissionError` | 403 | `Access denied` |
| `ValueError` | 400 | `Invalid request` |
| `fastapi.RequestValidationError` | 400 | `Invalid request data`, with field-level detail |
| Any other `Exception` | 500 | `An unexpected error occurred` |

`ValueError` and `PermissionError` keep their status codes, but their text is **not** sent to the client. Both are raised by libraries and by the operating system as well as by your code — a database library's argument check, a file the process may not open — and that text can name internal columns, file paths or values. The original message, the request path and where the exception was raised are logged at `WARNING` on the `vs_server.schema.exceptions` logger instead:

```
GET /users/42 -> 400: ValueError raised at /app/my_service/users.py:31: invalid literal for int() with base 10: 'abc'
```

To send a message to the client, raise a `vs-server` exception, which is meant for that:

```python
raise ValidationException("Email address is already registered")   # 400, message shown
raise ForbiddenException("Only project owners can add members")    # 403, message shown
```

---

## Extending vs-server

Implement `VsServer` to add support for any framework. The abstract interface is:

```python
from vs_server.server.vs_server import VsServer
from vs_common.config.vs_base_config import VsBaseConfig

class MyServer(VsServer):

    def __init__(self, config: VsBaseConfig):
        super().__init__(config)

    def add_controller(self, instance, guards=None) -> None: ...
    def add_router(self, router, prefix: str = "") -> None: ...
    def add_websocket(self, instance) -> None: ...
    def add_sse(self, instance) -> None: ...
    def get_app(self): ...
    def run(self) -> None: ...
```

Override template methods to customise behaviour:

| Method | Default | Override to |
|---|---|---|
| `get_host()` | Reads `server.host` | Hard-code or compute the bind address |
| `get_port()` | Reads `server.port` | Hard-code or compute the bind port |
| `get_reload()` | FastAPI only — reads `fastapi.reload` | Force hot-reload on/off |
| `get_workers()` | FastAPI only — reads `fastapi.workers` | Set worker count programmatically |
| `get_log_level()` | FastAPI only — reads `fastapi.log_level` | Set log level programmatically |
| `get_app_import()` | FastAPI only — reads `fastapi.app_import` | Return import string for multi-worker mode |
| `get_ssl_certfile()` | Reads `server.ssl_certfile` | Load cert from a secret store |
| `get_ssl_keyfile()` | Reads `server.ssl_keyfile` | Load key from a secret store |
| `get_ssl_keyfile_password()` | Reads `server.ssl_keyfile_password` | Load password from a secret store |
| `is_docs_enabled()` | Reads `server.docs_enabled` | Toggle docs based on environment or role |
| `is_docs_public()` | Reads `server.docs_public` | Decide whether docs skip authentication when security is enabled |
| `startup()` | Logs + runs `@startup` hooks | Add custom startup logic. Call `super().startup()` to keep hooks. |
| `shutdown()` | Runs `@shutdown` hooks + logs | Add custom shutdown logic. Call `super().shutdown()` to keep hooks. |
| `get_docs_url()` | Returns `None` | Return the framework-native docs URL |
| `_check_dependencies()` | Returns `{}` | Return `dict[str, "healthy" \| "unhealthy"]` merged into `/health` |
| `_register_middleware(app)` | Adds CORS | Add custom middleware. Call `super()` to keep CORS. |
| `_register_exception_handlers(app)` | Adds built-in handlers | Add custom exception handlers. Call `super()` to keep built-ins. |

---

## Class Reference

---

### VsServer

Abstract base class for all server implementations. Manages config, logging, and lifecycle hooks.

**Constructor:**

| Parameter | Type | Description |
|---|---|---|
| `config` | `VsBaseConfig` | Application config — reads `server.*` keys |

**Attributes set from config:**

| Attribute | Config key | Default |
|---|---|---|
| `name` | `server.name` | `vs-server` |
| `version` | `server.version` | `0.1.0` |
| `description` | `server.description` | `App server developed by Viveka Sutra` |
| `base_url` | `server.base_url` | `""` |

**Config methods** — read from `config.ini` by default. Override any of them in a subclass to change the value without touching config:

| Method | Default config key | Default value | Description |
|---|---|---|---|
| `get_host()` | `server.host` | `127.0.0.1` | Bind address |
| `get_port()` | `server.port` | `8000` | Bind port |
| `get_ssl_certfile()` | `server.ssl_certfile` | `None` | TLS certificate path |
| `get_ssl_keyfile()` | `server.ssl_keyfile` | `None` | TLS private key path |
| `get_ssl_keyfile_password()` | `server.ssl_keyfile_password` | `None` | TLS key password |
| `is_docs_enabled()` | `server.docs_enabled` | `true` | Whether to expose documentation endpoints |

**Lifecycle methods:**

| Method | Signature | Description |
|---|---|---|
| `startup` | `async startup() -> None` | Logs startup banner, then runs all `@startup` hooks. Call `super().startup()` to keep. |
| `shutdown` | `async shutdown() -> None` | Runs all `@shutdown` hooks, then logs stop. Call `super().shutdown()` to keep. |
| `get_docs_url` | `get_docs_url() -> Optional[str]` | Returns `None`. Override to return framework-native docs URL. |
| `add_controller` | `add_controller(instance, guards=None) -> None` | Abstract. Register a `@controller` instance. |
| `add_router` | `add_router(router, prefix="") -> None` | Abstract. Register a raw framework router. |
| `add_websocket` | `add_websocket(instance) -> None` | Abstract. Register a `@websocket` instance. |
| `add_sse` | `add_sse(instance) -> None` | Abstract. Register an `@sse` instance. |
| `get_app` | `get_app() -> Any` | Abstract. Return the underlying framework app. |
| `run` | `run() -> None` | Abstract. Start the server. |
| `run_async` | `async run_async(*, stop_event=None, ready=None) -> None` | Serve on the caller's event loop. See [Async Serving on an Existing Loop](#async-serving-on-an-existing-loop). |
| `enable_security` | `enable_security(security_filter) -> None` | Register an auth filter. |
| `enable_request_context` | `enable_request_context(request_enricher=None) -> None` | Bind a per-request auth context, optionally enriched, without authentication. |

---

### VsServerFactory

Registry mapping string keys to `VsServer` subclasses. Thread-safe class-level dict.

**Methods:**

| Method | Signature | Description |
|---|---|---|
| `register` | `register(key: str, server_class: Type[VsServer]) -> None` | Register a server class. Raises `TypeError` if not a `VsServer` subclass. |
| `get` | `get(key: str, config: VsBaseConfig) -> VsServer` | Instantiate and return a server. Raises `KeyError` if key not registered. Once the server is built, also sets `config` as the application config via `VsConfigManager.init_if_absent()`. |

**Notes:**
- `VsFastApiServer` auto-registers as `"fastapi"` when its module is imported.
- `VsServerFactory.get("fastapi", config)` loads and registers the built-in adapter on first use, so no explicit import is needed.
- After `get()`, application code can read the same config anywhere with `VsConfigManager.get()` (from `vs_common.config.vs_config_manager`). An earlier explicit `VsConfigManager.init(config)` always wins, and a second server built later does not replace the first config. A server that fails to build, or an unknown key, sets nothing.

---

### VsFastApiServer

Built-in `VsServer` implementation backed by FastAPI and uvicorn. Auto-registers as `"fastapi"` on import.

**Behaviour at construction:**
- Raises `ImportError` if `fastapi` is not installed.
- Builds the FastAPI app with lifespan, CORS middleware, exception handlers, and core routes.

**Built-in routes:** `GET /`, `GET /health` (and `GET /stream-docs` once a `@websocket`/`@sse` handler is added).

**Methods (beyond `VsServer` contract):**

| Method | Description |
|---|---|
| `enable_security(security_filter=None, request_enricher=None)` | Register security middleware. Defaults to `VsBearerTokenFilter`. Pass a custom `VsSecurityFilter` subclass for any other mechanism. Docs paths are excluded only when `server.docs_public = true`. |
| `enable_request_context(request_enricher=None, *, security_filter=None)` | Register the per-request auth-context middleware. Used internally by `enable_security()`; call directly to enrich context without authenticating. |
| `get_reload()` | Reads `fastapi.reload` (default `false`) |
| `get_workers()` | Reads `fastapi.workers` (default `1`) |
| `get_log_level()` | Reads `fastapi.log_level` (default `info`) |
| `get_app_import()` | Reads `fastapi.app_import` |
| `get_docs_url()` | Returns `"/docs"` |
| `_check_dependencies()` | Override to add custom dependency health checks |
| `_register_middleware(app)` | Adds CORS. Call `super()` to keep it. |
| `_register_exception_handlers(app)` | Adds built-in handlers. Call `super()` to keep them. |

**Notes:**
- `reload=True` and `workers > 1` are mutually exclusive. If `reload` is `true`, `workers` is ignored.
- TLS is enabled when both `ssl_certfile` and `ssl_keyfile` are set.
- `VsDbMiddleware` must be registered manually: `server.get_app().add_middleware(VsDbMiddleware)`.

---

### `@server`

Decorator. Marks a class as a named server implementation. Validates that it extends `VsServer`.

**Parameters:**

| Parameter | Type | Required | Description |
|---|---|---|---|
| `key` | `str` | Yes | Registry key used with `VsServerFactory.get(key, config)` |

---

### `server_registry`

Scans packages for `@server`-decorated classes and `@startup`/`@shutdown` hook functions. Works as a function decorator or a plain call. All parameters are optional.

**Parameters:**

| Parameter | Type | Description |
|---|---|---|
| `server` | `Optional[str]` | Package path to scan for `@server` classes |
| `hooks` | `Optional[str]` | Package path to import for lifecycle hook registration |
| `routes` | `Optional[List[str]]` | Packages or glob patterns to scan for route functions and `@controller` classes. See [server_registry](#server_registry). |
| `controller_factory` | `Optional[Callable[[type], object]]` | Builds each scanned controller; defaults to calling the class with no arguments |

---

### `@startup` / `@shutdown`

Decorators. Register a function into `_startup_hooks` or `_shutdown_hooks` at import time. Both sync and async functions are supported.

```python
from vs_server.lifecycle.vs_lifecycle import startup, shutdown

@startup
async def on_start(): ...

@shutdown
def on_stop(): ...
```

Hooks run in registration order via `VsServer.startup()` and `VsServer.shutdown()`.

---

### `@controller`

Decorator. Marks a class as an HTTP controller. Sets `cls._vs_controller` with path, description, and guards.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `path` | `str` | Yes | — | URL prefix for all routes in this controller |
| `description` | `str` | No | `""` | Tag description shown in Swagger |
| `guards` | `List[Callable]` | No | `[]` | Applied to every route in this controller |

---

### `@get`, `@post`, `@put`, `@delete`, `@patch`

Route decorators. Applied to methods inside a `@controller` class.

**Parameters (all share the same signature):**

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `path` | `str` | No | `""` | Route path appended to the controller prefix |
| `summary` | `str` | No | `None` | Short one-line description shown in Swagger |
| `description` | `str` | No | `None` | Longer description shown in Swagger |
| `guards` | `List[Callable]` | No | `[]` | Merged with controller guards |
| `**kwargs` | — | No | — | Passed to the underlying FastAPI route decorator (e.g. `response_model`, `status_code`) |

---

### `@websocket`

Decorator. Marks a class as a WebSocket handler.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `path` | `str` | Yes | — | WebSocket URL path |
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run at connect time — `async guard(websocket)` |

---

### `@on_message`

Decorator. Marks a method inside a `@websocket` class as a message handler.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `args` | `dict` | No | `{}` | `{arg_name: description}` shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run per-message — `async guard(websocket, data)` |

---

### `@sse`

Decorator. Marks a class as an SSE handler.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `path` | `str` | Yes | — | SSE endpoint URL path |
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run before the stream starts |

---

### `@sse_stream`

Decorator. Marks a method inside an `@sse` class as the event stream generator.

**Parameters:**

| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| `description` | `str` | No | `""` | Shown in `/stream-docs` |
| `args` | `dict` | No | `{}` | `{arg_name: description}` shown in `/stream-docs` |
| `guards` | `List[Callable]` | No | `[]` | Run before the stream starts |

---

### VsAPIException

Base exception class for all server-side HTTP error responses. Extends `VsBaseException` from `vs-common`. All subclasses are handled automatically by `VsFastApiServer`.

**Constructor:**

| Parameter | Type | Description |
|---|---|---|
| `status_code` | `int` | HTTP status code |
| `error_code` | `str` | Machine-readable error code |
| `message` | `str` | Human-readable error message |
| `details` | `Optional[Dict]` | Additional error context |

**Subclasses:**

| Class | Status | Code |
|---|---|---|
| `NotFoundException` | 404 | `NOT_FOUND` |
| `ValidationException` | 400 | `VALIDATION_ERROR` |
| `UnauthorizedException` | 401 | `UNAUTHORIZED` |
| `ForbiddenException` | 403 | `FORBIDDEN` |
| `InternalServerException` | 500 | `INTERNAL_ERROR` |
| `ServiceUnavailableException` | 503 | `SERVICE_UNAVAILABLE` |
| `RateLimitException` | 429 | `RATE_LIMIT_EXCEEDED` |
| `TimeoutException` | 504 | `TIMEOUT_ERROR` |

`RateLimitException` accepts an additional `retry_after: int` parameter (seconds) and sets the `Retry-After` response header.

---

### VsServerHealth

Pydantic model returned by `GET /health`.

**Fields:**

| Field | Type | Description |
|---|---|---|
| `status` | `str` | `healthy`, `degraded`, or `unhealthy` |
| `name` | `str` | Server name |
| `version` | `str` | Server version |
| `uptime_seconds` | `Optional[float]` | Seconds since startup |
| `cache` | `Optional[str]` | `healthy` or `unhealthy` |
| `instance_id` | `Optional[str]` | Hostname of the running instance |
| `dependencies` | `Dict[str, str]` | Custom dependency statuses from `_check_dependencies()` |
| `timestamp` | `datetime` | UTC timestamp of the health check |

---

### VsDocsRenderer

Generates the `/stream-docs` HTML page for WebSocket and SSE endpoints.

**Constructor:**

| Parameter | Type | Description |
|---|---|---|
| `name` | `str` | Server name shown in the page header |
| `version` | `str` | Server version shown in the page header |

**Methods:**

| Method | Signature | Description |
|---|---|---|
| `render` | `render(ws_endpoints: list, sse_endpoints: list) -> str` | Returns a complete HTML string for the docs page |


## Request Payload in Authentication and Enrichment

`VsAuthRequest.payload` is available to authenticators and `request_enricher`
callbacks with `vs-security>=0.1.17`. Install the `security` extra when using these
features. The payload is omitted from representations and is a detached,
recursively read-only snapshot (immutable mappings and tuples for JSON arrays).
Actions still receive and validate their original input. Treat payload values as
unvalidated input; derive trusted user and tenant identity from credentials.

HTTP adapters expose parsed JSON, including `application/json` and `+json` media
types. Non-JSON, absent, or malformed bodies expose `None`; downstream HTTP body
validation remains responsible for malformed JSON. The cached body is replayed to
endpoints. FastAPI 0.110 or newer is required for the body-reading middleware.

Because an authenticator runs before the caller is known, the body is read only up
to `server.max_auth_payload_bytes` (10 MB by default); a larger one is refused with
`413 PAYLOAD_TOO_LARGE`. JSON nested too deeply to parse is exposed as `None`.
`VsBearerTokenFilter` does not read the body at all.


## Async Serving on an Existing Loop

`await server.run_async()` serves on the caller's asyncio loop. It does not invoke
`uvicorn.run()` or start another event loop. An optional `asyncio.Event` passed as
`stop_event=` requests graceful shutdown; cancelling the caller also performs
cleanup. When composed by `VsAgentServer`, process signals and reverse transport
shutdown ordering are managed by the agent. Install `vs-common>=0.2.1`.

The async HTTP runner requires one worker and reload disabled. The synchronous
standalone `run()` retains its existing Uvicorn worker/reload support.


## ASGI Runtime Ownership

`vs_server.runtime.vs_async_server.serve_asgi` owns Uvicorn serving, readiness,
cooperative shutdown, and cancellation cleanup. FastAPI and MCP HTTP share this
helper. Importing it does not load FastAPI, Starlette, or Uvicorn; Uvicorn is loaded
when serving starts. The package root exposes `VsFastApiServer` lazily, and
`VsServerFactory.get("fastapi", config)` loads/registers the built-in adapter on
first use. Explicit `from vs_server import VsFastApiServer` remains supported.
