Metadata-Version: 2.4
Name: vs-server
Version: 0.1.0
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.1.0
Requires-Dist: pydantic>=2.0
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100; 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.100; extra == "dev"
Requires-Dist: uvicorn>=0.23; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Dynamic: license-file

# vs-server

HTTP server library for Python — built on FastAPI. Designed to feel like Spring MVC: annotate a controller class, define routes with method decorators, add guards for auth, and start the server with one line.

---

## The Problem It Solves

Without `vs-server`, every FastAPI service repeats the same boilerplate:

```python
# Without vs-server — repeated in every service
app = FastAPI(title="my-service", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], ...)
app.add_exception_handler(RequestValidationError, handler)
app.add_exception_handler(Exception, handler)

router = APIRouter(prefix="/users", tags=["Users"])

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

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

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

With `vs-server`:

```python
# With vs-server — zero boilerplate
@controller("/users")
class UserController:

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

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

VsFastApiServer(config).add_controller(UserController()).run()
```

---

## Installation

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

For future framework support:

```bash
pip install vs-server[flask]      # when available
```

---

## How It All Fits Together

```
Application Startup
    └── VsLogManager.init(...)           # initialize logging
    └── VsDbSessionFactory(config)       # optional — if using vs-db
    └── VsCacheManager.init(...)         # optional — if using cache

Server
    └── VsFastApiServer(config)
            ├── reads name/version/host/port from config.ini
            ├── wires CORS, exception handlers, lifespan
            ├── auto-registers VsDbMiddleware if vs-db is initialized
            └── exposes /  and /health

Controllers
    └── @controller("/users", guards=[require_auth])
            └── @get, @post, @put, @delete, @patch on methods
            └── guards stack: controller guards run first, method guards append
```

---

## Application Startup

```python
from vs_common.config.vs_ini_config import VsIniConfig
from vs_common.log.vs_log_manager import VsLogManager
from vs_common.schema.vs_log_config import VsLogConfig
from vs_server.server.vs_fast_api_server import VsFastApiServer

if __name__ == "__main__":
    config = VsIniConfig("config.ini")

    VsLogManager.init(VsLogConfig(
        level=config.get("logging.level", "INFO"),
        file_path=config.get("logging.file_path", "logs/app.log"),
    ))

    server = VsFastApiServer(config)
    server.add_controller(UserController())
    server.add_controller(OrderController())
    server.run()
```

`config.ini`:

```ini
[server]
name        = my-service
version     = 1.0.0
description = My API
base_url    =
host        = 0.0.0.0
port        = 8080
reload      = false
workers     = 1
log_level   = info

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

[logging]
level           = INFO
console_enabled = true
file_enabled    = true
file_path       = logs/app.log
```

---

## `@controller`

Marks a class as a route controller. All routes defined inside are registered under the given base path.

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

@controller("/users")
class UserController:
    ...
```

Register with the server:

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

The tag in Swagger/OpenAPI is auto-derived from the class name — `UserController` → `"User"`.

---

## HTTP Method Decorators

Define routes directly on controller methods. All FastAPI route parameters are supported via `**kwargs`.

```python
@controller("/users")
class UserController:

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

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

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

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

    @patch("/{id}", response_model=UserResponse)
    async def patch_user(self, id: int, body: UserPatchRequest): ...

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

Supported kwargs passed through to FastAPI:

| Parameter | Example | Description |
|---|---|---|
| `response_model` | `response_model=UserResponse` | Pydantic model for response serialization |
| `status_code` | `status_code=201` | HTTP status code for success |
| `dependencies` | `dependencies=[Depends(fn)]` | FastAPI dependencies |
| `tags` | `tags=["custom"]` | Override auto-generated Swagger tag |
| `summary` | `summary="List all users"` | Swagger summary |
| `deprecated` | `deprecated=True` | Mark route as deprecated in Swagger |

---

## Guards

Guards are callables that run before the route handler. They are the equivalent of Spring's `@PreAuthorize` or a scoped servlet filter.

### Controller-level guards

Apply to every route in the controller:

```python
from fastapi import Header
from vs_server.schema.exceptions import ForbiddenException

async def require_auth(authorization: str = Header(...)):
    if not is_valid_token(authorization):
        raise ForbiddenException("Invalid token")

@controller("/orders", guards=[require_auth])
class OrderController:

    @get("")
    async def list_orders(self): ...    # require_auth runs

    @post("")
    async def create_order(self): ...   # require_auth runs
```

### Method-level guards

Method guards **append** on top of controller guards — they never replace them:

```python
async def require_admin(authorization: str = Header(...)):
    if not is_admin(authorization):
        raise ForbiddenException("Admin access required")

@controller("/users", guards=[require_auth])
class UserController:

    @get("")
    async def list_users(self): ...                        # runs: require_auth

    @delete("/{id}", guards=[require_admin])
    async def delete_user(self, id: int): ...              # runs: require_auth → require_admin
```

Guards are any callable — auth, rate limiting, tenant validation, feature flags:

```python
async def rate_limit(request: Request): ...
async def validate_tenant(x_tenant_id: str = Header(...)): ...
async def require_feature(x_feature: str = Header(...)): ...

