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
9 changes: 6 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ Poetry-managed.
in the change that fixes it.
* **Style**: no emojis or em-dashes in code or docs; do not guess APIs,
versions, flags or package names, verify in code or docs.
* **Typing**: `X | None`, never `Optional[X]`; generic classes use PEP 695
(`class Envelope[T](BaseModel)`); route dependencies are `Annotated`, via
the `SessionDep` and `CurrentUserDep` aliases in `dependencies.py`.
* **Typing**: `X | None`, never `Optional[X]`; generic aliases come from
`collections.abc` (`AsyncGenerator[T]`, `Callable`), not `typing`; generic
classes use PEP 695 (`class Envelope[T](BaseModel)`); route dependencies
are `Annotated`, via the `SessionDep` and `CurrentUserDep` aliases in
`dependencies.py`. Read-only module constants that are mappings are
`frozendict` (Python 3.15); regexes use `prefixmatch`, not `match`.

## Project Structure
```
Expand Down
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,21 @@ notes (see [docs/releasing.md](docs/releasing.md)).
`RequestBodyLimitMiddleware` answers 413 before any route runs (#13).

### Changed
- Python 3.15 idioms. Read-only module constants are `frozendict`
(`_SECRET_MINIMUM_BYTES`, `_TAKEN_MESSAGES`, `_DESCRIPTIONS`, the release
script's `SECTIONS`); generic aliases come from `collections.abc` with the
single parameter 3.13+ allows; `scripts/release.py` uses `re.prefixmatch`
(3.15's explicit name for the soft-deprecated `match`), drops `from
__future__ import annotations` and names `encoding="utf-8"` on every file
and subprocess read, PEP 686's advice now that UTF-8 is the default, so
`-X warn_default_encoding` is clean. The setup guide adds the 3.15 sampling
profiler (`profiling.sampling`) next to the asyncio commands. Evaluated and
left unused, so the question need not be reopened: lazy imports (PEP 810;
the server imports everything at startup and the release script starts in
milliseconds), `sentinel` (no sentinel pattern), unpacking in comprehensions
(nothing to flatten), `TaskGroup.cancel` (no task groups), TypedDict
`closed` and `TypeForm` (no TypedDicts), free-threading and the JIT (nothing
CPU-bound) (#23).
- The rate limiter is built directly on `limits` (fixed window, in-process
memory) instead of slowapi, whose `asyncio.iscoroutinefunction` call is
removed in Python 3.16 and unfixed upstream. A limited route now declares
Expand Down
23 changes: 20 additions & 3 deletions docs/setup.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,10 +166,10 @@ Everything a new project renames or changes, in one list:
The starter itself stays at `0.1.0`.
7. **Docs**: this folder and the README.

## Debugging a hung process
## Debugging a hung or slow process

Python 3.14 can show what an asyncio program is waiting on, from outside the
process and without stopping it:
Python can show what an asyncio program is waiting on, from outside the
process and without stopping it (3.14):

```bash
python -m asyncio ps <pid> # one line per task: id, name, coroutine stack
Expand All @@ -178,3 +178,20 @@ python -m asyncio pstree <pid> # the same as an await tree

Point it at the uvicorn worker's pid. A task stuck on a database call or a lock
shows up with its full await chain; that is usually enough to name the culprit.

Python 3.15 adds a sampling profiler, `profiling.sampling` (Tachyon). It reads
the worker's memory from outside, so the worker pays nothing and need not be
restarted; `--async-aware` reports stacks per task rather than event-loop
internals:

```bash
python -m profiling.sampling dump --async-aware <pid> # one snapshot of every task
python -m profiling.sampling attach --async-aware -d 30 --flamegraph -o profile.html <pid>
python -m profiling.sampling run --async-aware -d 30 -m uvicorn basic_api.main:app --app-dir src
```

