C1a: code only, no comments, no Markdown

Remove 64 Python docstrings and 39 comments, and trim prose from three noqa pragmas. The submodule had zero tracked Markdown files.

Move published route descriptions into decorator arguments and the Correction schema description into ConfigDict. Drop internal docstrings, including the OAuth callback excluded from OpenAPI. Published route descriptions are unchanged in the before-and-after comparison of the nine application routers. The full application OpenAPI check requires fastapi-users, which is missing from the shared environment.
This commit is contained in:
2026-12-01 16:55:32 -06:00
parent 37c456c5ef
commit c326f4901d
13 changed files with 284 additions and 207 deletions
+52 -44
View File
@@ -1,6 +1,3 @@
"""The Conectar dialog: the kinds of source an operator can pick, "Probar conexión", the
server folders they may browse, and the files they upload. Open like the rest of the API."""
import os
import re
import shutil
@@ -20,28 +17,29 @@ router = APIRouter(prefix="/ingest", tags=["ingest"])
UPLOADS = "uploads"
@router.get("/sources/types")
@router.get(
"/sources/types",
description="Every kind of source the dialog offers, grouped, with the fields each one asks.",
)
def source_types() -> sources.Catalog:
"""Every kind of source the dialog offers, grouped, with the fields each one asks."""
return sources.catalog()
class Answers(BaseModel):
type: str
answers: dict[str, Any] = {}
pipeline: str | None = None # editing a saved source: its secrets come back masked
pipeline: str | None = None
node: str | None = None
class Tested(BaseModel):
ok: bool
message: str # in plain words, for the operator
detail: str | None = None # the source's own words, for whoever helps them
message: str
detail: str | None = None
tables: list[str] = []
rows: list[dict[str, Any]] = []
# What a source's own error means, in words an operator can act on (first match wins).
PLAIN = [
(
r"login failed|password authentication failed|access denied|authentication|"
@@ -92,11 +90,18 @@ def _with_saved_secrets(asked: Answers) -> dict[str, Any]:
return found.guided.answers
@router.post("/sources/test")
@router.post(
"/sources/test",
description=(
'"Probar conexión": reaches the source with the answers given. A '
"database lists its\n"
"tables (until one is picked; then its first rows); files and "
"records show their first\n"
"rows. Never a server error: what went wrong comes back in plain "
"words."
),
)
def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20) -> Tested:
""" "Probar conexión": reaches the source with the answers given. A database lists its
tables (until one is picked; then its first rows); files and records show their first
rows. Never a server error: what went wrong comes back in plain words."""
if asked.type not in sources.catalog().types:
raise HTTPException(404, detail=f"no source type {asked.type}")
answers = _with_saved_secrets(asked)
@@ -110,9 +115,9 @@ def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20)
tables=tables) # fmt: skip
node = Source(id="probe", guided={"type": asked.type, "answers": answers})
rows = [nodes.shown(r) for r in nodes.preview(node, limit)]
except (sources.MissingAnswer, ValidationError) as e: # an answer missing: plain words
except (sources.MissingAnswer, ValidationError) as e:
return Tested(ok=False, message=_missing(e))
except Exception as e: # noqa: BLE001 - whatever the source says goes back to the operator
except Exception as e: # noqa: BLE001
return Tested(ok=False, message=plain(e), detail=f"{type(e).__name__}: {e}"[:2000])
found = (
"Conexión correcta."
@@ -125,7 +130,7 @@ def test_source(asked: Answers, limit: Annotated[int, Query(ge=1, le=100)] = 20)
def _missing(e: Exception) -> str:
if isinstance(e, ValidationError): # raised while the node is made from the answers
if isinstance(e, ValidationError):
return next((str(err["ctx"]["error"]) for err in e.errors()
if isinstance(err.get("ctx", {}).get("error"), sources.MissingAnswer)),
str(e)) # fmt: skip
@@ -133,8 +138,6 @@ def _missing(e: Exception) -> str:
def roots() -> dict[str, Path]:
"""The folders the operator mounted for sources (SOURCE_ROOTS, separated by ":"), by
name; uploads always."""
found = {"Subidos": (DATA_DIR / UPLOADS).resolve()}
for raw in filter(None, os.environ.get("SOURCE_ROOTS", "").split(os.pathsep)):
path = Path(raw).resolve()
@@ -144,21 +147,26 @@ def roots() -> dict[str, Path]:
class Entry(BaseModel):
name: str
path: str # what a folder field takes
path: str
kind: Literal["folder", "file"]
size: int | None = None
class Browsed(BaseModel):
path: str | None # None: the list of roots
path: str | None
parent: str | None
entries: list[Entry]
@router.get("/sources/browse")
@router.get(
"/sources/browse",
description=(
"The server folders a source may read: the roots, or what one "
"folder under them\n"
"holds. Nothing outside the roots is shown."
),
)
def browse(path: str | None = None) -> Browsed:
"""The server folders a source may read: the roots, or what one folder under them
holds. Nothing outside the roots is shown."""
allowed = roots()
if path is None:
return Browsed(path=None, parent=None, entries=[
@@ -178,24 +186,28 @@ def browse(path: str | None = None) -> Browsed:
class Uploaded(BaseModel):
bucket_url: str # the folder: what an upload field and a filesystem source take
bucket_url: str
files: list[str]
def _relative(name: str) -> PurePosixPath:
"""A file's name as the browser sent it (a folder upload keeps its subfolders), never
reaching outside its folder."""
parts = [p for p in PurePosixPath(name.replace("\\", "/")).parts if p not in ("", ".", "..")]
if not parts:
raise HTTPException(422, detail="the file needs a name")
return PurePosixPath(*parts)
@router.post("/uploads")
@router.post(
"/uploads",
description=(
"Files from the operator's computer (one, many, or a whole "
"folder), kept on the\n"
"server for a `filesystem` source; streamed to disk, so large "
"recordings fit. Send\n"
"`folder` from a previous answer to add to the same set."
),
)
def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None) -> Uploaded:
"""Files from the operator's computer (one, many, or a whole folder), kept on the
server for a `filesystem` source; streamed to disk, so large recordings fit. Send
`folder` from a previous answer to add to the same set."""
base = (DATA_DIR / UPLOADS).resolve()
target = Path(folder).resolve() if folder else base / uuid.uuid4().hex[:12]
if target.parent != base:
@@ -211,10 +223,6 @@ def upload(files: list[UploadFile], folder: Annotated[str | None, Form()] = None
return Uploaded(bucket_url=str(target), files=kept)
# Sign-in buttons: OAuth 2.0 authorization code flow with PKCE (authlib). The dialog opens
# `start`'s address in a window; the provider sends the user back to `callback`, which
# hands the account to the dialog (window.opener) and closes. A pending sign-in is a file
# in the data folder for ten minutes, so whichever API worker gets the callback finds it.
PENDING = DATA_DIR / "oauth_pending"
PENDING_SECONDS = 600
STATE = re.compile(r"[A-Za-z0-9_-]{8,128}")
@@ -234,7 +242,6 @@ def _pend(state: str, pending: dict[str, Any]) -> None:
def _claimed(state: str) -> dict[str, Any] | None:
"""The pending sign-in of `state`, taken once (by an atomic rename), if still fresh."""
import json
import time
@@ -278,14 +285,19 @@ def _client(provider: sources.Provider, env: dict[str, str], redirect_uri: str):
class SignIn(BaseModel):
url: str # where the dialog's window goes
url: str
state: str
@router.get("/sources/oauth/{provider}/start")
@router.get(
"/sources/oauth/{provider}/start",
description=(
"The provider's sign-in address. `origin` is the web app's "
"(where the user returns:\n"
"`{origin}/api/…/callback`, the address IT registered)."
),
)
def oauth_start(provider: str, origin: str) -> SignIn:
"""The provider's sign-in address. `origin` is the web app's (where the user returns:
`{origin}/api/…/callback`, the address IT registered)."""
import secrets
found, env = _registration(provider)
@@ -300,9 +312,6 @@ def oauth_start(provider: str, origin: str) -> SignIn:
def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[str, Any]:
"""What a source needs to read as the signed-in user, and who they are (shown in the
dialog). Microsoft: msgraphfs's OAuth client parameters and the user's own drive;
Google: dlt's OAuth credentials for Drive."""
import httpx
found = sources.catalog().providers[provider]
@@ -330,7 +339,6 @@ def account(provider: str, token: dict[str, Any], env: dict[str, str]) -> dict[s
@router.get("/sources/oauth/{provider}/callback", include_in_schema=False)
def oauth_callback(provider: str, state: str, code: str | None = None, error: str | None = None):
"""Where the provider returns the user: the account goes to the dialog that asked."""
import json
from fastapi.responses import HTMLResponse
@@ -349,7 +357,7 @@ def oauth_callback(provider: str, state: str, code: str | None = None, error: st
_endpoint(found.token_url, env), code=code, code_verifier=pending["verifier"]
)
message["account"] = account(provider, dict(token), env)
except Exception as e: # noqa: BLE001 - shown to the person signing in
except Exception as e: # noqa: BLE001
message["error"] = f"No se pudo iniciar sesión: {e}"
payload = json.dumps(message).replace("</", "<\\/")
target = json.dumps(pending["origin"])