Metadata-Version: 2.4
Name: viveka-setu
Version: 0.1.1
Summary: FastAPI + Uvicorn application factory for Viveka services — built-in health, CORS, exception handling, and lifecycle management
License: VIVEKASUTRA PROPRIETARY SOFTWARE LICENSE
        
        Copyright (c) 2025 VivekaSutra. All rights reserved.
        https://vivekasutra.com/
        
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        IMPORTANT: READ THIS LICENSE CAREFULLY BEFORE DOWNLOADING,
        INSTALLING, OR USING THIS SOFTWARE.
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        
        By downloading, installing, or using this software ("viveka-setu"),
        you agree to be bound by the terms of this license agreement.
        If you do not agree, do not download, install, or use this software.
        
        
        1. GRANT OF LICENSE
           VivekaSutra grants you a limited, non-exclusive, non-transferable,
           royalty-free license to download and use this software solely for
           your personal or internal business purposes.
        
        
        2. RESTRICTIONS
           You may NOT:
           a) Copy, modify, merge, or create derivative works of this software.
           b) Distribute, sell, sublicense, rent, lease, or transfer this
              software or any rights in it to any third party.
           c) Reverse engineer, decompile, disassemble, or attempt to derive
              the source code of this software.
           d) Remove, alter, or obscure any proprietary notices, labels,
              or markings on this software.
           e) Use this software to build a competing product or service.
        
        
        3. INTELLECTUAL PROPERTY
           This software and all copies thereof are proprietary to VivekaSutra.
           All title, ownership rights, and intellectual property rights remain
           exclusively with VivekaSutra. This license does not grant you any
           rights to trademarks, service marks, or trade names of VivekaSutra.
        
        
        4. NO WARRANTY
           THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
           EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
           MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
           NON-INFRINGEMENT.
        
           VIVEKASUTRA DOES NOT WARRANT THAT:
           a) THE SOFTWARE WILL MEET YOUR REQUIREMENTS.
           b) THE SOFTWARE WILL OPERATE UNINTERRUPTED OR ERROR-FREE.
           c) ANY ERRORS IN THE SOFTWARE WILL BE CORRECTED.
           d) THE SOFTWARE IS COMPATIBLE WITH YOUR SYSTEMS OR ENVIRONMENT.
        
           YOU ASSUME ALL RISK ASSOCIATED WITH THE USE OF THIS SOFTWARE.
        
        
        5. LIMITATION OF LIABILITY
           TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL
           VIVEKASUTRA, ITS DIRECTORS, EMPLOYEES, PARTNERS, AGENTS, SUPPLIERS,
           OR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
           EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING BUT NOT LIMITED TO LOSS
           OF PROFITS, DATA, BUSINESS, OR GOODWILL, EVEN IF VIVEKASUTRA HAS BEEN
           ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
        
        
        6. INDEMNIFICATION
           You agree to indemnify and hold harmless VivekaSutra from and against
           any claims, liabilities, damages, losses, and expenses arising out of
           your use of this software or violation of this license.
        
        
        7. TERMINATION
           Your rights under this license terminate automatically if you fail to
           comply with any of its terms. Upon termination you must immediately
           cease all use and destroy all copies in your possession.
        
        
        8. GOVERNING LAW
           This license shall be governed by applicable laws. Disputes shall be
           subject to the exclusive jurisdiction of competent courts.
        
        
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        For licensing inquiries: https://vivekasutra.com/
        ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
        
        VivekaSutra — Copyright (c) 2025. All rights reserved.
        
Project-URL: Homepage, https://vivekasutra.com/
Project-URL: Source, https://github.com/vivekasutra/viveka-setu
Keywords: fastapi,uvicorn,server,api,async,viveka,framework
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 :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
Classifier: Framework :: AsyncIO
Classifier: Framework :: FastAPI
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: fastapi>=0.109
Requires-Dist: uvicorn[standard]>=0.27
Requires-Dist: starlette>=0.35
Requires-Dist: pydantic>=2.0
Requires-Dist: viveka-grantha>=0.1.0
Provides-Extra: database
Requires-Dist: viveka-kosha>=0.1.0; extra == "database"
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: httpx>=0.27; extra == "dev"
Dynamic: license-file

# viveka-setu

FastAPI + Uvicorn application factory for Viveka services. Spin up a production-ready API server with built-in health checks, CORS, exception handling, DB middleware, and lifecycle management — in under ten lines of code.