All of these read another process's memory. On Linux the same user is not
enough while `kernel.yama.ptrace_scope` is `1` (the usual default): run the
profiler as root, give it `CAP_SYS_PTRACE` (`--cap-add=SYS_PTRACE` for a
container), or set the scope to `0`. `run` starts the server as the profiler's
own child and needs none of that, which makes it the way to profile locally.
62 changes: 38 additions & 24 deletions scripts/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@
Standard library only, so CI can run it before installing anything.
"""

from __future__ import annotations

import argparse
import datetime as dt
import os
Expand Down Expand Up @@ -66,14 +64,16 @@

# Conventional Commit type -> changelog heading, in display order. Types not
# listed (chore, ci, test, build, style) are housekeeping and left out.
SECTIONS = {
"feat": "Added",
"refactor": "Changed",
"perf": "Performance",
"fix": "Fixed",
"security": "Security",
"docs": "Documentation",
}
SECTIONS = frozendict(
{
"feat": "Added",
"refactor": "Changed",
"perf": "Performance",
"fix": "Fixed",
"security": "Security",
"docs": "Documentation",
}
)
BREAKING = "Breaking changes"
COMMIT_RE = re.compile(
r"^(?P<type>[a-z]+)(?:\((?P<scope>[^)]+)\))?(?P<bang>!)?: (?P<desc>.+)$"
Expand All @@ -89,7 +89,7 @@ class ReleaseError(Exception):

def parse_version(text: str) -> tuple[int, int, int, str | None]:
"""Split X.Y.Z[-pre] into its parts, or raise ReleaseError."""
match = VERSION_RE.match(text.strip())
match = VERSION_RE.prefixmatch(text.strip())
if not match:
raise ReleaseError(f"not a version: {text!r} (expected X.Y.Z or X.Y.Z-rc.N)")
major, minor, patch, pre = match.groups()
Expand Down Expand Up @@ -189,7 +189,7 @@ def render_section(commits: list[Commit]) -> str:
"""Changelog entries grouped by Conventional Commit type; '' if none."""
groups: dict[str, list[str]] = {}
for commit in commits:
match = COMMIT_RE.match(commit.subject)
match = COMMIT_RE.prefixmatch(commit.subject)
if not match:
continue # not conventional (merges and the like): nothing to file it under
kind, scope, desc = match["type"], match["scope"], match["desc"]
Expand Down Expand Up @@ -259,7 +259,10 @@ def release_notes(changelog: str, version: str) -> str:


def git(*args: str, check: bool = True) -> str:
result = subprocess.run(["git", *args], cwd=ROOT, capture_output=True, text=True)
# UTF-8 is the 3.15 default; stated so the intent survives PYTHONUTF8=0.
result = subprocess.run(
["git", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8"
)
if check and result.returncode != 0:
raise ReleaseError(f"git {' '.join(args)} failed:\n{result.stderr.strip()}")
return result.stdout.strip()
Expand Down Expand Up @@ -352,6 +355,7 @@ def refresh_installed_metadata() -> None:
cwd=ROOT,
capture_output=True,
text=True,
encoding="utf-8",
)
if result.returncode == 0:
print("Reinstalled the project so APP_VERSION reports the new version.")
Expand All @@ -363,14 +367,18 @@ def refresh_installed_metadata() -> None:


def cmd_prepare(args: argparse.Namespace) -> None:
project = read_project(PYPROJECT.read_text())
project = read_project(PYPROJECT.read_text(encoding="utf-8"))
version = bump(project.version, args.part)
tag = f"v{version}"
preflight(project, tag, allow_branch=args.allow_branch)

previous = last_tag()
generated = render_section(commits_since(previous))
changelog = CHANGELOG.read_text() if CHANGELOG.exists() else UNRELEASED + "\n"
changelog = (
CHANGELOG.read_text(encoding="utf-8")
if CHANGELOG.exists()
else UNRELEASED + "\n"
)
new_changelog, notes = add_release(changelog, version, generated, dt.date.today())

print(
Expand All @@ -394,14 +402,16 @@ def cmd_prepare(args: argparse.Namespace) -> None:
run_tests()

files = {
PYPROJECT: write_version(PYPROJECT.read_text(), version),
PYPROJECT: write_version(PYPROJECT.read_text(encoding="utf-8"), version),
CHANGELOG: new_changelog,
}
originals = {p: p.read_text() if p.exists() else None for p in files}
originals = {
p: p.read_text(encoding="utf-8") if p.exists() else None for p in files
}
relative = [str(p.relative_to(ROOT)) for p in files]
try:
for path, text in files.items():
path.write_text(text)
path.write_text(text, encoding="utf-8")
editor = os.environ.get("VISUAL") or os.environ.get("EDITOR")
if (
editor
Expand All @@ -410,7 +420,7 @@ def cmd_prepare(args: argparse.Namespace) -> None:
and confirm("Edit CHANGELOG.md before committing?", False)
):
subprocess.run([*shlex.split(editor), str(CHANGELOG)], check=True)
notes = release_notes(CHANGELOG.read_text(), version)
notes = release_notes(CHANGELOG.read_text(encoding="utf-8"), version)
if not confirm(f"Commit and tag {tag}?", args.yes):
raise ReleaseError("stopped before committing")
git("add", *relative)
Expand All @@ -420,7 +430,7 @@ def cmd_prepare(args: argparse.Namespace) -> None:
if original is None:
path.unlink(missing_ok=True)
else:
path.write_text(original)
path.write_text(original, encoding="utf-8")
git("reset", "-q", "--", *relative, check=False)
print("The version files were restored; nothing was committed.")
raise
Expand Down Expand Up @@ -457,7 +467,7 @@ def pipelines_url(remote: str) -> str:
Returns:
A URL, or a short hint when the remote is not recognised.
"""
match = re.match(
match = re.prefixmatch(
r"^(?:[a-z+]+://)?(?:[^@/]+@)?(?P<host>[^:/]+)(?::\d+)?"
r"[:/](?P<path>.+?)(?:\.git)?/?$",
remote.strip(),
Expand Down Expand Up @@ -486,11 +496,15 @@ def _emit_outputs(version: str) -> None:


def cmd_notes(args: argparse.Namespace) -> None:
print(release_notes(CHANGELOG.read_text(), args.version.removeprefix("v")))
print(
release_notes(
CHANGELOG.read_text(encoding="utf-8"), args.version.removeprefix("v")
)
)


def cmd_check_version(args: argparse.Namespace) -> None:
version = read_project(PYPROJECT.read_text()).version
version = read_project(PYPROJECT.read_text(encoding="utf-8")).version
tag_version = args.tag.removeprefix("refs/tags/").removeprefix("v")
if tag_version != version:
raise ReleaseError(
Expand All @@ -501,7 +515,7 @@ def cmd_check_version(args: argparse.Namespace) -> None:


def cmd_version(_args: argparse.Namespace) -> None:
version = read_project(PYPROJECT.read_text()).version
version = read_project(PYPROJECT.read_text(encoding="utf-8")).version
print(version)
_emit_outputs(version)

Expand Down
2 changes: 1 addition & 1 deletion src/basic_api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ def _test_database_url() -> str:
_ALLOWED_ALGORITHMS = ("HS256", "HS384", "HS512")
# RFC 7518 section 3.2: an HMAC key should be at least as long as the hash it
# drives. PyJWT 2.15 checks the same rule at sign and verify time.
_SECRET_MINIMUM_BYTES = {"HS256": 32, "HS384": 48, "HS512": 64}
_SECRET_MINIMUM_BYTES = frozendict({"HS256": 32, "HS384": 48, "HS512": 64})
_MIN_BCRYPT_ROUNDS = 12


Expand Down
4 changes: 2 additions & 2 deletions src/basic_api/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import asyncio
import logging
from typing import AsyncGenerator
from collections.abc import AsyncGenerator

from sqlalchemy import text
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
Expand Down Expand Up @@ -69,7 +69,7 @@ async def ping(timeout: float = 2.0) -> bool:
return False


async def get_session() -> AsyncGenerator[AsyncSession, None]:
async def get_session() -> AsyncGenerator[AsyncSession]:
"""One session per request; closed when the request ends."""
async with async_session_factory() as session:
yield session
26 changes: 14 additions & 12 deletions src/basic_api/schemas/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,20 @@ class ErrorDetail(BaseModel):


# Code -> what it means in this API. Kept in step with docs/api.md.
_DESCRIPTIONS: dict[int, str] = {
400: "A confirmation password was wrong",
401: (
"Missing or invalid X-API-Key; or missing, invalid, expired or orphaned "
"bearer token; or wrong login credentials"
),
403: "The account is disabled",
409: "Username, email or phone number already in use",
413: "Request body over MAX_REQUEST_BODY_BYTES (plain-text body)",
429: "Over the rate limit; wait for Retry-After seconds",
503: "Database unreachable",
}
_DESCRIPTIONS: frozendict[int, str] = frozendict(
{
400: "A confirmation password was wrong",
401: (
"Missing or invalid X-API-Key; or missing, invalid, expired or orphaned "
"bearer token; or wrong login credentials"
),
403: "The account is disabled",
409: "Username, email or phone number already in use",
413: "Request body over MAX_REQUEST_BODY_BYTES (plain-text body)",
429: "Over the rate limit; wait for Retry-After seconds",
503: "Database unreachable",
}
)


def error_responses(*codes: int) -> dict[int | str, dict[str, Any]]:
Expand Down
12 changes: 7 additions & 5 deletions src/basic_api/services/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,13 @@
# What a client is told when an identifier collides, per field, so a form can
# mark the right input. Checked before the insert; the unique constraints are
# the backstop for two requests racing past the checks.
_TAKEN_MESSAGES = {
"username": "Username is already taken",
"email": "Email address is already registered",
"phone_number": "Phone number is already associated with an account",
}
_TAKEN_MESSAGES = frozendict(
{
"username": "Username is already taken",
"email": "Email address is already registered",
"phone_number": "Phone number is already associated with an account",
}
)
_RACE_MESSAGE = "A user with this username, email, or phone number already exists"


Expand Down
6 changes: 3 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

import asyncio
import os
from typing import AsyncGenerator
from collections.abc import AsyncGenerator

import pytest
from dotenv import load_dotenv
Expand Down Expand Up @@ -71,7 +71,7 @@ async def teardown():


@pytest.fixture
async def session() -> AsyncGenerator[AsyncSession, None]:
async def session() -> AsyncGenerator[AsyncSession]:
"""A session per test; every row is deleted afterwards."""
async with async_session_maker() as session:
yield session
Expand All @@ -84,7 +84,7 @@ async def session() -> AsyncGenerator[AsyncSession, None]:


@pytest.fixture
async def client(session: AsyncSession) -> AsyncGenerator[AsyncClient, None]:
async def client(session: AsyncSession) -> AsyncGenerator[AsyncClient]:
"""HTTP client over the app, sharing the test session and sending the API key."""

def get_session_override():
Expand Down
Loading
Loading