From f6c781a2a69c00191047ae5b153049dcdebb1118 Mon Sep 17 00:00:00 2001 From: Sau1707 <83017316+Sau1707@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:05:55 +0100 Subject: [PATCH] refactor!: simplify SDK runtime and model declarations Consolidate runtime route ownership and MCP dispatch, resolve build metadata once, and remove redundant CompanyDB forwarding. BREAKING CHANGE: Remove longlink.Model and UserRelationship. Use SQLModel or Audit with explicit user foreign-key fields and relationships, preserving existing column names and nullability. --- api/src/database/models/__init__.py | 1 - api/src/database/models/companies.py | 3 - api/src/database/services/companies.py | 2 +- api/src/routes/v1/companies.py | 2 +- api/tests/database/services/test_companies.py | 3 +- api/tests/routes/v1/test_companies.py | 2 +- sdk/longlink/.static/new/AGENTS.md | 17 +++- sdk/longlink/__init__.py | 3 - sdk/longlink/app.py | 36 +++++---- sdk/longlink/cli/build.py | 31 +++----- sdk/longlink/database/base.py | 3 +- sdk/longlink/database/relations.py | 60 -------------- sdk/pyproject.toml | 3 - sdk/tests/cli/test_build.py | 78 ++++++------------- sdk/tests/database/test_relations.py | 51 +++++++----- sdk/tests/test_app.py | 54 ++++++++++++- web/src/platform/routes/docs/sdk/database.tsx | 29 +++---- 17 files changed, 170 insertions(+), 208 deletions(-) delete mode 100644 api/src/database/models/companies.py delete mode 100644 sdk/longlink/database/relations.py diff --git a/api/src/database/models/__init__.py b/api/src/database/models/__init__.py index 2e1180d52..6674cb3ed 100644 --- a/api/src/database/models/__init__.py +++ b/api/src/database/models/__init__.py @@ -3,7 +3,6 @@ from src.database.models import users as users from src.database.models import computes as computes from src.database.models import invoices as invoices -from src.database.models import companies as companies from src.database.models import solutions as solutions from src.database.models import operations as operations from src.database.models import registries as registries diff --git a/api/src/database/models/companies.py b/api/src/database/models/companies.py deleted file mode 100644 index 940712d03..000000000 --- a/api/src/database/models/companies.py +++ /dev/null @@ -1,3 +0,0 @@ -from longlink import CompanyDB - -__all__ = ["CompanyDB"] diff --git a/api/src/database/services/companies.py b/api/src/database/services/companies.py index 2ef6e2514..29eda0272 100644 --- a/api/src/database/services/companies.py +++ b/api/src/database/services/companies.py @@ -1,4 +1,5 @@ from fastapi import HTTPException +from longlink import CompanyDB from sqlmodel import col from sqlalchemy import or_, func, select from sqlalchemy.orm import defer @@ -6,7 +7,6 @@ from src.database.types import attr from src.models.pagination import Pagination from sqlalchemy.ext.asyncio import AsyncSession -from src.database.models.companies import CompanyDB async def fetch(session: AsyncSession, pagination: Pagination, query: str | None) -> tuple[Sequence[CompanyDB], int]: diff --git a/api/src/routes/v1/companies.py b/api/src/routes/v1/companies.py index 80b8eb7b3..accc1c6dc 100644 --- a/api/src/routes/v1/companies.py +++ b/api/src/routes/v1/companies.py @@ -1,10 +1,10 @@ from src import auth from typing import Annotated from fastapi import Path, Query, Depends, Response, APIRouter +from longlink import CompanyDB from src.models.companies import CompanyPage, CompanyProfile from src.database.services import companies from src.models.pagination import Pagination -from src.database.models.companies import CompanyDB router = APIRouter(prefix="/companies") diff --git a/api/tests/database/services/test_companies.py b/api/tests/database/services/test_companies.py index f6f42619b..2e3177066 100644 --- a/api/tests/database/services/test_companies.py +++ b/api/tests/database/services/test_companies.py @@ -2,12 +2,11 @@ import sqlalchemy import sqlalchemy.exc import sqlalchemy.event -from longlink import LegalForm +from longlink import CompanyDB, LegalForm from src.database.session import session_scope from src.models.companies import CompanyProfile, CompanySummary from src.database.services import companies from src.models.pagination import Pagination -from src.database.models.companies import CompanyDB async def test_company_profiles_serialize_detached_without_loading_logos_or_references() -> None: diff --git a/api/tests/routes/v1/test_companies.py b/api/tests/routes/v1/test_companies.py index 8ae9cd304..aeedca895 100644 --- a/api/tests/routes/v1/test_companies.py +++ b/api/tests/routes/v1/test_companies.py @@ -1,7 +1,7 @@ import pytest from httpx2 import AsyncClient +from longlink import CompanyDB from src.database.session import session_scope -from src.database.models.companies import CompanyDB async def test_company_logo_serves_stored_webp_from_public_profile(client: AsyncClient) -> None: diff --git a/sdk/longlink/.static/new/AGENTS.md b/sdk/longlink/.static/new/AGENTS.md index 379d46159..be3fdcbd7 100644 --- a/sdk/longlink/.static/new/AGENTS.md +++ b/sdk/longlink/.static/new/AGENTS.md @@ -1,8 +1,10 @@ + LongLink v CLI: run every command as `uv run longlink ` (shown below as `longlink ...`). PRINCIPLES: + - KISS: Choose the simplest correct implementation. - SRP / Separation of concerns: Keep responsibilities focused and ownership clear. - High cohesion / Low coupling: Keep related behavior together and reduce unnecessary dependencies. @@ -10,6 +12,7 @@ PRINCIPLES: - DRY: Avoid duplicated knowledge or business rules. AVOID abstractions that only remove superficial code similarity. STRUCTURE: + ```t ├── src/ │ ├── assets/ # Repository static assets (JSON, files, loogs, ...) @@ -25,14 +28,15 @@ STRUCTURE: ``` RULES: + - USE `ctx.database` to access the database session. - USE `ctx.storage` to access the storage filesystem. - USE `longlink.Audit` for Platform-user attribution. -- USE `UserRelationship()` to save users into a table. - USE `ctx.user` to access the current user informations - DO run formatting, linting, type checking, and relevant existing tests. SERVICES AND UTILS: + - USE `src/services/` for business logic and integrations, with one module per domain or service (`tasks.py`, `mail.py`, `s3.py`). - USE `src/utils/` for generic reusable helpers (`dates.py`); AVOID business logic, integrations, and catch-all modules. - REUSE existing modules; keep single-use logic with its caller unless extraction improves clarity. @@ -40,6 +44,7 @@ SERVICES AND UTILS: - KEEP services and utilities independent of routes and views, with explicit inputs; PREFER functions unless state or resource lifecycles require classes. PYTHON: + - AVOID renaming imports. - DO use clear domain names. - DO FOLLOW the zen of python. @@ -62,6 +67,7 @@ PYTHON: - DO store asynchronous query results in a named variable before calling `.all()`, `.one_or_none()`. TESTING: + - DO use Arrange, Act, and Assert sections. - DO mock external boundaries, not business logic. - DO use `longlink.testclient.TestClient` for route tests. @@ -70,6 +76,7 @@ TESTING: - Where practical, PREFER real implementations and explicit dependency boundaries to mocks or global runtime-state changes. VIEWS: + - PREFER explicit async/await. - DO add JSDoc to JavaScript functions. - MINIMIZE comment to the bare minimun. @@ -79,9 +86,9 @@ VIEWS: - DO extract components only for meaningful UI boundaries. - AVOID unnecessary UI microcopy or decorative text elements. - Each view IDEALLY have one scope and one primary presentation - - Table view: one table for one dataset. - - Menu view: one menu for related options or sections. - - Card view: one card-based presentation for one scope. + - Table view: one table for one dataset. + - Menu view: one menu for related options or sections. + - Card view: one card-based presentation for one scope. - USE the exposed LongLink View components for layout and presentation. Use native HTML for semantics such as forms. Keep custom components for functionality unavailable through the exposed API. - AVOID duplicated derived state and effects that do not synchronize with external systems. - DON'T add standalone explanatory, onboarding, or empty-state sentences around the primary content. @@ -89,10 +96,12 @@ VIEWS: - FOLLOW a prop-driven component philosophy: configure layout, alignment, spacing, and styling through component props rather than utility classes or custom CSS. Exposed components do not accept `className` or `style`; preserve their default styling. DOCS: + - USE `longlink migrate` to generate migrations - USE `longlink docs --help` to lists documentation commands: - USE `longlink docs group ` to browse a component group - USE `longlink docs build ""` for implementation outline and relevant APIs - USE `longlink docs search ""` to find supported components and runtime APIs - USE `longlink docs component ` to get props, runtime members, and usage guidance + diff --git a/sdk/longlink/__init__.py b/sdk/longlink/__init__.py index 4727e4bd5..f3f4959d0 100644 --- a/sdk/longlink/__init__.py +++ b/sdk/longlink/__init__.py @@ -6,7 +6,6 @@ from .database.users import User from .database.platform import PlatformModel from .database.companies import Company, CompanyDB -from .database.relations import Model, UserRelationship from .utils.environments import Environments from .database.legalforms import LegalForm @@ -19,9 +18,7 @@ "Environments", "LongLink", "LegalForm", - "Model", "PlatformModel", "User", - "UserRelationship", "permissions", ] diff --git a/sdk/longlink/app.py b/sdk/longlink/app.py index feb8bc382..f906438aa 100644 --- a/sdk/longlink/app.py +++ b/sdk/longlink/app.py @@ -16,7 +16,7 @@ from longlink.routing import RouteDecorators from longlink.storage import Storage, create_storage from fastapi.responses import Response, RedirectResponse -from starlette.routing import Match, Mount +from starlette.routing import Match, Mount, Route from longlink.constants import ROOT from longlink.middleware import FrontendMiddleware from fastapi.openapi.utils import get_openapi @@ -100,9 +100,12 @@ def __init__(self) -> None: if not any(isinstance(item, ApiAccessFilter) for item in access_logger.filters): access_logger.addFilter(ApiAccessFilter()) - # Mount SDK-managed routes before user-facing assets. - runtime_router = router(view_manifest) - self.include_router(runtime_router) + # Own framework documentation and SDK endpoints in one private router branch. + self._runtime_router = APIRouter(routes=self.router.routes[:]) + self.router.routes.clear() + self._runtime_router.include_router(router(view_manifest)) + self.include_router(self._runtime_router) + self._runtime_branch = self.router.routes[-1] # Only production requests with a valid Platform identity may reach Solution routes. self.add_middleware(IdentityMiddleware, identity_secret=settings.IDENTITY_SECRET, mode=settings.ENV) @@ -111,11 +114,11 @@ def __init__(self) -> None: # Views are registered once before the frontend mount is installed. for definition, content in discovered_views: - self.add_api_route(f"/{definition.path}", _view_handler(content), methods=["GET"], include_in_schema=False) + self._runtime_router.add_api_route(f"/{definition.path}", _view_handler(content), methods=["GET"], include_in_schema=False) # Reserve the root redirect only when automatic navigation has a target. if view_manifest.resolved_tabs(): - self.add_api_route("/", self._redirect_root, methods=["GET"], include_in_schema=False) + self._runtime_router.add_api_route("/", self._redirect_root, methods=["GET"], include_in_schema=False) # Share the manifest catalog after registering Views so they cannot collide with themselves. self._view_manifest = view_manifest @@ -174,11 +177,15 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[Mapping[str, Any]]: await stack.enter_async_context(client) mcp = FastMCP.from_openapi(openapi_spec=schema, client=client, name=self.title) - # Close MCP and remove its temporary routes before closing the client and application. + # Close MCP and remove its exact endpoint before closing the client and application. mcp_app = mcp.http_app(path="/mcp", json_response=True) - self.router.routes[0:0] = mcp_app.routes - for route in mcp_app.routes: - stack.callback(self.router.routes.remove, route) + mcp_route = Route("/mcp", endpoint=mcp_app) + + # Invalidate FastAPI's included-router cache on both insertion and removal. + self._runtime_router.routes.insert(0, mcp_route) + self._runtime_router._mark_routes_changed() + stack.callback(self._runtime_router._mark_routes_changed) + stack.callback(self._runtime_router.routes.remove, mcp_route) await stack.enter_async_context(mcp_app.lifespan(mcp_app)) yield state or {} @@ -186,7 +193,6 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[Mapping[str, Any]]: # Serve the embedded frontend as low-priority routes so Solution routes take precedence. self.frontend("/", directory=frontend_directory) - self._runtime_routes = {id(route.original_route) for route in iter_route_contexts(self.routes)} def permission_routes(self) -> list[RouteContext]: """Select the same registered business routes during build inspection and startup.""" @@ -195,9 +201,8 @@ def permission_routes(self) -> list[RouteContext]: # Static assets use application-wide identity admission, not business endpoint grants. routes = [ route - for route in iter_route_contexts(self.routes) - if id(route.original_route) not in self._runtime_routes - and not (isinstance(route.original_route, Mount) and isinstance(route.original_route.app, StaticFiles)) + for route in iter_route_contexts([branch for branch in self.routes if branch is not self._runtime_branch]) + if not (isinstance(route.original_route, Mount) and isinstance(route.original_route.app, StaticFiles)) ] if any(not isinstance(route.original_route, APIRoute) for route in routes): raise ValueError("Solution permissions require FastAPI API routes; only StaticFiles mounts are supported") @@ -245,8 +250,7 @@ def include_view( # Explicit nested tabs need a redirect even when there were no automatic root tabs. if needs_root_redirect: - self.add_api_route("/", self._redirect_root, methods=["GET"], include_in_schema=False) - self._runtime_routes.add(id(self.routes[-1])) + self._runtime_router.add_api_route("/", self._redirect_root, methods=["GET"], include_in_schema=False) async def _redirect_root(self) -> RedirectResponse: """Resolve the first tab after Solution navigation registration is complete.""" diff --git a/sdk/longlink/cli/build.py b/sdk/longlink/cli/build.py index 7d6a1bfe3..ffc44e630 100644 --- a/sdk/longlink/cli/build.py +++ b/sdk/longlink/cli/build.py @@ -6,6 +6,7 @@ import tomllib import tempfile import subprocess +from typing import cast from pathlib import Path from longlink import images, metadata, permissions from pydantic import TypeAdapter, ValidationError @@ -143,7 +144,7 @@ def read_pyproject(root: Path) -> dict[str, object]: raise errors.Error(f"Invalid project file {pyproject}: {error}") from error -def read_project_metadata(pyproject_data: Mapping[str, object]) -> tuple[str, str, str | None]: +def read_project_metadata(pyproject_data: Mapping[str, object]) -> tuple[str, str]: """Validate the Solution name, version, and optional description.""" # Require the image metadata before creating any build artifacts. @@ -162,7 +163,7 @@ def read_project_metadata(pyproject_data: Mapping[str, object]) -> tuple[str, st if project_description is not None and not isinstance(project_description, str): raise errors.Error("[project].description must be a string") - return project_name, project_version, project_description + return project_name, project_version def normalize_package_name(name: str) -> str: @@ -432,15 +433,7 @@ def validate_lockfile(lockfile: Path, workspace_root: Path) -> None: _validate_metadata_target(lockfile, workspace_root, "Lockfile") -def build_solution( - root: Path, - build_context: Path, - *, - pyproject_data: Mapping[str, object], - project_version: str, - project_description: str | None, - version: str | None = None, -) -> None: +def build_solution(root: Path, build_context: Path, *, pyproject_data: Mapping[str, object], version: str) -> None: """Create Docker build artifacts from validated Solution metadata.""" # Resolve build paths using the project metadata prepared by the command. @@ -473,7 +466,9 @@ def build_solution( sdk_version = "0.0.0" # Render standard OCI metadata and LongLink-specific runtime metadata. - labels = [f"LABEL org.opencontainers.image.version={json.dumps(version if version is not None else project_version)}"] + project_data = cast(Mapping[str, object], pyproject_data["project"]) + project_description = project_data.get("description") + labels = [f"LABEL org.opencontainers.image.version={json.dumps(version)}"] if project_description is not None: labels.append(f"LABEL org.opencontainers.image.description={json.dumps(project_description)}") if banner is not None: @@ -639,9 +634,10 @@ def build_command( # Validate the project and Docker prerequisites before copying source files. root = Path.cwd().resolve() pyproject_data = read_pyproject(root) - solution_name, project_version, project_description = read_project_metadata(pyproject_data) + solution_name, project_version = read_project_metadata(pyproject_data) if version is not None and (not version or any(character.isspace() or not character.isprintable() for character in version)): raise errors.Error("Image version must be nonempty and contain no whitespace or control characters") + embedded_version = version if version is not None else project_version image_tag = resolve_image_tag(solution_name, tag or project_version, registry) image_tags = [image_tag] @@ -661,14 +657,7 @@ def build_command( # Release copied sources as soon as the Docker build finishes. with tempfile.TemporaryDirectory(prefix="longlink-build-") as temp_dir: build_context = Path(temp_dir) - build_solution( - root, - build_context, - pyproject_data=pyproject_data, - project_version=project_version, - project_description=project_description, - version=version, - ) + build_solution(root, build_context, pyproject_data=pyproject_data, version=embedded_version) docker_build_command = [docker_command, "build", "--platform", "linux/amd64", "-f", str(build_context / "Dockerfile")] for image_tag in image_tags: diff --git a/sdk/longlink/database/base.py b/sdk/longlink/database/base.py index 55f44bcfb..89ab7eb32 100644 --- a/sdk/longlink/database/base.py +++ b/sdk/longlink/database/base.py @@ -13,13 +13,12 @@ from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine from longlink.database.users import User from longlink.utils.settings import Envs -from longlink.database.relations import Model from sqlmodel.ext.asyncio.session import AsyncSession LOCAL_USER_ID = UUID("00000000-0000-0000-0000-000000000001") -class Audit(Model): +class Audit(SQLModel): """Base SQLModel for Solution tables that track Platform users.""" model_config = SQLModelConfig(ignored_types=(declared_attr,)) diff --git a/sdk/longlink/database/relations.py b/sdk/longlink/database/relations.py deleted file mode 100644 index 018d3567f..000000000 --- a/sdk/longlink/database/relations.py +++ /dev/null @@ -1,60 +0,0 @@ -from uuid import UUID -from typing import Any, cast -from sqlmodel import Field, SQLModel, Relationship -from sqlmodel.main import SQLModelMetaclass, get_annotations -from longlink.database.users import User - - -class _UserRelationship: - """Mark a user relationship for expansion before SQLModel maps a table.""" - - -def UserRelationship() -> User: - """Declare a local user relationship; a User | None annotation makes it optional.""" - - return cast(User, _UserRelationship()) - - -class _ModelMetaclass(SQLModelMetaclass): - """Expand named user relations before SQLModel processes field annotations.""" - - def __new__(cls, name: str, bases: tuple[type[Any], ...], class_dict: dict[str, Any], **kwargs: object) -> type[SQLModel]: - """Add one UUID foreign key and relationship for each user marker.""" - - # Leave ordinary SQLModel declarations untouched. - relations = [key for key, value in class_dict.items() if isinstance(value, _UserRelationship)] - if not relations: - return super().__new__(cls, name, bases, class_dict, **kwargs) - - namespace = dict(class_dict) - annotations = dict(get_annotations(namespace)) - - # Each relationship owns a distinct foreign key to the Solution's users table. - for relation in relations: - annotation = annotations.get(relation) - optional = annotation in (User | None, "User | None", "longlink.database.users.User | None") - if not optional and annotation not in (User, "User", "longlink.database.users.User"): - raise TypeError(f"{relation} must be annotated as User") - - # Resolve supported postponed user annotations before SQLAlchemy maps relationships. - annotations[relation] = User | None if optional else User - column = f"{relation}_id" - if column in namespace or column in annotations: - raise ValueError(f"{column} is managed by UserRelationship()") - - # Match the generated foreign key's nullability to the relationship annotation. - if optional: - annotations[column] = UUID | None - namespace[column] = Field(default=None, foreign_key="users.id") - else: - annotations[column] = UUID - namespace[column] = Field(foreign_key="users.id") - namespace[relation] = Relationship(sa_relationship_kwargs={"foreign_keys": f"[{name}.{column}]", "lazy": "selectin"}) - - # SQLModel must see the expanded annotations before mapping the table. - namespace["__annotations__"] = annotations - return super().__new__(cls, name, bases, namespace, **kwargs) - - -class Model(SQLModel, metaclass=_ModelMetaclass): - """Base for Solution tables with declarative local user relationships.""" diff --git a/sdk/pyproject.toml b/sdk/pyproject.toml index 3b01fe262..7d8fdc03a 100644 --- a/sdk/pyproject.toml +++ b/sdk/pyproject.toml @@ -124,9 +124,6 @@ ignore = ["D100", "D104", "D202"] # JWT algorithm and audience names are public protocol constants. "longlink/identity.py" = ["S105"] -[tool.ruff.lint.pep8-naming] -ignore-names = ["UserRelationship"] - [tool.ruff.lint.isort] no-sections = true length-sort = true diff --git a/sdk/tests/cli/test_build.py b/sdk/tests/cli/test_build.py index 712de3d2d..6ef73454e 100644 --- a/sdk/tests/cli/test_build.py +++ b/sdk/tests/cli/test_build.py @@ -444,17 +444,11 @@ def missing_package_version(_package: str) -> str: project = chdir_project / "pyproject.toml" project.write_text(project.read_text(encoding="utf-8") + f"banner = {json.dumps(banner)}\n", encoding="utf-8") pyproject_data = build.read_pyproject(chdir_project) - _, project_version, project_description = build.read_project_metadata(pyproject_data) + _, project_version = build.read_project_metadata(pyproject_data) # Act with chdir(chdir_project.parent): - build.build_solution( - chdir_project, - build_context, - pyproject_data=pyproject_data, - project_version=project_version, - project_description=project_description, - ) + build.build_solution(chdir_project, build_context, pyproject_data=pyproject_data, version=project_version) # Assert dockerfile = build_context.joinpath("Dockerfile").read_text(encoding="utf-8") @@ -539,16 +533,10 @@ def test_build_solution_filters_symlinks_by_resolved_target(chdir_project: Path) # Read project metadata before rendering the build artifacts. pyproject_data = build.read_pyproject(chdir_project) - _, project_version, project_description = build.read_project_metadata(pyproject_data) + _, project_version = build.read_project_metadata(pyproject_data) # Act - build.build_solution( - chdir_project, - build_context, - pyproject_data=pyproject_data, - project_version=project_version, - project_description=project_description, - ) + build.build_solution(chdir_project, build_context, pyproject_data=pyproject_data, version=project_version) # Assert assert build_context.joinpath("linked-envs.py").readlink() == Path("src/envs.py") @@ -707,16 +695,10 @@ def test_build_solution_filters_expanded_context(chdir_project: Path) -> None: # Read project metadata before rendering the build artifacts. pyproject_data = build.read_pyproject(chdir_project) - _, project_version, project_description = build.read_project_metadata(pyproject_data) + _, project_version = build.read_project_metadata(pyproject_data) # Act - build.build_solution( - chdir_project, - build_context, - pyproject_data=pyproject_data, - project_version=project_version, - project_description=project_description, - ) + build.build_solution(chdir_project, build_context, pyproject_data=pyproject_data, version=project_version) # Assert assert not build_context.joinpath("solution", ".env").exists() @@ -794,12 +776,10 @@ def test_build_solution_preserves_workspace_manifests_without_unrelated_sources( ) context = workspace / "context" metadata = build.read_pyproject(build_project) - _, project_version, project_description = build.read_project_metadata(metadata) + _, project_version = build.read_project_metadata(metadata) # Act - build.build_solution( - build_project, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + build.build_solution(build_project, context, pyproject_data=metadata, version=project_version) # Assert dockerfile = context.joinpath("Dockerfile").read_text(encoding="utf-8") @@ -831,12 +811,10 @@ def test_build_solution_copies_literal_manifest_only_paths(build_project: Path, member.joinpath("source.py").write_text("VALUE = 1\n", encoding="utf-8") context = workspace / "context" metadata = build.read_pyproject(build_project) - _, project_version, project_description = build.read_project_metadata(metadata) + _, project_version = build.read_project_metadata(metadata) # Act - build.build_solution( - build_project, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + build.build_solution(build_project, context, pyproject_data=metadata, version=project_version) # Assert copied_member = context / "members" / member_name @@ -852,14 +830,12 @@ def test_build_solution_requires_workspace_lockfile(build_project: Path) -> None workspace = build_project.parent workspace.joinpath("pyproject.toml").write_text('[tool.uv.workspace]\nmembers = ["solution"]\n', encoding="utf-8") metadata = build.read_pyproject(build_project) - _, project_version, project_description = build.read_project_metadata(metadata) + _, project_version = build.read_project_metadata(metadata) context = workspace / "context" # Act and assert with pytest.raises(errors.Error, match="Lockfile not found"): - build.build_solution( - build_project, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + build.build_solution(build_project, context, pyproject_data=metadata, version=project_version) assert not context.exists() @@ -878,7 +854,7 @@ def test_build_solution_rechecks_lockfile_after_model_import(build_project: Path encoding="utf-8", ) metadata = build.read_pyproject(build_project) - _, project_version, project_description = build.read_project_metadata(metadata) + _, project_version = build.read_project_metadata(metadata) # Keep generated build context separate from the source project. context = build_project.parent / "context" @@ -888,9 +864,7 @@ def test_build_solution_rechecks_lockfile_after_model_import(build_project: Path # Reject the changed lockfile after inspection and before the explicit metadata copy. with pytest.raises(errors.Error, match=message): - build.build_solution( - build_project, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + build.build_solution(build_project, context, pyproject_data=metadata, version=project_version) assert not context.joinpath("uv.lock").exists() @@ -915,14 +889,12 @@ def test_build_solution_rejects_unsafe_solution_paths(build_project: Path, direc ) workspace.joinpath("uv.lock").write_text("workspace lock", encoding="utf-8") metadata = build.read_pyproject(build_project) - _, project_version, project_description = build.read_project_metadata(metadata) + _, project_version = build.read_project_metadata(metadata) context = workspace / "context" # Act and assert with pytest.raises(errors.Error, match=f"must not contain {message}"): - build.build_solution( - build_project, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + build.build_solution(build_project, context, pyproject_data=metadata, version=project_version) assert not context.exists() @@ -933,7 +905,7 @@ def test_build_solution_rejects_unsafe_metadata_symlinks(build_project: Path, fi # Arrange metadata = build.read_pyproject(build_project) - _, project_version, project_description = build.read_project_metadata(metadata) + _, project_version = build.read_project_metadata(metadata) original = build_project / filename content = original.read_text(encoding="utf-8") if original.exists() else "private lockfile" target = build_project.parent / "outside.toml" if target_kind == "outside" else build_project / ".env" @@ -945,9 +917,7 @@ def test_build_solution_rejects_unsafe_metadata_symlinks(build_project: Path, fi # Act and assert with pytest.raises(errors.Error, match=message): - build.build_solution( - build_project, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + build.build_solution(build_project, context, pyproject_data=metadata, version=project_version) assert not context.joinpath(filename).exists() @@ -1163,10 +1133,8 @@ def test_generated_python_matches_inspector_and_is_available_in_uv_catalog(build ["uv", "lock", "--project", str(build_project), "--python", sys.executable, "--offline"], capture_output=True, text=True, check=True ) metadata = build.read_pyproject(build_project) - _, project_version, project_description = build.read_project_metadata(metadata) - build.build_solution( - build_project, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + _, project_version = build.read_project_metadata(metadata) + build.build_solution(build_project, context, pyproject_data=metadata, version=project_version) instructions = context.joinpath("Dockerfile").read_text(encoding="utf-8").splitlines() python_version = next(line.removeprefix("RUN uv python install ") for line in instructions if line.startswith("RUN uv python install ")) @@ -1256,10 +1224,8 @@ def test_generated_context_copy_preserves_literal_workspace_paths(tmp_path: Path # Generate the actual context and retain copy instructions verbatim, not reconstructed arguments. context = tmp_path / "context" metadata = build.read_pyproject(solution) - _, project_version, project_description = build.read_project_metadata(metadata) - build.build_solution( - solution, context, pyproject_data=metadata, project_version=project_version, project_description=project_description - ) + _, project_version = build.read_project_metadata(metadata) + build.build_solution(solution, context, pyproject_data=metadata, version=project_version) assert not context.joinpath("unrelated", "private.txt").exists() assert context.joinpath("shared", "source.py").is_file() generated_lines = context.joinpath("Dockerfile").read_text(encoding="utf-8").splitlines() diff --git a/sdk/tests/database/test_relations.py b/sdk/tests/database/test_relations.py index 85419b2f4..8337ed884 100644 --- a/sdk/tests/database/test_relations.py +++ b/sdk/tests/database/test_relations.py @@ -1,25 +1,24 @@ -from __future__ import annotations - import pytest from uuid import UUID from typing import ClassVar -from longlink import User, Model, UserRelationship -from sqlmodel import Field, SQLModel +from longlink import User, Audit +from sqlmodel import Field, SQLModel, Relationship from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import registry from longlink.database import base as database_base +from longlink.database import audit from longlink.utils.settings import Envs async def test_user_relationships_persist_required_and_optional_roles() -> None: - """Persist distinct user roles and reject a missing required owner.""" + """Persist independent user roles alongside audit identities and require an owner.""" # Own cleanup before any declaration or constructor can configure a failing mapper. mapper_registry = registry(metadata=SQLModel.metadata, class_registry={"User": User}) database = database_base.Database(Envs(ENV="testing")) try: - # Arrange postponed annotations for both required and optional user roles. - class RelationshipModel(Model, registry=mapper_registry): + # Arrange explicit user roles alongside inherited audit relationships. + class RelationshipModel(Audit, registry=mapper_registry): """Own only this test's temporary mapper while sharing real table metadata.""" class UserRoleItem(RelationshipModel, table=True): @@ -31,9 +30,15 @@ class UserRoleItem(RelationshipModel, table=True): # Identifier id: int | None = Field(default=None, primary_key=True) - # User roles - owner: User = UserRelationship() - approved_by: User | None = UserRelationship() + # User identifiers + owner_id: UUID = Field(foreign_key="users.id") + approved_by_id: UUID | None = Field(default=None, foreign_key="users.id") + + # User relationships + owner: User = Relationship(sa_relationship_kwargs={"foreign_keys": "[UserRoleItem.owner_id]", "lazy": "selectin"}) + approved_by: User | None = Relationship( + sa_relationship_kwargs={"foreign_keys": "[UserRoleItem.approved_by_id]", "lazy": "selectin"} + ) owner = User(id=UUID("00000000-0000-0000-0000-000000000002"), name="Owner", email="owner@example.com") approver = User(id=UUID("00000000-0000-0000-0000-000000000003"), name="Approver", email="approver@example.com") @@ -41,10 +46,11 @@ class UserRoleItem(RelationshipModel, table=True): # Act async with database.session() as session: session.add_all([owner, approver]) - unapproved = UserRoleItem(owner=owner) - approved = UserRoleItem(owner=owner, approved_by=approver) + unapproved = UserRoleItem(owner_id=owner.id, owner=owner) + approved = UserRoleItem(owner_id=owner.id, owner=owner, approved_by=approver) session.add_all([unapproved, approved]) - await session.commit() + with audit.actor(database_base.LOCAL_USER_ID): + await session.commit() unapproved_id = unapproved.id approved_id = approved.id @@ -52,29 +58,34 @@ class UserRoleItem(RelationshipModel, table=True): async with database.session() as session: unapproved = await session.get(UserRoleItem, unapproved_id) assert unapproved is not None - assert getattr(unapproved, "owner_id") == owner.id + assert unapproved.owner_id == owner.id assert unapproved.owner.id == owner.id - assert getattr(unapproved, "approved_by_id") is None + assert unapproved.approved_by_id is None assert unapproved.approved_by is None # Inspect a second row with an explicitly assigned optional approver. approved = await session.get(UserRoleItem, approved_id) assert approved is not None - # Generated foreign keys must retain their independently assigned user identities. - assert getattr(approved, "owner_id") == owner.id + # Explicit roles must not overwrite the audit identities. + assert approved.owner_id == owner.id assert approved.owner.id == owner.id - assert getattr(approved, "approved_by_id") == approver.id + assert approved.approved_by_id == approver.id assert approved.approved_by is not None assert approved.approved_by.id == approver.id + assert approved.created_id == database_base.LOCAL_USER_ID + assert approved.updated_id == database_base.LOCAL_USER_ID + assert approved.created_by.id == database_base.LOCAL_USER_ID + assert approved.updated_by.id == database_base.LOCAL_USER_ID # Verify required relations through actual persistence. async with database.session() as session: - session.add(UserRoleItem()) + session.add(UserRoleItem()) # ty: ignore[missing-argument] # Required user relations remain enforced by the database. with pytest.raises(IntegrityError, match="NOT NULL constraint failed: test_user_role_items.owner_id"): - await session.commit() + with audit.actor(database_base.LOCAL_USER_ID): + await session.commit() await session.rollback() finally: # Release each local resource even if another cleanup step fails. diff --git a/sdk/tests/test_app.py b/sdk/tests/test_app.py index 657108bc2..969e8786c 100644 --- a/sdk/tests/test_app.py +++ b/sdk/tests/test_app.py @@ -4,7 +4,7 @@ import longlink from uuid import UUID from typing import Annotated -from fastapi import Header, Depends, Response, APIRouter, HTTPException +from fastapi import Header, Depends, Request, Response, APIRouter, HTTPException from pathlib import Path from longlink import User, Context, identity, permissions from longlink import app as longlink_app @@ -17,6 +17,7 @@ from longlink.database import audit, migrations from sqlalchemy.engine import Engine from fastapi.testclient import TestClient +from starlette.staticfiles import StaticFiles from longlink.database.base import Database from longlink.utils.settings import Envs @@ -404,6 +405,54 @@ async def settings_get_endpoint() -> dict[str, str]: assert root_response.status_code == 404 +def test_late_nested_tab_redirect_stays_outside_business_permissions(solution_source: Path) -> None: + """Serve an explicitly included nested tab without discovering runtime endpoints as business routes.""" + + # Arrange + directory = solution_source / "views" / "admin" + directory.mkdir() + (directory / "dashboard.jsx").write_text("export default function Dashboard() { return Dashboard; }", encoding="utf-8") + app = LongLink() + client = TestClient(app) + assert client.get("/", follow_redirects=False).status_code == 200 + + # Act + app.include_view("admin/dashboard.jsx") + with client: + response = client.get("/", follow_redirects=False) + manifest = client.get("/views.json") + documentation = client.get("/openapi.json") + catalog = app.state.permission_catalog + + # Assert + assert response.status_code == 307 + assert response.headers["location"] == "/admin/dashboard" + assert manifest.json()["tabs"] == [{"route": "/admin/dashboard"}] + assert documentation.status_code == 200 + assert catalog.endpoints == [] + assert app.permission_routes() == [] + + +@pytest.mark.usefixtures("solution_source") +def test_permission_discovery_admits_static_files_but_rejects_unguarded_routes(tmp_path: Path) -> None: + """Keep static admission separate from business guards without admitting arbitrary ASGI handlers.""" + + # Arrange + app = LongLink() + app.mount("/files", StaticFiles(directory=tmp_path)) + + async def unguarded_endpoint(request: Request) -> Response: + """Represent a handler outside FastAPI's permission contract.""" + + return Response("unguarded") + + # Act and assert + assert app.permission_routes() == [] + app.add_route("/unguarded", unguarded_endpoint) + with pytest.raises(ValueError, match="Solution permissions require FastAPI API routes"): + app.permission_routes() + + @pytest.mark.usefixtures("solution_source") def test_solution_add_api_route_rejects_view_endpoint_overlap(solution_source: Path) -> None: """Reject a direct Solution route that would overlap a registered View endpoint.""" @@ -762,10 +811,13 @@ def test_empty_mcp_catalog_does_not_allow_internal_tools() -> None: "/mcp", json={"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "get_views_views_json_get", "arguments": {}}}, ) + slash = client.post("/mcp/", json={"jsonrpc": "2.0", "id": 4, "method": "tools/list"}, follow_redirects=False) # Excluding a tool applies to execution, not only discovery. assert discovery.json()["result"]["tools"] == [] assert invocation.json()["result"]["isError"] is True + assert slash.status_code == 307 + assert slash.headers["location"].endswith("/mcp") @pytest.mark.usefixtures("solution_source") diff --git a/web/src/platform/routes/docs/sdk/database.tsx b/web/src/platform/routes/docs/sdk/database.tsx index 1c84aaa61..23d6e35de 100644 --- a/web/src/platform/routes/docs/sdk/database.tsx +++ b/web/src/platform/routes/docs/sdk/database.tsx @@ -70,36 +70,39 @@ async def create_project(ctx: Context) -> None: email, avatar, and profile update timestamp. Authenticated requests refresh the requesting user's profile before your route runs. Profiles remain at their last-seen values until the user returns; this table is not an organization membership directory. Use Audit{' '} - for automatic attribution or - UserRelationship() to add a named user relationship. + for automatic attribution or standard SQLModel fields and relationships for named user roles.

- Audit adds creation, update, and deletion timestamps; matching Platform - user IDs; and relationships to local users. Use it only for tables that need this history. + Audit adds creation and update timestamps, matching Platform user IDs, and + relationships to local users. Use it only for tables that need this history.

- UserRelationship() gives owner its own required - foreign key to the local user table. Use Model instead of{' '} - Audit if you do not need audit history. Annotate a relationship as{' '} - User | None for an optional role, such as an invoice approver; its - generated foreign key defaults to null. + Declare owner_id with{' '} + Field(foreign_key="users.id") and owner with{' '} + Relationship. Set foreign_keys to distinguish the + owner from audit relationships and lazy="selectin" to load the user for + async access. Inherit from SQLModel instead of{' '} + Audit if you do not need audit history.

Project: """Create a project owned by an existing local user.""" - project = Project(name="Launch", owner=owner) + project = Project(name="Launch", owner_id=owner.id, owner=owner) ctx.database.add(project) await ctx.database.flush() return project