Buckets:

download
raw
27 kB
"""App Builder component for creating and configuring FastAPI applications.
This module provides the AppBuilder class that handles the creation and configuration
of FastAPI application instances, following the single responsibility principle.
"""
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional
from fastapi import FastAPI
from jvspatial.api.config import ServerConfig
from jvspatial.api.constants import LogIcons
# RBAC: graph and progressive JSON graph APIs are admin-only (see also auth middleware path rules).
_ADMIN_API_ROLES: List[str] = ["admin"]
class AppBuilder:
"""Component responsible for building and configuring FastAPI applications.
This class handles the creation of FastAPI instances with proper configuration,
following the single responsibility principle by focusing solely on app creation.
Attributes:
config: Server configuration instance
_logger: Logger instance for app building operations
"""
def __init__(self, config: ServerConfig):
"""Initialize the AppBuilder.
Args:
config: Server configuration instance
"""
self.config = config
self._logger = logging.getLogger(__name__)
def create_app(self, lifespan: Optional[Any] = None) -> FastAPI:
"""Create a FastAPI application instance.
Args:
lifespan: Optional lifespan context manager for startup/shutdown
Returns:
Configured FastAPI application instance
Production unpublish: setting ``JVSPATIAL_DOCS_DISABLED=1`` (or
``true``/``yes``/``on``) forces ``docs_url``, ``redoc_url``,
``openapi_url``, and ``swagger_ui_oauth2_redirect_url`` to
``None``. FastAPI then never registers any of those routes — they
return 404 with no body, the OpenAPI schema is not served, and no
Swagger UI HTML is emitted. Use this in production when the API
surface should not be self-documenting.
"""
# Use the canonical boolean parser instead of an ad-hoc inline
# set so behavior matches the rest of the codebase
# (audit §7.2 / §7.12).
from jvspatial.env import env, parse_bool
docs_disabled = bool(
env("JVSPATIAL_DOCS_DISABLED", default=False, parse=parse_bool)
)
app_kwargs: Dict[str, Any] = {
"title": self.config.title,
"description": self.config.description,
"version": self.config.version,
"docs_url": None if docs_disabled else self.config.docs_url,
"redoc_url": None if docs_disabled else self.config.redoc_url,
"debug": self.config.debug,
# Configure OpenAPI tags order - ensure "App" appears after "default"
# Tags are ordered by their appearance in this list
"openapi_tags": [
{"name": "default", "description": "Default API endpoints"},
{"name": "App", "description": "Application-specific endpoints"},
],
}
if docs_disabled:
# Explicitly nuke the OpenAPI JSON spec and the Swagger OAuth2
# redirect endpoint too — FastAPI defaults them on otherwise.
app_kwargs["openapi_url"] = None
app_kwargs["swagger_ui_oauth2_redirect_url"] = None
# Add lifespan if provided
if lifespan is not None:
app_kwargs["lifespan"] = lifespan
app = FastAPI(**app_kwargs)
# Override the openapi() method to enforce tag ordering
# This ensures "App" always appears after "default" in the OpenAPI schema
from fastapi.openapi.utils import get_openapi
def custom_openapi() -> Dict[str, Any]:
"""Custom OpenAPI schema generator with enforced tag ordering."""
if app.openapi_schema:
return app.openapi_schema
# Generate the schema using get_openapi directly
schema = get_openapi(
title=app.title,
version=app.version,
description=app.description,
routes=app.routes,
)
# Enforce tag ordering - ensure "App" appears after "default"
# Collect all unique tags from the schema
all_tags = set()
for path_item in schema.get("paths", {}).values():
for operation in path_item.values():
if isinstance(operation, dict) and "tags" in operation:
all_tags.update(operation["tags"])
# Prefer order: default, App, Files; then any remaining tags alphabetically
preferred = ["default", "App", "Files"]
ordered_tags = [t for t in preferred if t in all_tags]
ordered_tags.extend(sorted(t for t in all_tags if t not in ordered_tags))
# Create tag definitions in the correct order
if "tags" not in schema:
schema["tags"] = []
tag_definitions = []
for tag in ordered_tags:
tag_def = {"name": tag}
# Add description if we have it
if tag == "default":
tag_def["description"] = "Default API endpoints"
elif tag == "App":
tag_def["description"] = "Application-specific endpoints"
elif tag == "Files":
tag_def["description"] = (
"File upload, serve, delete, and proxy URLs"
)
tag_definitions.append(tag_def)
schema["tags"] = tag_definitions
# Cache the schema
app.openapi_schema = schema
return schema
# Replace the openapi method
app.openapi = custom_openapi
self._logger.debug(
f"{LogIcons.SUCCESS} FastAPI app created: {self.config.title} v{self.config.version}"
)
return app
def configure_openapi_security(
self, app: FastAPI, has_auth_endpoints: bool = False
) -> None:
"""Configure OpenAPI security schemes if auth endpoints exist.
Args:
app: FastAPI application instance to configure
has_auth_endpoints: Whether authenticated endpoints exist
"""
if not has_auth_endpoints:
return
try:
# Configure OpenAPI security if needed
from jvspatial.api.auth.openapi_config import configure_openapi_security
configure_openapi_security(app)
# OpenAPI security configured (no log needed)
except ImportError as e:
self._logger.warning(
f"{LogIcons.WARNING} Could not configure OpenAPI security: {e}"
)
def register_core_routes(
self,
app: FastAPI,
graph_context: Optional[Any] = None,
server: Optional[Any] = None,
) -> None:
"""Register core routes (health, root).
Args:
app: FastAPI application instance to configure
graph_context: Optional GraphContext for health checks
server: Optional Server instance for endpoint registration
"""
from fastapi.responses import JSONResponse
from jvspatial.core.entities import Root
admin_graph_dir = self._resolve_admin_graph_static_dir()
mount_admin_graph = (
self.config.graph_endpoint_enabled
and admin_graph_dir is not None
and (admin_graph_dir / "index.html").is_file()
)
# Add default health check endpoint
@app.get("/health", response_model=None)
async def health_check() -> Dict[str, Any]:
"""Health check endpoint."""
try:
# Test database connectivity - Root.get() always returns singleton
root = await Root.get()
return {
"status": "healthy",
"database": "connected",
"root_node": root.id,
"service": self.config.title,
"version": self.config.version,
}
except Exception as e:
return JSONResponse(
status_code=503,
content={
"status": "unhealthy",
"error": str(e),
"service": self.config.title,
"version": self.config.version,
},
)
# Add root endpoint
@app.get("/")
async def root_info() -> Dict[str, Any]:
"""Root endpoint with API information."""
info: Dict[str, Any] = {
"service": self.config.title,
"description": self.config.description,
"version": self.config.version,
"docs": self.config.docs_url,
"health": "/health",
}
if self.config.graph_endpoint_enabled:
info["graph"] = "/api/graph"
info["graph_progressive"] = {
"expand": "/api/graph/expand",
"subgraph": "/api/graph/subgraph",
}
if mount_admin_graph:
info["admin_graph_ui"] = "/admin/graph/"
return info
# Add graph visualization endpoint (optional)
if self.config.graph_endpoint_enabled:
self._register_graph_endpoint(app, graph_context, server)
if server and hasattr(server, "_endpoint_registry"):
self._register_progressive_graph_endpoints(app, graph_context, server)
from jvspatial.api.deferred_invoke_route import register_deferred_invoke_route
register_deferred_invoke_route(app)
if mount_admin_graph and admin_graph_dir is not None:
from fastapi.staticfiles import StaticFiles
app.mount(
"/admin/graph",
StaticFiles(directory=str(admin_graph_dir), html=True),
name="admin_graph_ui",
)
# Core routes registered (no log needed)
def _resolve_admin_graph_static_dir(self) -> Optional[Path]:
"""Directory with embedded graph UI ``index.html``, if available.
Populated by ``cd jvgraph-ui && npm run embed`` (copies the Vite build into
``jvspatial/static/admin_graph/`` inside the installed package).
"""
root = Path(__file__).resolve().parents[2] / "static" / "admin_graph"
if (root / "index.html").is_file():
return root
return None
def _register_progressive_graph_endpoints(
self,
app: FastAPI,
graph_context: Optional[Any] = None,
server: Optional[Any] = None,
) -> None:
"""Register JSON graph expand + subgraph endpoints (bounded, merge-friendly).
Paths (relative to API prefix): ``/graph/expand``, ``/graph/subgraph``.
Same policy as ``/api/graph``: authentication required and **admin** role
(see ``_ADMIN_API_ROLES``; middleware also enforces admin for ``/graph/*``).
"""
from contextlib import suppress
from jvspatial.api._route_utils import iter_api_routes
from jvspatial.api.endpoints.factory import ParameterModelFactory
from jvspatial.api.endpoints.graph_visualization import (
make_graph_expand_handler,
make_graph_subgraph_handler,
)
expand_path_full = "/api/graph/expand"
subgraph_path_full = "/api/graph/subgraph"
def _already_registered(path_full: str) -> bool:
if server._endpoint_registry.has_path(path_full):
for ep in server._endpoint_registry.get_by_path(path_full):
if "GET" in ep.methods:
return True
if any(
route.path == path_full and "GET" in route.methods
for route in iter_api_routes(app.routes)
):
return True
return False
if _already_registered(expand_path_full) and _already_registered(
subgraph_path_full
):
return
get_expand = make_graph_expand_handler(graph_context)
get_subgraph = make_graph_subgraph_handler(graph_context)
tags = ["App"]
registered_any = False
for path_full, rel_path, source_fn, op_id in (
(expand_path_full, "/graph/expand", get_expand, "get_graph_expand"),
(subgraph_path_full, "/graph/subgraph", get_subgraph, "get_graph_subgraph"),
):
if _already_registered(path_full):
continue
param_model = ParameterModelFactory.create_model(source_fn, path=path_full)
if param_model is not None:
from jvspatial.api.decorators.function_wrappers import (
wrap_function_with_params,
)
wrapped = wrap_function_with_params(
source_fn, param_model, ["GET"], path=path_full
)
else:
wrapped = source_fn
source_fn._auth_required = True # type: ignore[attr-defined]
wrapped._auth_required = True # type: ignore[attr-defined]
source_fn._required_roles = _ADMIN_API_ROLES # type: ignore[attr-defined]
wrapped._required_roles = _ADMIN_API_ROLES # type: ignore[attr-defined]
if not hasattr(wrapped, "_jvspatial_endpoint_config"):
wrapped._jvspatial_endpoint_config = {} # type: ignore[attr-defined]
wrapped._jvspatial_endpoint_config["tags"] = tags # type: ignore[attr-defined]
wrapped._jvspatial_endpoint_config["auth_required"] = True # type: ignore[attr-defined]
wrapped._jvspatial_endpoint_config["roles"] = _ADMIN_API_ROLES # type: ignore[attr-defined]
with suppress(Exception):
server._endpoint_registry.register_function(
source_fn,
path_full,
methods=["GET"],
route_config={
"path": path_full,
"endpoint": wrapped,
"methods": ["GET"],
"auth_required": True,
"tags": tags,
"roles": _ADMIN_API_ROLES,
},
auth_required=True,
tags=tags,
roles=_ADMIN_API_ROLES,
)
server.endpoint_router.add_route(
path=rel_path,
endpoint=wrapped,
methods=["GET"],
source_obj=source_fn,
auth=True,
roles=_ADMIN_API_ROLES,
tags=tags,
operation_id=op_id,
)
registered_any = True
if registered_any:
server._has_auth_endpoints = True
def _register_graph_endpoint(
self,
app: FastAPI,
graph_context: Optional[Any] = None,
server: Optional[Any] = None,
) -> None:
"""Register graph visualization endpoint if enabled.
Uses the @endpoint decorator and registers with the endpoint registry
for proper authentication handling.
Args:
app: FastAPI application instance
graph_context: Optional GraphContext for graph generation
server: Optional Server instance for endpoint registration
"""
from fastapi import HTTPException, Query
from fastapi.responses import PlainTextResponse
from jvspatial.core.context import get_default_context
from jvspatial.core.graph import export_graph
# Store graph_context for use in the endpoint function
# We'll access it via closure
_graph_context = graph_context
# Define the endpoint function without the decorator to avoid auto-registration
# We'll register it manually with explicit tags
async def get_graph(
format: str = Query( # noqa: B008
default="dot",
description="Graph format: 'dot' (Graphviz) or 'mermaid'",
pattern="^(dot|mermaid)$",
),
include_attributes: bool = Query( # noqa: B008
default=True, description="Include node/edge attributes in labels"
),
rankdir: str = Query( # noqa: B008
default="TB",
description="Graph direction: TB, LR, BT, RL (for DOT) or TB, TD, BT, RL, LR (for Mermaid)",
),
node_shape: str = Query( # noqa: B008
default="box",
description="Node shape for DOT format: box, ellipse, circle, diamond, etc.",
),
) -> str:
"""Get graph visualization in DOT or Mermaid format.
This endpoint generates a visual representation of the current application graph
using the built-in graphing operation. The graph includes all nodes and edges
in the database.
**Requires authentication** - This endpoint exposes graph data and requires
a valid authentication token.
**Args:**
- **format**: Output format - `'dot'` for Graphviz or `'mermaid'` for Mermaid diagrams
- **include_attributes**: Whether to include node/edge attributes in labels
- **rankdir**: Graph direction:
- For DOT: `TB` (top-bottom), `LR` (left-right), `BT` (bottom-top), `RL` (right-left)
- For Mermaid: `TB`, `TD`, `BT`, `RL`, `LR`
- **node_shape**: Node shape for DOT format (e.g., `box`, `ellipse`, `circle`, `diamond`)
**Returns:**
Graph representation string in the requested format
**Examples:**
Get Graphviz DOT format:
```
GET /api/graph?format=dot&rankdir=LR
```
Get Mermaid format without attributes:
```
GET /api/graph?format=mermaid&include_attributes=false
```
Get DOT format with custom node shape:
```
GET /api/graph?format=dot&node_shape=ellipse&rankdir=TB
```
"""
try:
# Use provided graph context or fallback to default
context = _graph_context
if not context:
context = get_default_context()
# Generate graph based on format
if format == "dot":
graph_output = await export_graph(
context,
format="dot",
include_attributes=include_attributes,
rankdir=rankdir,
node_shape=node_shape,
)
else: # mermaid
# Map rankdir to mermaid direction
direction = rankdir
graph_output = await export_graph(
context,
format="mermaid",
include_attributes=include_attributes,
direction=direction,
)
return graph_output
except Exception as e:
self._logger.error(f"Graph generation error: {e}", exc_info=True)
raise HTTPException(
status_code=500,
detail=f"Failed to generate graph: {str(e)}",
)
# Manually register the function endpoint with the endpoint registry
# so the authentication middleware can find it
# Use explicit tags=["App"] to ensure it only appears under App tag
if server and hasattr(server, "_endpoint_registry"):
try:
# Check if graph endpoint is already registered to prevent duplicates
# This can happen if register_core_routes is called multiple times
graph_path = "/api/graph"
# Check endpoint registry by path (most reliable)
if server._endpoint_registry.has_path(graph_path):
# Check if GET method is already registered at this path
existing_endpoints = server._endpoint_registry.get_by_path(
graph_path
)
for endpoint_info in existing_endpoints:
if "GET" in endpoint_info.methods:
# Already registered, skip to avoid duplicates
return
# Also check if route already exists in the app (fallback check)
from fastapi.routing import APIRoute
for route in app.routes:
if (
isinstance(route, APIRoute)
and route.path == graph_path
and "GET" in route.methods
):
# Already registered, skip to avoid duplicates
return
from jvspatial.api.endpoints.factory import ParameterModelFactory
# Create parameter model if function has parameters
# Use full path for parameter model
param_model = ParameterModelFactory.create_model(
get_graph, path="/api/graph"
)
# Wrap function with parameter handling if needed
if param_model is not None:
from jvspatial.api.decorators.function_wrappers import (
wrap_function_with_params,
)
wrapped_func = wrap_function_with_params(
get_graph, param_model, ["GET"], path="/api/graph"
)
else:
wrapped_func = get_graph
# Set auth attributes on the function
get_graph._auth_required = True # type: ignore[attr-defined]
wrapped_func._auth_required = True # type: ignore[attr-defined]
get_graph._required_roles = _ADMIN_API_ROLES # type: ignore[attr-defined]
wrapped_func._required_roles = _ADMIN_API_ROLES # type: ignore[attr-defined]
# Explicitly set tags to only ["App"] - no default tag
tags = ["App"]
# Set endpoint config with explicit tags to prevent default tag addition
if not hasattr(wrapped_func, "_jvspatial_endpoint_config"):
wrapped_func._jvspatial_endpoint_config = {} # type: ignore[attr-defined]
wrapped_func._jvspatial_endpoint_config["tags"] = tags # type: ignore[attr-defined]
wrapped_func._jvspatial_endpoint_config["auth_required"] = True # type: ignore[attr-defined]
wrapped_func._jvspatial_endpoint_config["roles"] = _ADMIN_API_ROLES # type: ignore[attr-defined]
# Register with endpoint registry using full path
# Check if already registered to avoid duplicates
from contextlib import suppress
with suppress(Exception):
server._endpoint_registry.register_function(
get_graph, # Original function
"/api/graph", # Full path for registry
methods=["GET"],
route_config={
"path": "/api/graph", # Full path
"endpoint": wrapped_func,
"methods": ["GET"],
"auth_required": True,
"response_class": PlainTextResponse,
"tags": tags, # Explicitly ["App"] only
"roles": _ADMIN_API_ROLES,
},
auth_required=True,
response_class=PlainTextResponse,
tags=tags, # Explicitly ["App"] only
roles=_ADMIN_API_ROLES,
)
# Register with endpoint router - path is relative to router prefix (/api)
# This ensures the endpoint is only registered once with explicit tags
server.endpoint_router.add_route(
path="/graph", # Relative to /api prefix (becomes /api/graph)
endpoint=wrapped_func,
methods=["GET"],
source_obj=get_graph,
auth=True,
roles=_ADMIN_API_ROLES,
response_class=PlainTextResponse,
tags=tags, # Explicitly set to only ["App"] - prevents default tag
operation_id="get_graph_visualization", # Explicit operation_id to prevent duplicates
)
# Mark server as having auth endpoints
server._has_auth_endpoints = True
except Exception as e:
self._logger.warning(
f"Could not register graph endpoint with registry: {e}"
)
# Fallback: register directly with FastAPI and set auth attribute
# Check if already registered to avoid duplicates
from fastapi.routing import APIRoute
graph_path = "/api/graph"
route_already_exists = False
for route in app.routes:
if (
isinstance(route, APIRoute)
and route.path == graph_path
and "GET" in route.methods
):
route_already_exists = True
break
if not route_already_exists:
app.get(
"/api/graph",
response_class=PlainTextResponse,
tags=["App"], # Explicitly set to only App tag
operation_id="get_graph_visualization", # Explicit operation_id to prevent duplicates
)(get_graph)
get_graph._auth_required = True # type: ignore[attr-defined]
get_graph._required_roles = _ADMIN_API_ROLES # type: ignore[attr-defined]
if not hasattr(get_graph, "_jvspatial_endpoint_config"):
get_graph._jvspatial_endpoint_config = {} # type: ignore[attr-defined]
get_graph._jvspatial_endpoint_config["auth_required"] = True # type: ignore[attr-defined]
get_graph._jvspatial_endpoint_config["roles"] = _ADMIN_API_ROLES # type: ignore[attr-defined]
__all__ = ["AppBuilder"]

Xet Storage Details

Size:
27 kB
·
Xet hash:
3abec5e42286e4e6cfba7beda8bd1dc9f02a4e1d44daab44b9d95a93466e33f3

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.