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
173 changes: 173 additions & 0 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
# Lint, tests and releases on a GitLab instance. The GitHub equivalents are
# .github/workflows/ci.yml and release.yml; both hosts read the same sources
# of truth, so nothing is pinned twice: Python from .python-version (checked
# against PYTHON_VERSION below), Poetry from poetry.lock's header, the
# version and the release notes through scripts/release.py.
#
# Adapting this starter to a new project: edit the `variables` block and the
# postgres image tag in `test`; nothing in the jobs refers to the project by
# name. The starter itself never gets a v* tag (scripts/release.py refuses
# while [tool.release] starter = true), so the release jobs are dormant here.

# One pipeline per change: a branch with an open merge request gets the merge
# request pipeline only, not a second branch pipeline for the same commit.
# A v* tag gets its own pipeline, which adds the release jobs.
workflow:
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
- if: $CI_COMMIT_BRANCH && $CI_OPEN_MERGE_REQUESTS
when: never
- if: $CI_COMMIT_BRANCH
- if: $CI_COMMIT_TAG =~ /^v[0-9]/

stages:
- lint
- test
- build
- release

variables:
# The image tag cannot read .python-version, so the minor is repeated here;
# .python's before_script fails the job if the two disagree.
PYTHON_VERSION: "3.14"
# Paths black and flake8 check; mypy takes its paths from [tool.mypy].
CODE_PATHS: src tests scripts
# Throwaway database for the test job. None of these are secrets. The
# POSTGRES_* values configure the service; tests/conftest.py builds the test
# database URL from DB_*, so the two sets must agree. DB_HOST is the service
# host name the runner derives from the image name.
POSTGRES_USER: ci
POSTGRES_PASSWORD: ci
POSTGRES_DB: ci_test_db
DB_USER: ci
DB_PASSWORD: ci
DB_HOST: postgres
DB_PORT: "5432"
TEST_DB_NAME: ci_test_db
# The app refuses to import without these two; the secret must be at least
# 32 bytes (config.py checks), otherwise any value works in CI.
JWT_SECRET_KEY: ci-only-not-a-secret-but-at-least-32-bytes-long
API_KEY: ci-only-not-a-secret

# Python with the dev group installed, and pip and Poetry caches that live for
# as long as poetry.lock is unchanged.
.python:
image: python:${PYTHON_VERSION}-slim
variables:
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
POETRY_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pypoetry"
cache:
key:
files:
- poetry.lock
paths:
- .cache/pip
- .cache/pypoetry
before_script:
- |
wanted="$(tr -d '[:space:]' < .python-version)"
actual="$(python -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
if [ "$wanted" != "$actual" ]; then
echo "PYTHON_VERSION=$PYTHON_VERSION gives Python $actual but .python-version says $wanted; keep them in step."
exit 1
fi
- pip install "poetry==$(sed -n 's/.*generated by Poetry \([0-9.]*\).*/\1/p' poetry.lock | head -1)"
- poetry install --no-interaction

lint:
extends: .python
stage: lint
# Only test saves the cache: its contents change only with poetry.lock, and
# re-saving it in both jobs costs time for nothing.
cache:
policy: pull
interruptible: true
script:
- poetry run black --check $CODE_PATHS
- poetry run flake8 $CODE_PATHS
- poetry run mypy
# Known vulnerabilities in the installed dependencies; the project's own
# package is editable and not on PyPI, so it is skipped rather than failed.
- poetry run pip-audit --progress-spinner off --skip-editable

test:
extends: .python
stage: test
# Start at once instead of after lint; build and release still need both.
needs: []
interruptible: true
services:
# The PostgreSQL major the project targets; CI on GitHub tests the same one.
- postgres:17
script:
- poetry run pytest --junitxml=report.xml
artifacts:
when: always
reports:
# Test results show up in the merge request widget.
junit: report.xml
expire_in: 1 week

