Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion api/src/database/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 0 additions & 3 deletions api/src/database/models/companies.py

This file was deleted.

2 changes: 1 addition & 1 deletion api/src/database/services/companies.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from fastapi import HTTPException
from longlink import CompanyDB
from sqlmodel import col
from sqlalchemy import or_, func, select
from sqlalchemy.orm import defer
from collections.abc import Sequence
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]:
Expand Down
2 changes: 1 addition & 1 deletion api/src/routes/v1/companies.py
Original file line number Diff line number Diff line change
@@ -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")

Expand Down
3 changes: 1 addition & 2 deletions api/tests/database/services/test_companies.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion api/tests/routes/v1/test_companies.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
17 changes: 13 additions & 4 deletions sdk/longlink/.static/new/AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,18 @@
<!-- LONGLINK:START -->

LongLink v<version>
CLI: run every command as `uv run longlink <cmd>` (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.
- YAGNI: Avoid features, abstractions, configuration, and extension points needed only for hypothetical future use.
- 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, ...)
Expand All @@ -25,21 +28,23 @@ 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.
- IMPORT modules (`from src.services import mail`, `from src.utils import dates`) and call their functions; AVOID re-exports.
- 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.
Expand All @@ -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.
Expand All @@ -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.
Expand All @@ -79,20 +86,22 @@ 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.
- DON'T add decorative containers, redundant labels, or explanatory text that repeats what the interface already makes clear.
- 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 <name>` to browse a component group
- USE `longlink docs build "<idea>"` for implementation outline and relevant APIs
- USE `longlink docs search "<query>"` to find supported components and runtime APIs
- USE `longlink docs component <Name>` to get props, runtime members, and usage guidance

<!-- LONGLINK:END -->
3 changes: 0 additions & 3 deletions sdk/longlink/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -19,9 +18,7 @@
"Environments",
"LongLink",
"LegalForm",
"Model",
"PlatformModel",
"User",
"UserRelationship",
"permissions",
]
36 changes: 20 additions & 16 deletions sdk/longlink/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -174,19 +177,22 @@ 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 {}

self.router.lifespan_context = lifespan

# 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."""
Expand All @@ -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")
Expand Down Expand Up @@ -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."""
Expand Down
31 changes: 10 additions & 21 deletions sdk/longlink/cli/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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]

Expand All @@ -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:
Expand Down
3 changes: 1 addition & 2 deletions sdk/longlink/database/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,))
Expand Down
Loading