Metadata-Version: 2.4
Name: vcti-webapp
Version: 1.0.0
Summary: Service lifecycle framework with FastAPI background services, dependency management, and optional desktop GUI launcher
Author: Visual Collaboration Technologies Inc.
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.100
Requires-Dist: uvicorn>=0.20
Provides-Extra: gui
Requires-Dist: pywebview>=4.0; extra == "gui"
Provides-Extra: zip
Requires-Dist: pywebview>=4.0; extra == "zip"
Requires-Dist: vcti-session>=1.0.0; extra == "zip"
Provides-Extra: all
Requires-Dist: pywebview>=4.0; extra == "all"
Requires-Dist: vcti-session>=1.0.0; extra == "all"
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# Web App

Service lifecycle framework with FastAPI background services, dependency management, and optional desktop GUI launcher.

## Overview

vcti-webapp provides a `Service` base class for managing background services
with ordered dependencies and thread-safe lifecycle control. `FastAPIService`
extends this to run FastAPI applications via uvicorn in background threads
with automatic port discovery. For desktop applications, the optional GUI
module adds `AppLauncher` (pywebview window), `StaticDirApp` (static file
serving), and `ZippedApp` (serve from ZIP archives).

## Installation

Core (services only):
```bash
pip install vcti-webapp>=1.0.0
```

With desktop GUI support:
```bash
pip install vcti-webapp[gui]>=1.0.0
```

With ZIP archive support (includes GUI + vcti-session):
```bash
pip install vcti-webapp[zip]>=1.0.0
```

---

## Quick Start

### Background FastAPI service

```python
from fastapi import FastAPI
from vcti.webapp import FastAPIService

app = FastAPI()

@app.get("/health")
async def health():
    return {"status": "ok"}

# Start in background thread with auto-discovered port
with FastAPIService(app, name="api") as svc:
    print(f"Running on http://localhost:{svc.port}")
    # ... do work ...
# Server stops automatically on exit
```

### Service dependencies

```python
from vcti.webapp import Service, FastAPIService, service_dependency

class DatabaseService(Service):
    def _start_service(self):
        self.connection = connect_to_db()
    def _stop_service(self):
        self.connection.close()

db = DatabaseService(name="database")
api = FastAPIService(app, name="api")
api.add_dependency(db)

api.start()   # starts db first, then api
api.stop()    # stops api first, then db (reverse order)
```

### Error recovery

```python
from vcti.webapp import CyclicDependencyError

# Circular dependencies are caught at registration time
try:
    svc_a.add_dependency(svc_b)
except CyclicDependencyError:
    print("Would create a cycle — dependency not added")

# Start failures roll back dependencies automatically
try:
    svc.start()
except RuntimeError:
    # All already-started dependencies have been stopped
    print("Service failed to start, deps cleaned up")
```

### Desktop GUI (requires pywebview)

```python
from vcti.webapp.app_launcher import AppLauncher

launcher = AppLauncher(app, window_title="My App", window_size=(1280, 720))
launcher.start()  # opens desktop window, blocks until closed
```

---

## Core API

### Service (base)

| Method | Description |
|--------|-------------|
| `start()` | Start service and dependencies (thread-safe, safe to call from multiple threads) |
| `stop()` | Stop service and optionally dependencies |
| `add_dependency(service)` | Register a dependency (returns self, raises `CyclicDependencyError` on cycle) |
| `is_running()` | Check if running |

### FastAPIService

| Parameter | Default | Description |
|-----------|---------|-------------|
| `app` | *(required)* | The FastAPI application |
| `host` | `"127.0.0.1"` | Bind address (loopback only by default for security) |
| `port` | `None` | TCP port (`None` = auto-discover a free port) |
| `ready_timeout` | `10.0` | Seconds to wait for server readiness; `0` to skip |
| `ready_poll_interval` | `0.05` | Seconds between readiness polls |
| `uvicorn_config` | `None` | Extra kwargs forwarded to `uvicorn.Config` |

### GUI classes (optional — `vcti-webapp[gui]`)

| Class | Purpose |
|-------|---------|
| `AppLauncher` | Desktop window via pywebview |
| `StaticDirApp` | Serve static files from a directory |
| `ZippedApp` | Extract and serve from ZIP archive |

---

## Advanced Usage

### Custom uvicorn configuration

```python
# Suppress noisy startup logs
svc = FastAPIService(app, uvicorn_config={"log_level": "warning", "access_log": False})

# TLS termination at uvicorn
svc = FastAPIService(app, uvicorn_config={
    "ssl_keyfile": "key.pem",
    "ssl_certfile": "cert.pem",
})
```

### Slow CI environments

```python
# Increase readiness timeout on slow machines
svc = FastAPIService(app, ready_timeout=30.0, ready_poll_interval=0.1)
```

### Shared dependencies

When multiple services share a dependency, use `stop_dependencies=False`
to prevent the first service to stop from tearing down the shared resource:

```python
db = DatabaseService(name="db")

api = FastAPIService(app, name="api", stop_dependencies=False)
api.add_dependency(db)

worker = WorkerService(name="worker", stop_dependencies=False)
worker.add_dependency(db)

# api.stop() leaves db running — worker still needs it
```

### Static file serving without GUI

`StaticDirApp` inherits from `AppLauncher` (which requires pywebview),
but you can serve static files without a GUI using plain `FastAPIService`:

```python
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from vcti.webapp import FastAPIService

app = FastAPI()
app.mount("/static", StaticFiles(directory="./dist"), name="static")

with FastAPIService(app, name="docs-server") as svc:
    print(f"Serving at http://localhost:{svc.port}/static/index.html")
```

### Root redirect (show_index_on_root)

`StaticDirApp` and `ZippedApp` redirect `GET /` to
`{static_route}/{default_page}` by default.  Set `show_index_on_root=False`
if you define your own root route or want `/` to return 404:

```python
StaticDirApp(Path("./dist"), show_index_on_root=False)
```

---

## Threading

`start()` and `stop()` are thread-safe.  Calling `start()` from multiple
threads simultaneously is safe — only one thread runs startup; others
return immediately.  See [docs/design.md](docs/design.md) for details on
lock ordering and concurrency guarantees.

---

## Dependencies

- [fastapi](https://fastapi.tiangolo.com/) (>=0.100) — required
- [uvicorn](https://www.uvicorn.org/) (>=0.20) — required
- [pywebview](https://pywebview.flowrl.com/) (>=4.0) — optional, for GUI
- [vcti-session](https://pypi.org/project/vcti-session/) (>=1.0.0) — optional, for ZippedApp