@controller("/api", guards=[require_auth, rate_limit, validate_tenant])
class ApiController: ...
```

---

## Exception Handling

### Built-in exceptions

All exceptions produce a consistent response shape:

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

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

Usage in a controller:

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

@get("/{id}", response_model=UserResponse)
async def get_user(self, id: int):
    user = await self.service.get_by_id(id)
    if not user:
        raise NotFoundException(f"User {id} not found")
    return user
```

`RateLimitException` automatically adds a `Retry-After` header to the response.

### Custom exception handlers

Override `_register_exception_handlers()` to add your own:

```python
class MyServer(VsFastApiServer):

    def _register_exception_handlers(self, app) -> None:
        super()._register_exception_handlers(app)          # keep defaults
        app.add_exception_handler(PaymentException, payment_error_handler)
        app.add_exception_handler(InventoryException, inventory_error_handler)
```

---

## Built-in Routes

Registered automatically on every server:

### `GET /`

```json
{
  "service": "my-service",
  "version": "1.0.0",
  "status": "running"
}
```

### `GET /health`

```json
{
  "status": "healthy",
  "name": "my-service",
  "version": "1.0.0",
  "uptime_seconds": 142.3,
  "cache": "healthy",
  "timestamp": "2026-07-19T10:00:00"
}
```

`status` is `"healthy"` when all components are up, `"degraded"` when cache is unreachable.

---

## Lifecycle Hooks

Override `startup()` and `shutdown()` for custom logic:

```python
class MyServer(VsFastApiServer):

    async def startup(self) -> None:
        await super().startup()
        await self.warm_up_cache()
        self._logger.info("Cache warmed up")

    async def shutdown(self) -> None:
        await self.flush_pending_jobs()
        await super().shutdown()
```

---

## Custom Middleware

Override `_register_middleware()` to add your own middleware:

```python
class MyServer(VsFastApiServer):

    def _register_middleware(self, app) -> None:
        super()._register_middleware(app)          # keep CORS
        app.add_middleware(MyRateLimitMiddleware)
        app.add_middleware(RequestIdMiddleware)
```

---

## Using with vs-db

Initialize `VsDbSessionFactory` before creating the server — `VsDbMiddleware` is registered automatically:

```python
from vs_common.config.vs_ini_config import VsIniConfig
from vs_common.log.vs_log_manager import VsLogManager
from vs_common.schema.vs_log_config import VsLogConfig
from vs_db.session.vs_db_session_factory import VsDbSessionFactory
from vs_server.server.vs_fast_api_server import VsFastApiServer

if __name__ == "__main__":
    config = VsIniConfig("config.ini")
    VsLogManager.init(VsLogConfig(...))
    VsDbSessionFactory(config)             # vs-db initialized → middleware auto-registered

    server = VsFastApiServer(config)
    server.add_controller(UserController())
    server.run()
```

No manual middleware registration needed.

---

## Implementing Your Own Server

Extend `VsServer` to support any framework:

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

class VsFlaskServer(VsServer):

    def __init__(self, config: VsBaseConfig):
        try:
            from flask import Flask
        except ImportError:
            raise ImportError("Run: pip install vs-server[flask]")
        super().__init__(config)
        self._app = Flask(self.name)

    def add_router(self, router, prefix: str = "") -> None:
        self._app.register_blueprint(router, url_prefix=prefix)

    def add_controller(self, instance) -> None:
        # scan for _vs_route metadata and register with Flask
        ...

    def get_app(self):
        return self._app

    def run(self) -> None:
        self._app.run(
            host=self._config.get("server.host", "127.0.0.1"),
            port=self._config.get("server.port", 8000, int),
        )
```

---

## Full Example

```python
from pydantic import BaseModel
from fastapi import Header
from vs_server.decorator.vs_controller_decorator import controller, get, post, put, delete
from vs_server.schema.exceptions import NotFoundException, ForbiddenException


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

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


async def require_auth(authorization: str = Header(...)):
    if authorization != "Bearer secret":
        raise ForbiddenException("Invalid token")

async def require_admin(authorization: str = Header(...)):
    if authorization != "Bearer admin":
        raise ForbiddenException("Admin access required")


@controller("/users", guards=[require_auth])
class UserController:

    def __init__(self):
        self.service = UserService()

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

    @get("/{id}", response_model=UserResponse)
    async def get_user(self, id: int):
        user = await self.service.get_by_id(id)
        if not user:
            raise NotFoundException(f"User {id} not found")
        return user

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

    @put("/{id}", response_model=UserResponse)
    async def update_user(self, id: int, body: UserRequest):
        return await self.service.update(id, body)

    @delete("/{id}", status_code=204, guards=[require_admin])
    async def delete_user(self, id: int):
        await self.service.delete(id)


if __name__ == "__main__":
    from vs_common.config.vs_ini_config import VsIniConfig
    from vs_common.log.vs_log_manager import VsLogManager
    from vs_common.schema.vs_log_config import VsLogConfig
    from vs_server.server.vs_fast_api_server import VsFastApiServer

    config = VsIniConfig("config.ini")
    VsLogManager.init(VsLogConfig(level="INFO"))

    server = VsFastApiServer(config)
    server.add_controller(UserController())
    server.run()
```

**What vs-server eliminated:**
- No `FastAPI()` setup
- No `add_middleware()` calls for CORS and exception handlers
- No `APIRouter()` boilerplate
- No `include_router()` calls
- No `uvicorn.run()` wiring
- Guards expressed as plain callables — no FastAPI `Depends` syntax in user code