# --- Release pipeline: only on a v* tag made by scripts/release.py ---------

# The script is standard library only, so nothing is installed first: the tag
# must match pyproject.toml and CHANGELOG.md must have the section.
verify:
stage: lint
image: python:${PYTHON_VERSION}-slim
cache: []
rules:
- if: $CI_COMMIT_TAG =~ /^v[0-9]/
script:
- python scripts/release.py check-version "$CI_COMMIT_TAG"
- python scripts/release.py notes "$CI_COMMIT_TAG" > release-notes.md
artifacts:
paths:
- release-notes.md
expire_in: 1 week

build:
extends: .python
stage: build
cache:
policy: pull
rules:
- if: $CI_COMMIT_TAG =~ /^v[0-9]/
needs:
- verify
- lint
- test
script:
- poetry build
artifacts:
paths:
- dist/
expire_in: 1 week

# One job creates the release once everything passed, so a failed check never
# leaves a release behind. glab authenticates with the job token
# (GLAB_ENABLE_CI_AUTOLOGIN); the wheel and sdist go to the project's generic
# package registry, which accepts the job token, and are linked from the
# release page. release-cli is deprecated since GitLab 18.0; glab replaces it.
release:
stage: release
# Pinned, not `latest`: every upstream rebuild of a floating tag leaves the
# previous image dangling on the runner host.
image: registry.gitlab.com/gitlab-org/cli:v1.122.0
cache: []
rules:
- if: $CI_COMMIT_TAG =~ /^v[0-9]/
needs:
- verify
- build
variables:
GIT_STRATEGY: none
GLAB_ENABLE_CI_AUTOLOGIN: "true"
script:
- |
glab release create "$CI_COMMIT_TAG" dist/* \
--name "$CI_COMMIT_TAG" \
--notes-file release-notes.md \
--ref "$CI_COMMIT_SHA" \
--use-package-registry \
--package-name "$CI_PROJECT_NAME"
5 changes: 3 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Poetry-managed.
* **Environment**: the app refuses to start without `DATABASE_URL`, `API_KEY`
and a 32+ byte `JWT_SECRET_KEY` (`src/basic_api/config.py`); copy
`.env.example` to `.env`. A dev machine may have no PostgreSQL: database
tests then run only in CI.
tests then run only in CI (`.github/workflows/ci.yml` and `.gitlab-ci.yml`, kept in step).
* **Configuration**: add a variable in `config.py` and `.env.example` together;
nothing else reads the environment.
* **Errors**: routers translate domain exceptions (`exceptions.py`) to status
Expand Down Expand Up @@ -56,7 +56,8 @@ docs/ # setup, authentication, api, schemas, releasing, known_issue
* **Type check**: `poetry run mypy` (covers `src` and `scripts`)
* **Release** (in a clone, never in the starter): `poetry run python scripts/release.py prepare minor`;
`--dry-run` first. The version lives only in `pyproject.toml`; Unreleased in
`CHANGELOG.md` becomes the notes. `.github/workflows/release.yml` publishes the tag.
`CHANGELOG.md` becomes the notes. `.github/workflows/release.yml` (GitHub) or the
tag jobs in `.gitlab-ci.yml` (GitLab) publish the tag.
* **Dependency audit**: `poetry run pip-audit` (CI runs it in `lint`)
* **Dependencies**: `poetry add <pkg>` (dev tools: `--group dev`), then `poetry install`.
Ranges in `pyproject.toml` are open to the next major; `poetry.lock` is the pin.
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ notes (see [docs/releasing.md](docs/releasing.md)).
pycparser from the dependency tree; HS256 needs none of them (#9).

### Dependencies
- Refresh before the move to Python 3.15: pydantic 2.13.5 to 2.14.1 with
pydantic-core 2.50.1, the first release with Python 3.15 wheels; FastAPI
0.142.2 to 0.143.1; Starlette 1.7.0 to 1.8.0; Black 26.10.0 to 26.10.1 and
the transitive updates Poetry resolved. FastAPI 0.143 makes its automatic
OpenTelemetry exporter setup opt-in, which changes nothing here because the
starter configures no telemetry. SQLAlchemy stays on 2.0.x by choice, see
the comment in `pyproject.toml` (#19).
- Every dependency moved to its current release and the ranges in
`pyproject.toml` opened to the next major (`poetry.lock` is the pin):
FastAPI 0.121 to 0.142, Starlette 0.49 to 1.7, uvicorn 0.38 to 0.54,
Expand All @@ -34,6 +41,11 @@ notes (see [docs/releasing.md](docs/releasing.md)).
- `cryptography` 46.0.3 to 50.0.2, closing seven published advisories (#7).

### Added
- `.gitlab-ci.yml`: the same lint and test jobs as the GitHub workflow for a
GitLab instance (test results in the merge request widget), plus the release
jobs on a `v*` tag: verify, build, and a GitLab release created with `glab`
with the wheel and sdist in the generic package registry. The release script
prints the pipeline URL for GitHub or GitLab remotes (#18).
- Release tooling: `scripts/release.py prepare patch|minor|major|X.Y.Z` runs
the suite, bumps `pyproject.toml`, turns Unreleased into the version's
section, commits, tags and pushes atomically; `.github/workflows/release.yml`
Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ configuration right. That work is done here, tested, and documented.
- User self-service: read, update, change password and delete the own account
- Async PostgreSQL through SQLModel and asyncpg; health check that pings it
- One `config.py` reads and validates every environment variable at startup
- black, flake8 and mypy clean; pytest suite; GitHub Actions lint and test jobs
- black, flake8 and mypy clean; pytest suite; lint and test pipelines for GitHub Actions and GitLab CI

## Documentation

Expand All @@ -34,7 +34,7 @@ configuration right. That work is done here, tested, and documented.
| [Authentication](docs/authentication.md) | API key, login flow, token lifetime, what invalidates a token, rate limits, errors |
| [API Reference](docs/api.md) | Every endpoint with status codes, response envelope and error shape |
| [Schemas](docs/schemas.md) | Request and response models with their limits |
| [Releasing](docs/releasing.md) | `scripts/release.py`: version bump, changelog, tag, GitHub release; writing the notes |
| [Releasing](docs/releasing.md) | `scripts/release.py`: version bump, changelog, tag, release on GitHub or GitLab; writing the notes |
| [Known Issues](docs/known_issues.md) | What the starter deliberately does not do yet |
| [Changelog](CHANGELOG.md) | What changed and when |

Expand Down Expand Up @@ -62,7 +62,8 @@ basic_api/
users.py # Business rules for users, independent of HTTP
tests/ # pytest suite; database-backed and pure tests
docs/ # Written documentation
.github/workflows/ci.yml
.github/workflows/ # ci.yml and release.yml (GitHub Actions)
.gitlab-ci.yml # the same jobs for GitLab
pyproject.toml # Poetry project, dev group, black and mypy config
.env.example # Every variable, grouped, with its default
```
Expand Down Expand Up @@ -123,7 +124,7 @@ poetry run black --check src tests && poetry run flake8 src tests && poetry run
```

CI runs the same three checks and the full suite against `postgres:17` on every
push and pull request.
push and pull or merge request, on GitHub Actions or GitLab.

## Adapting this starter

Expand Down
13 changes: 7 additions & 6 deletions docs/known_issues.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,17 +163,18 @@ Logging is configured (`logging_config.py`: levels, JSON or text lines, a
request id on every line and response), but there are no metrics, no traces
and no error tracker: a 500 is a log line, not an alert.

**Fix:** for tracing and metrics, FastAPI 0.142's native OpenTelemetry
(`FastAPI(telemetry={...})`, with `auto_configure` reading the standard `OTEL_*`
variables) is the path; it needs `opentelemetry-sdk` and an OTLP exporter
installed to emit anything. An error tracker (Sentry or similar) hooks in as a
**Fix:** for tracing and metrics, FastAPI's native OpenTelemetry
(`FastAPI(telemetry={...})`) is the path. Since FastAPI 0.143 the automatic
exporter setup from the standard `OTEL_*` variables is opt-in:
`telemetry={"auto_configure": True}` or `FASTAPI_OTEL_AUTO_CONFIGURE=true`. It
needs `opentelemetry-sdk` and an OTLP exporter installed to emit anything. An error tracker (Sentry or similar) hooks in as a
logging handler or ASGI middleware.

### CI has no coverage or secret scan

**Where:** `.github/workflows/ci.yml`.
**Where:** `.github/workflows/ci.yml`, `.gitlab-ci.yml`.

The pipeline formats, lints, type-checks, audits dependencies (`pip-audit`)
The pipelines format, lint, type-checks, audits dependencies (`pip-audit`)
and tests, and Dependabot proposes updates. It does not measure coverage and
does not scan for committed secrets.

Expand Down
52 changes: 35 additions & 17 deletions docs/releasing.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,29 @@ project built from it.
```text
CHANGELOG.md "Unreleased" --> scripts/release.py prepare --> commit + tag vX.Y.Z --> push
|
GitHub release (notes, wheel, sdist) <-- publish <-- build <-- ci <-- verify <----+
release page (notes, wheel, sdist) <-- publish <-- build <-- lint + test <-- verify <-+
```

- **The notes** are the `## [Unreleased]` section of [CHANGELOG.md](../CHANGELOG.md).
The script renames it to the version; the workflow publishes that section as
The script renames it to the version; the pipeline publishes that section as
the release notes, word for word.
- **The script** (`scripts/release.py`) bumps the version, updates the
changelog, commits, tags, and pushes. The version lives in one place,
`[project] version` in `pyproject.toml`; the app reads it from the installed
package metadata (`APP_VERSION`, shown by `GET /` and the OpenAPI document).
- **The workflow** (`.github/workflows/release.yml`) runs on the pushed tag:
- **The pipeline** runs on the pushed tag, on either host:
1. **verify**: the tag matches `pyproject.toml` and the notes exist.
2. **ci**: the same lint and test jobs as a pull request, PostgreSQL included.
2. **lint and test**: the same jobs as a pull or merge request, PostgreSQL
included.
3. **build**: the wheel and the sdist (`poetry build`).
4. **publish**: one GitHub release, created only when everything passed.
4. **publish**: one release, created only when everything passed.

On GitHub that is `.github/workflows/release.yml` (a GitHub release with the
archives attached, marked pre-release when the version has a suffix). On
GitLab it is the tag pipeline in `.gitlab-ci.yml` (a GitLab release created
with `glab`; the archives go to the project's generic package registry and
are linked from the release page). Both repositories can hold both files; a
host ignores the other's.

## Choosing the version

Expand All @@ -41,8 +49,9 @@ a client of this API would notice.
The commit type cannot tell the script that a `feat` broke a client; you choose
the part. For a test deployment ahead of a release, give an explicit
pre-release version: `prepare 1.0.0-rc.1`. It is published as a **pre-release**,
so GitHub does not show it as "Latest". A later `prepare patch|minor|major`
from `1.0.0-rc.N` finishes it as `1.0.0`.
so GitHub does not show it as "Latest" (GitLab has no pre-release flag; the
suffix in the name is the signal). A later `prepare patch|minor|major` from
`1.0.0-rc.N` finishes it as `1.0.0`.

A pre-release spelled `1.0.0-rc.1` is valid PEP 440, and the installed metadata
normalises it: `GET /` reports `1.0.0rc1`. The tag and the changelog keep the
Expand Down Expand Up @@ -98,7 +107,7 @@ The script:
server reports the new version; the installed metadata is written at
install time, not read from `pyproject.toml`.
8. Asks, then pushes `main` and the tag in one atomic push, which starts the
workflow.
pipeline, and prints where to watch it.

Answer **no** at the push question, or pass `--no-push`, to stop with
everything still local. Push later with the command it prints, or undo with:
Expand All @@ -110,12 +119,20 @@ git tag -d vX.Y.Z && git reset --hard HEAD~1
Other options: `--skip-tests` when you have just run them; `--yes` answers every
question, for scripted use; `--allow-branch` releases from another branch.

### 5. Watch the workflow and check the release
### 5. Watch the pipeline and check the release

Open the repository's **Actions** tab (GitHub) or **Build > Pipelines**
(GitLab). The release appears under **Releases** (GitHub) or **Deploy >
Releases** (GitLab) when the last job finishes. Check that the notes read
correctly, the wheel and the sdist are attached, and a deployment of the tag
answers the new version on `GET /`.

Open the repository's **Actions** tab. The release appears under **Releases**
when *publish* finishes. Check that the notes read correctly, the wheel and the
sdist are attached, and a deployment of the tag answers the new version on
`GET /`.
On GitLab, the first release of a project is also the first test of the job
token's rights: if `release` fails uploading the archives (a 401 or 403 from
the package registry), check that **Settings > General > Visibility > Package
registry** is on and that the job token is allowed to reach the project
(**Settings > CI/CD > Job token permissions**). Nothing was published; fix and
rerun the job.

## The starter and its clones

Expand All @@ -129,7 +146,7 @@ starter = true

A project built from the starter sets it to `false` once (it is in the
[Adapting this starter](setup.md#adapting-this-starter) list) and inherits the
script, the workflow, the test and this page unchanged; nothing in them names
script, both pipelines, the test and this page unchanged; nothing in them names
the project. The first release works from a repository with no tags: the
Unreleased section is the notes, and if it is empty the script lists every
conventional commit in the history, so write the section. Start wherever the
Expand Down Expand Up @@ -209,7 +226,8 @@ Each entry is the summary with its scope in bold and the short commit hash.

```bash
python scripts/release.py notes X.Y.Z > notes.md
gh release edit vX.Y.Z --notes-file notes.md
gh release edit vX.Y.Z --notes-file notes.md # GitHub
glab release create vX.Y.Z --notes-file notes.md # GitLab: updates an existing release
```

The annotated tag keeps the original text; that is expected.
Expand All @@ -224,8 +242,8 @@ Each entry is the summary with its scope in bold and the short commit hash.
| Tests fail in `prepare` | Nothing was written. Fix on `main` first. |
| The push was rejected (branch protection on `main`) | Nothing was pushed: the push is atomic. Allow the push for the release commit, or push it through a PR and push the tag after merging (`git push origin vX.Y.Z`; the tag must point at the merged commit). |
| *verify* fails | The tag was not made by the script, or `pyproject.toml` was edited by hand. Delete the tag (`git push --delete origin vX.Y.Z && git tag -d vX.Y.Z`), fix, release again. Nothing was published. |
| *ci* or *build* fails | Nothing is published. A flaky runner: **Re-run failed jobs**. Code at fault: fix on `main`, delete the tag as above, release the next patch version rather than reusing the number. |
| *publish* fails | Re-run the failed job; the archives from *build* are reused. |
| *lint*, *test* or *build* fails | Nothing is published. A flaky runner: rerun the failed job. Code at fault: fix on `main`, delete the tag as above, release the next patch version rather than reusing the number. |
| *publish* (GitHub) or *release* (GitLab) fails | Rerun the failed job; the archives from *build* are reused. |
| `GET /` still shows the old version on your machine | `poetry install --only-root`. |

Never re-point or reuse a tag that has a published release. Release the next
Expand Down
Loading
Loading