Files
jobboard/app/main.py
T
WolfandClaude Opus 5.5 59a301c351 Wire the app like the boilerplate: door, queue, schedules, eight tabs
app/main.py assembles it in the boilerplate's order, auth.connect first,
then the queue with the scheduler and the pages. TABS is Roles,
Applications, Agents, Companies, Jobs, Schedules, Messages and Account:
the alpha page's three views become templates on the boilerplate's
base.html, driven by static/roles.js (the old app.js) through api() and
toasts.js, over the unchanged JSON routes. Companies lists every board with
its open roles and the affinity control. A 422 is one sentence, so a toast
never reads [object Object].

Config takes the boilerplate's shape: APP_CONFIG or config.yaml, a missing
file is the defaults, an unknown key is an error. roles.yaml is gone;
config.yaml is the committed default and carries the starter agents.

pull is now a job that asks for the pull cascade, because a schedule
enqueues a job kind; its default schedule, every 6h, is declared beside it
in app/jobs/cascade.py. pull_batch's targets are keyword-only so the Jobs
tab offers no batch button. `app worker` is the boilerplate's; `app job`
still drains a queue of its own and fires no schedules.

test_coupling holds pipeline, auth and desk apart (desk may import
pipeline) and plugins to desk; test_architecture keeps app's layers, now
with main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 12:48:12 +02:00

119 lines
4.9 KiB
Python

"""The app, assembled.
uv run app serve
uv run uvicorn app.main:app --reload
`create_app()` is the whole of the wiring, and the order in it is the point:
config and store, the door, the queue, the pages. Everything before the queue
is something the queue needs; everything after it is something that enqueues.
"""
from __future__ import annotations
import logging
from typing import Any
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from starlette.exceptions import HTTPException as StarletteHTTPException
import auth
from app import jobs
from app.config import Config, load
from app.storage import Store
from app.web import STATIC_DIR, api_router, pages_router, templates
from pipeline import Jobs
from pipeline.web import connect
log = logging.getLogger(__name__)
#: Prefixes whose errors are JSON rather than a page. A caller that asked for
#: data gets `{"detail": ...}`; a browser that asked for a page gets one.
API_PREFIXES = ("/api", "/ws", "/_jobs", "/_auth", "/static", "/health")
def create_app(config: Config | None = None) -> FastAPI:
"""Build the application. A test passes its own config; nobody else does."""
config = config or load()
logging.basicConfig(
level=getattr(logging, str(config.log_level).upper(), logging.INFO),
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
# `Store` first, so the file is at the current schema before the queue and
# auth add their own tables to it.
store = Store(config.database)
jobs.seed_agents(config, store)
app = FastAPI(title="roledesk", docs_url="/api/docs",
summary="ATS boards in, roles scored per search agent, "
"applications tracked.")
app.state.config = config
app.state.store = store
# The door, first, because it is the door. The middleware covers every
# route whenever it was added, `/ws/jobs` included; written first, nobody
# has to work that out. `auto` locks unless the bind address is loopback.
# Auth's tables are the `auth_*` ones in the same file.
auth.connect(app, auth.AuthStore(config.database), config.auth,
host=config.server.host, open=("/static/",),
stylesheet="/static/app.css")
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
# The queue: routes, socket, `<desk-jobs>`, `<desk-schedules>`, and a
# worker in the lifespan that also fires the schedules. `tz` is what a
# `daily at 06:00` cadence is read in.
connect(app, Jobs(str(config.database)), config, store,
workers=config.workers.model_dump(),
bootstrap=jobs.BOOTSTRAP, bootstrap_arg=str(config.path or ""),
tz=config.timezone)
app.include_router(api_router)
app.include_router(pages_router)
@app.get("/health", include_in_schema=False)
def health() -> dict[str, Any]:
"""Open, session-free, and it reads the store: `docker compose up
--wait` waits on this, so it has to prove the database answers."""
return {"ok": True, "open_roles": sum(store.open_role_counts().values())}
@app.exception_handler(StarletteHTTPException)
async def errors(request: Request, exc: StarletteHTTPException) -> Any:
"""JSON for a caller, a page for a browser. One shape for every API
error, `{"detail": "<one sentence>"}`, so `api()` in `static/app.js`
turns any failure into one toast carrying the server's own wording."""
headers = getattr(exc, "headers", None)
wants_page = (request.method == "GET"
and not request.url.path.startswith(API_PREFIXES))
if not wants_page:
return JSONResponse({"detail": exc.detail}, status_code=exc.status_code,
headers=headers)
return templates.TemplateResponse(
request, "error.html",
{"status": exc.status_code, "detail": exc.detail},
status_code=exc.status_code, headers=headers)
@app.exception_handler(RequestValidationError)
async def invalid(request: Request, exc: RequestValidationError) -> JSONResponse:
"""FastAPI's 422 body is a list of objects, which a toast shows as
`[object Object]`. The same errors as one sentence instead."""
said = "; ".join(
f"{'.'.join(str(p) for p in err['loc'] if p != 'body')}: {err['msg']}"
for err in exc.errors())
return JSONResponse({"detail": said or "The request was not valid."},
status_code=422)
return app
def __getattr__(name: str) -> Any:
"""`app.main:app` for uvicorn, built on first use rather than on import, so
importing this module opens no database."""
if name == "app":
built = create_app()
globals()["app"] = built
return built
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")