Developed by [VivekaSutra](https://vivekasutra.com/)

---

## Overview

viveka-setu is the equivalent of Spring Boot's embedded Tomcat + `@SpringBootApplication`. It wraps FastAPI and Uvicorn so developers focus on business logic, not server boilerplate.

| Feature | Detail |
|---|---|
| Built-in routes | `GET /` (status) and `GET /health` (uptime + version) |
| CORS | Configurable origins via `config.ini` or defaults to `*` |
| Exception handling | Standard JSON error responses for all HTTP error types |
| DB middleware | Auto-wired `DbMiddleware` when `enable_database=True` |
| Cache | Auto-wired Redis cache when `enable_cache=True` |
| Lifecycle hooks | `startup()` and `shutdown()` overridable in `VivekaApp` |
| CLI args | `--host`, `--port`, `--reload`, `--workers`, `--log-level` |
| Config priority | CLI args → `config.ini` → hardcoded defaults |

---

## Installation

```bash
pip install viveka-setu
```

With database support (viveka-kosha):

```bash
pip install "viveka-setu[database]"
```

---

## Quickstart

```python
from viveka_server import VivekaApp, VivekaServer, VivekaAppConfig

app    = VivekaApp(VivekaAppConfig(name="my-service", version="1.0.0"))
server = VivekaServer(app)
server.run()
```

That's it. Your service is running at `http://127.0.0.1:8000` with:
- `GET /` → `{"service": "my-service", "version": "1.0.0", "status": "running"}`
- `GET /health` → uptime, name, version, timestamp
- `GET /docs` → FastAPI Swagger UI

---

## Configuration

`config.ini`:

```ini
[server]
host      = 0.0.0.0
port      = 8080
reload    = false
workers   = 4
log_level = info

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

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

[database]
url          = postgresql+asyncpg://user:pass@localhost/mydb
pool_size    = 10
max_overflow = 20

[cache]
enabled     = true
url         = redis://localhost:6379/0
default_ttl = 3600
```

---

## Adding Custom Routes

Override `build_routes()` in a `VivekaServer` subclass:

```python
from fastapi import APIRouter
from viveka_server import VivekaApp, VivekaServer, VivekaAppConfig

class MyServer(VivekaServer):
    def build_routes(self, router: APIRouter) -> APIRouter:

        @router.get("/api/v1/ping")
        async def ping():
            return {"pong": True}

        @router.get("/api/v1/users/{user_id}")
        async def get_user(user_id: int):
            return {"id": user_id}

        return router

app    = VivekaApp(VivekaAppConfig(name="my-service", version="1.0.0"))
server = MyServer(app)
server.run()
```

---

## Lifecycle Hooks

Override `startup()` and `shutdown()` in a `VivekaApp` subclass for custom initialization:

```python
from viveka_server import VivekaApp, VivekaAppConfig

class MyApp(VivekaApp):
    async def startup(self) -> None:
        await super().startup()
        # load ML models, warm caches, connect external services
        self.logger.info("Custom startup complete")

    async def shutdown(self) -> None:
        # release resources, flush buffers
        self.logger.info("Custom shutdown complete")
        await super().shutdown()
```

---

## Enable Database & Cache

```python
from viveka_server import VivekaApp, VivekaServer, VivekaAppConfig

app = VivekaApp(VivekaAppConfig(
    name            = "data-service",
    version         = "1.0.0",
    enable_database = True,   # auto-wires DbMiddleware + DatabaseSessionFactory
    enable_cache    = True,   # auto-wires VivekaCacheManager + RedisCacheService
))
server = VivekaServer(app)
server.run()
```

Requires `[database]` and `[cache]` sections in `config.ini`.
Requires `pip install "viveka-setu[database]"` for DB support.

---

## Exception Handling

viveka-setu registers a global exception handler that converts all `VivekaAPIException` subclasses to a consistent JSON response:

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

Raise exceptions directly from any route or service:

```python
from viveka_server import NotFoundException, UnauthorizedException, RateLimitException

@router.get("/users/{user_id}")
async def get_user(user_id: int):
    user = await user_repo.get(user_id)
    if not user:
        raise NotFoundException(f"User {user_id} not found")
    return user
```

### Available Exceptions

| Class | HTTP Code | Error Code |
|---|---|---|
| `NotFoundException` | 404 | `NOT_FOUND` |
| `ValidationException` | 400 | `VALIDATION_ERROR` |
| `UnauthorizedException` | 401 | `UNAUTHORIZED` |
| `ForbiddenException` | 403 | `FORBIDDEN` |
| `InternalServerException` | 500 | `INTERNAL_ERROR` |
| `RateLimitException` | 429 | `RATE_LIMIT_EXCEEDED` |
| `BudgetExceededException` | 402 | `BUDGET_EXCEEDED` |
| `TimeoutException` | 504 | `TIMEOUT_ERROR` |
| `ProviderException` | 502 | `PROVIDER_ERROR` |

---

## CLI Usage

```bash
python main.py --host 0.0.0.0 --port 8080 --workers 4
python main.py --reload                  # development mode
python main.py --log-level debug
```

---

## Part of the Viveka Platform

- **viveka-grantha** — config, logging, cache (required)
- **viveka-kosha** — async database / ORM (optional, for `enable_database=True`)
- **viveka-setu** — server factory ← you are here

---

## License

Copyright (c) 2025 VivekaSutra. All rights reserved.

This software is distributed under the **VivekaSutra Proprietary Software License**.

- Free to download and use for personal or commercial purposes
- Modification, redistribution, and reverse engineering are not permitted
- Provided "AS IS" — no warranty of any kind
- VivekaSutra is not liable for any damages arising from use

See [LICENSE.txt](LICENSE.txt) for the full license text.
For licensing inquiries visit [vivekasutra.com](https://vivekasutra.com/)
