Add web-frontend, web-project-audit and web-project-scaffold-containerized-python skills

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Neil Bantoc 2026-11-04 14:46:25 -08:00
parent 59fc08fa5f
commit 5201aa9bd5
63 changed files with 3042 additions and 0 deletions

View file

@ -0,0 +1,123 @@
---
name: web-project-scaffold-containerized-python
description: Scaffold a new web project with a Python (FastAPI) backend and a no-build HTML/CSS/JS frontend, packaged in a Docker container that deploys by pulling source from a remote git repo — `docker exec <name> update` fetches the latest commit, syncs requirements, restarts the app in place and rolls back on failure, with no image rebuild. Servers are set up by one copy-paste install command (curl … | bash) that installs Docker, clones the repo, writes the .env with repo URL and credentials, and starts the container. Requires an existing remote git repo URL up front. Use when the user wants to start/create/bootstrap a new web app, site, API or internal tool that should be Python-based, containerized, or easy to deploy and update on a server.
---
# Scaffold a containerized Python web project
Goal: hand back a project where **`scripts/verify.sh` prints `VERIFY: PASS`** before any feature work. The run proves the image builds, the container clones from the repo named in `.env`, the tests pass, and `update` deploys, refuses broken code and rolls back without a rebuild. A passing run is the contract. Don't build features on a skeleton that hasn't passed.
## Principles (why the skeleton looks the way it does)
1. **Nothing is compiled.** The backend is Python (FastAPI + uvicorn). The frontend is plain HTML, CSS and ES modules served from `app/static/`, with no bundler, TypeScript, Sass, JSX or npm. Third-party browser libraries are vendored into `app/static/vendor/` as files with the pinned version in a comment. A deploy is therefore just new files.
2. **Containerized.** The host needs only Docker and git. Python, the venv and every tool run in the container, for dev and prod alike.
3. **The image is the runtime, not the app.** The image holds Python, git, tini and three scripts in `container/`. The source is a git checkout in the `/srv` volume, cloned from `REPO_URL` on first start. A rebuild is needed only when `container/` or the Python version changes.
4. **Update is one command.** `/usr/local/bin/update` is on PATH, so `docker exec <name> update` works. It reads `.env`, fetches `REPO_REF` from `REPO_URL`, checks out, reinstalls requirements if they changed, checks that `app.main` imports, sends SIGHUP to the in-container supervisor (which restarts uvicorn), and waits for `/healthz` to report the new commit. Any failure restores the previous commit. `--check`, `--rollback` and `<ref>` cover the rest.
5. **Remote and credentials live in `.env`.** It is gitignored and mounted read-only at `/run/config/app.env`. The container parses it (it doesn't execute it) on every start and every update, so a new URL or rotated token needs no rebuild or recreate.
- **Variables:** `REPO_URL`, `REPO_REF`, `GIT_TOKEN`/`GIT_USERNAME` (https) or `GIT_SSH_KEY` (base64 deploy key), plus any app settings.
- **Token:** a git credential helper supplies it from the environment. It never goes into `.git/config` or the URL.
- **Isolation:** the uvicorn process gets the app settings but not the git credentials.
6. **Install is one pasted line.** The project ships `install.sh`. On a fresh Linux server, the user pastes `curl -fsSL <raw install.sh URL> | bash`, Homebrew-style, and the installer does the rest:
- installs git and Docker (Engine + Compose) if they're missing
- checks it can read the repo, asking for a token on the terminal if the https repo is private
- clones into `/opt/<name>`
- writes `.env` from `.env.example` with the repo URL, branch, credentials and port, owned by uid 1000 with mode 640
- builds the image, starts the container and waits for `/healthz`
Re-running it is safe, and is also how the image gets rebuilt: it keeps `.env` and replaces only the keys passed in. Everything is inside `main()`, so a partial download runs nothing. It uses sudo only for steps that need it.
## Step 0 — Get the remote repo URL first (required)
Servers install from and update from the remote. The install command is that repo's raw `install.sh` URL, and the URL is the default `REPO_URL` baked into `install.sh` and `.env.example`. So **don't scaffold until the user has given the remote git repo URL.** If they haven't, ask for it before anything else. Ask whether it is private: over https it needs a read-only token, and over SSH a deploy key.
- Have them create an empty repo first if it doesn't exist (GitHub, GitLab, Gitea, …).
- GitHub and GitLab raw URLs are derived. For any other host, ask for the raw URL of `install.sh` on the default branch and pass `--install-url`.
- The URL must not contain credentials. Those go only in the server's `.env`, through the installer.
## Step 1 — Check the environment (never install silently)
```bash
bash "$SKILL_DIR/scripts/doctor.sh"
```
It checks git, docker, compose v2, buildx and daemon access. If it exits non-zero, show the user its fix lines and stop. Let them run the installs, suggesting the `! <command>` prefix. Don't scaffold blind.
## Step 2 — Decide the few inputs
- `--name`: a lowercase slug. It becomes the container name (so `docker exec <name> update`), the image name and the compose project.
- `--title`: the display name.
- `--python`: default 3.14. Use the user's version if they give one.
- `--port`: the host port on 127.0.0.1, default 8000.
- `--branch`: default `main`.
- `--repo-url` (**required**, from Step 0): the remote the servers clone from. It goes into `install.sh`, `.env.example` and the local `origin`.
- `--install-url`: only for hosts other than GitHub and GitLab.
Ask only for what you can't default. The name is usually obvious from the request.
## Step 3 — Generate
```bash
bash "$SKILL_DIR/scripts/scaffold.sh" --dir <project-dir> --name <slug> --repo-url <url> [--title "…"] [--python 3.14] [--port 8000] [--branch main] [--install-url <url>]
```
- **Pins:** it resolves current `fastapi`, `uvicorn[standard]`, `pytest` and `httpx2` versions in a throwaway `python:<ver>-slim` container and pins them `==X.Y.*`. Use `--no-resolve` when offline.
- **Templates and tokens:** it copies `templates/project`. If the `web-frontend` skill is installed, it copies that skill's `tokens.css` into `app/static/css/`.
- **`.env` and git:** it writes a local `.env` (mode 600) for dev, runs `git init` and adds `origin`, then prints the install command. It doesn't commit, push, build or start anything.
Resulting layout (details in the generated `README.md`):
```
app/main.py, app/api.py FastAPI: /healthz {status, version}, /api/*, /static (no-cache), /
app/static/ index.html, css/tokens.css + app.css, js/main.js + api.js, vendor/
tests/test_app.py pytest + TestClient
install.sh server installer: curl … | bash (Docker, clone, .env, build, start, health)
container/ Dockerfile, lib.sh, entrypoint.sh (setup + supervisor), update.sh
compose.yml prod: volumes runtime:/srv + data:/data, ./.env mounted, loopback port, read-only rootfs
compose.dev.yml dev overlay: source bind-mounted, DEV=1 → dev deps + --reload, update disabled
.env.example / .env REPO_URL, REPO_REF, GIT_TOKEN/GIT_USERNAME, GIT_SSH_KEY, HOST_PORT, app settings
```
## Step 4 — Verify the contract
```bash
bash "$SKILL_DIR/scripts/verify.sh" <project-dir> # add --keep to leave containers for debugging
```
It works on a throwaway copy with a local bare repo as the "remote" and a dummy token in its `.env`. Your project, its `.env` and its git history are untouched. It checks:
- the build and a healthy start
- the app sees `.env` settings but not `GIT_TOKEN`, and the token is never written to disk
- pytest passes
- `update` deploys a commit that changes requirements, with the same image and the same container start time
- an import-breaking commit is refused and a startup-crashing commit is rolled back, with the old commit still serving
- `update --rollback`
- `install.sh` piped into bash, as on a fresh server, against a `git://` remote: it brings the app up healthy and reachable on the host port, writes `.env` (uid 1000, mode 640) and never calls sudo when it isn't needed; a re-run is safe and replaces only the keys passed in
It doesn't exercise the Docker-install branch, because Docker is already present. That branch was tested on a bare Debian image: git, ssh, Docker and Compose all installed.
It must end with `VERIFY: PASS`. If it fails, fix the template or the project until it passes, then report the versions used.
Then tell the user the flow:
1. **Push** the project to the remote. Offer to make the first commit and push; don't do either unless they ask. The install command only works once `install.sh` is on the remote branch.
2. **Install:** paste the printed command on the server. For a private https repo, use the `read -rsp … && curl -H …` form from the README, so the token is never echoed or saved in shell history.
3. **Deploy:** `git push`, then `docker exec <name> update` on the server.
4. **Rebuild** (only when `container/` changes): run the install command again.
## Building on the skeleton
- **UI:** follow the `web-frontend` skill for the look (tokens, layout, components), within the no-build rule: plain CSS on the tokens, ES modules, vendored libraries, no CDN. Web fonts are vendored into `static/vendor/fonts/` or left on the system stack.
- **API:** routes go in `app/api.py`, or an `app/api/` package as it grows, under `/api`. Use Pydantic models for request and response bodies.
- **Persistence:** keep it under `$DATA_DIR` (`/data`, its own volume). SQLite is the default for small apps. Create the schema and run migrations idempotently in `lifespan`, never at import time, because `update` imports `app.main` as its pre-flight check.
- **Dependencies:** add each one to `requirements.txt` with a `==X.Y.*` pin. `update` installs it on the next deploy. Test-only dependencies go in `requirements-dev.txt`.
- **Settings and secrets:** new ones go in `.env` and `.env.example`, which holds names and placeholders only. Read them with `os.environ` in the app.
- **System packages** (e.g. `ffmpeg`, `libpq`) mean a `container/Dockerfile` change, and so a rebuild. Prefer pure-Python wheels. When a system package is needed, say a rebuild is required.
## Guardrails
- **Every "it works" claim comes from a `verify.sh` run that printed `VERIFY: PASS`,** never from reading the files.
- **No build step, ever.** Don't add `package.json`, a bundler, TypeScript or a CSS preprocessor. If the user needs one, they are asking for a different project shape; say so.
- **Never bake app source into the image.** `.dockerignore` lets in only `container/`. Copying `app/` into the image would make `update` and the image disagree.
- **No remote, no scaffold.** Get the repo URL first (Step 0). Don't invent a placeholder URL to fill in later.
- **The server is set up only through `install.sh`.** Keep it idempotent and inside `main()`. When a project needs more server setup (a system package, a firewall rule, a volume path), add it to the installer rather than to manual README steps.
- **Never commit `.env`, tokens or keys.** Don't put credentials in `REPO_URL`. Don't print `.env` values. Name variables, never their values.
- **Keep the scripts in `container/` generic.** Project-specific logic belongs in the app (`lifespan`), not in `update.sh`, which can only change with a rebuild.
- **Used ⇒ declared:** every import maps to a pinned line in `requirements*.txt`, and every vendored file has its version noted.

View file

@ -0,0 +1,31 @@
#!/usr/bin/env bash
# Check that this machine can build and run the scaffold. The host needs only Docker
# (with Compose v2 and BuildKit) and git; Python runs inside the container.
# Exits non-zero if something required is missing. Installs nothing.
ok=1
pass() { printf ' ok %s\n' "$*"; }
fail() { printf ' MISS %s\n' "$*"; ok=0; }
note() { printf ' note %s\n' "$*"; }
echo "Host tools"
if command -v git >/dev/null; then pass "git $(git --version | awk '{print $3}')"; else
fail "git: install it (e.g. sudo apt install git)"; fi
if command -v docker >/dev/null; then pass "docker $(docker --version | sed 's/Docker version //; s/,.*//')"; else
fail "docker: install Docker Engine (https://docs.docker.com/engine/install/)"; fi
if command -v docker >/dev/null; then
if docker compose version >/dev/null 2>&1; then pass "compose $(docker compose version --short)"; else
fail "docker compose v2 plugin: sudo apt install docker-compose-plugin"; fi
if docker buildx version >/dev/null 2>&1; then pass "buildx (BuildKit; needed for COPY --chmod)"; else
fail "docker buildx plugin: sudo apt install docker-buildx-plugin"; fi
if docker info >/dev/null 2>&1; then pass "daemon reachable as $(id -un)"; else
fail "cannot talk to the Docker daemon: start it, or add yourself to the docker group (sudo usermod -aG docker $USER, then log in again)"; fi
fi
echo "Notes"
note "host uid $(id -u): the image's app user defaults to uid 1000; dev bind mounts are easiest when they match"
command -v python3 >/dev/null && note "host python3 $(python3 -V 2>&1 | awk '{print $2}') is not used; Python runs in the container"
[ "$ok" = 1 ] && { echo "Ready."; exit 0; }
echo "Fix the MISS lines above, then re-run."
exit 1

View file

@ -0,0 +1,111 @@
#!/usr/bin/env bash
# Write a new containerized Python web project from templates/project.
# scaffold.sh --dir <path> --name <slug> --repo-url <url> [--title "My App"] [--python 3.14]
# [--port 8000] [--branch main] [--install-url <url>] [--no-resolve]
# --repo-url is required: the remote must exist, since servers install and update from it.
# --install-url is the raw URL of install.sh on the default branch; derived for GitHub and
# GitLab, required for other hosts.
# Resolves current fastapi/uvicorn/pytest/httpx2 versions inside python:<ver>-slim and pins
# them (==X.Y.*), unless --no-resolve (then the fallback pins below are used).
# Writes .env from .env.example, runs `git init` and adds the remote as origin.
# Does not commit, build or start anything; run verify.sh for that.
set -euo pipefail
SKILL_DIR=$(cd "$(dirname "$0")/.." && pwd)
TEMPLATE="$SKILL_DIR/templates/project"
TOKENS="$SKILL_DIR/../web-frontend/assets/tokens.css"
dir= name= title= python=3.14 port=8000 branch=main repo_url= install_url= resolve=1
while [ $# -gt 0 ]; do
case $1 in
--dir) dir=$2; shift ;;
--name) name=$2; shift ;;
--title) title=$2; shift ;;
--python) python=$2; shift ;;
--port) port=$2; shift ;;
--branch) branch=$2; shift ;;
--repo-url) repo_url=$2; shift ;;
--install-url) install_url=$2; shift ;;
--no-resolve) resolve=0 ;;
-h|--help) sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
*) echo "unknown argument: $1" >&2; exit 2 ;;
esac
shift
done
[ -n "$dir" ] && [ -n "$name" ] && [ -n "$repo_url" ] || { echo "usage: scaffold.sh --dir <path> --name <slug> --repo-url <url> [...]" >&2; exit 2; }
[[ $repo_url =~ ^(https://|ssh://|git@[^:]+:) ]] || { echo "--repo-url must be https://..., ssh://... or git@host:owner/repo.git" >&2; exit 2; }
[[ $repo_url =~ ://[^/]*@ ]] && { echo "--repo-url must not contain credentials; they go in the server's .env" >&2; exit 2; }
# Raw URL of install.sh, and the header a private repo's token goes in.
token_header="Authorization: Bearer "
if [[ $repo_url =~ github\.com[:/]([^/]+)/([^/]+)$ ]]; then
derived="https://raw.githubusercontent.com/${BASH_REMATCH[1]}/${BASH_REMATCH[2]%.git}/$branch/install.sh"
token_header="Authorization: token "
elif [[ $repo_url =~ gitlab\.com[:/](.+)/([^/]+)$ ]]; then
gl_path="${BASH_REMATCH[1]}/${BASH_REMATCH[2]%.git}"
derived="https://gitlab.com/api/v4/projects/${gl_path//\//%2F}/repository/files/install.sh/raw?ref=$branch"
token_header="PRIVATE-TOKEN: "
else derived=; fi
install_url=${install_url:-$derived}
[ -n "$install_url" ] || { echo "can't derive the raw install.sh URL for $repo_url; pass --install-url" >&2; exit 2; }
[[ $name =~ ^[a-z][a-z0-9-]*$ ]] || { echo "--name must be a lowercase slug (letters, digits, -)" >&2; exit 2; }
[ -n "$title" ] || title=$(echo "$name" | tr '-' ' ' | sed -E 's/(^| )([a-z])/\1\u\2/g')
if [ -e "$dir" ] && [ -n "$(ls -A "$dir" | grep -v '^\.git$' || true)" ]; then
echo "$dir exists and is not empty; refusing to overwrite" >&2; exit 1
fi
# Fallback pins, verified 2026-11 on Python 3.14.
fastapi=0.162 uvicorn=0.54 pytest=9.2 httpx=2.16
if [ "$resolve" = 1 ]; then
echo "resolving current versions in python:$python-slim ..."
if out=$(docker run --rm "python:$python-slim" sh -c \
'pip install -q --disable-pip-version-check --root-user-action=ignore fastapi "uvicorn[standard]" pytest httpx2 >/dev/null 2>&1 && pip freeze'); then
v() { echo "$out" | sed -n "s/^$1==\([0-9]*\.[0-9]*\).*/\1/p"; }
fastapi=$(v fastapi) uvicorn=$(v uvicorn) pytest=$(v pytest) httpx=$(v httpx2)
else
echo "could not resolve versions (offline, or no python:$python-slim image); using fallback pins" >&2
fi
fi
mkdir -p "$dir"
cp -r "$TEMPLATE/." "$dir/"
if [ -f "$TOKENS" ]; then
cp "$TOKENS" "$dir/app/static/css/tokens.css"
else
echo "web-frontend skill not found; writing minimal tokens.css" >&2
cat > "$dir/app/static/css/tokens.css" <<'CSS'
:root { color-scheme: light dark; --hue: 250; --bg: oklch(0.985 0.01 var(--hue)); --surface: oklch(1 0 0);
--surface-2: oklch(0.965 0.01 var(--hue)); --border: oklch(0.9 0.015 var(--hue)); --fg: oklch(0.22 0.02 var(--hue));
--fg-muted: oklch(0.45 0.02 var(--hue)); --ok: oklch(0.55 0.13 150); --danger: oklch(0.55 0.19 25);
--font-body: ui-sans-serif, system-ui, sans-serif; --font-mono: ui-monospace, Menlo, monospace;
--text-xs: .75rem; --text-lg: 1.125rem; --weight-medium: 500; --weight-semibold: 600; --measure: 65ch;
--space-2: .5rem; --space-4: 1rem; --space-5: 1.25rem; --space-6: 1.5rem; --space-12: 3rem;
--gutter: max(16px, 4vw); --content-max: 72rem; --radius-md: 8px; --radius-full: 999px; }
@media (prefers-color-scheme: dark) { :root { --bg: oklch(0.17 0.015 var(--hue)); --surface: oklch(0.21 0.015 var(--hue));
--surface-2: oklch(0.245 0.015 var(--hue)); --border: oklch(0.3 0.02 var(--hue)); --fg: oklch(0.95 0.01 var(--hue));
--fg-muted: oklch(0.74 0.015 var(--hue)); --ok: oklch(0.72 0.14 150); --danger: oklch(0.7 0.17 25); } }
body { margin: 0; background: var(--bg); color: var(--fg); font-family: var(--font-body); line-height: 1.6; }
.label { font-size: var(--text-xs); font-weight: var(--weight-semibold); text-transform: uppercase; letter-spacing: .06em; color: var(--fg-muted); }
CSS
fi
# Fill placeholders in every text file.
find "$dir" -type f ! -path '*/.git/*' -print0 | xargs -0 sed -i \
-e "s|__NAME__|$name|g" -e "s|__TITLE__|$title|g" -e "s|__PYTHON__|$python|g" \
-e "s|__PORT__|$port|g" -e "s|__BRANCH__|$branch|g" \
-e "s|__REPO_URL__|$repo_url|g" -e "s|__INSTALL_URL__|$install_url|g" -e "s|__TOKEN_HEADER__|$token_header|g" \
-e "s|__FASTAPI__|$fastapi.*|g" -e "s|__UVICORN__|$uvicorn.*|g" \
-e "s|__PYTEST__|$pytest.*|g" -e "s|__HTTPX__|$httpx.*|g"
chmod +x "$dir/container/entrypoint.sh" "$dir/container/update.sh" "$dir/install.sh"
# The machine's own .env: gitignored, read by the container.
cp "$dir/.env.example" "$dir/.env"
chmod 600 "$dir/.env"
[ -d "$dir/.git" ] || git -C "$dir" init -q -b "$branch"
git -C "$dir" remote get-url origin >/dev/null 2>&1 || git -C "$dir" remote add origin "$repo_url"
left=$(grep -rl '__[A-Z]*__' "$dir" --exclude-dir=.git || true)
[ -z "$left" ] || { echo "unfilled placeholders in: $left" >&2; exit 1; }
echo "scaffolded $name in $dir (Python $python, fastapi $fastapi, uvicorn $uvicorn)"
echo "install command (after the first push): curl -fsSL $install_url | bash"
echo "next: bash $SKILL_DIR/scripts/verify.sh $dir"

View file

@ -0,0 +1,153 @@
#!/usr/bin/env bash
# Prove the scaffold's contract end to end, on a throwaway copy (the project itself, its
# .env and its git history are not touched):
# 1. the image builds and the container comes up healthy, cloning from a "remote" repo
# named in .env
# 2. the tests pass in the dev setup
# 3. `docker exec <c> update` deploys a new commit (with a requirements change) without
# rebuilding the image or restarting the container
# 4. an update to code that fails to import is refused; the old commit keeps serving
# 5. an update to code that crashes at startup is rolled back; the old commit keeps serving
# 6. `update --rollback` returns to the commit before the last successful update
# 7. install.sh, piped into bash as on a fresh server, clones from a git:// remote, writes
# .env (uid 1000, mode 640), and brings the app up healthy; a re-run is safe and only
# replaces the .env keys passed to it. Docker is not reinstalled (it is present here).
# verify.sh <project-dir> [--keep] # --keep leaves the containers and temp dir for debugging
set -uo pipefail
project=$(cd "${1:?usage: verify.sh <project-dir> [--keep]}" && pwd)
keep=0; [ "${2:-}" = --keep ] && keep=1
W=$(mktemp -d "${TMPDIR:-/tmp}/scaffold-verify.XXXXXX")
P="verify-$(basename "$project" | tr -cd 'a-z0-9-')-$$"
C="$P-app"
branch=$(sed -n 's/^REPO_REF=//p' "$project/.env.example"); branch=${branch:-main}
fails=0
step() { printf '\n== %s\n' "$*"; }
pass() { printf ' PASS %s\n' "$*"; }
fail() { printf ' FAIL %s\n' "$*"; fails=$((fails + 1)); }
dc() { docker compose -p "$P" -f "$W/work/compose.yml" -f "$W/verify.yml" "$@"; }
cleanup() {
if [ "$keep" = 1 ]; then echo "kept: $W, compose project $P (docker compose -p $P down -v)"; return; fi
dc down -v --rmi local >/dev/null 2>&1
docker compose -p "$P-dev" -f "$W/work/compose.yml" -f "$W/work/compose.dev.yml" -f "$W/verify-dev.yml" down -v >/dev/null 2>&1
docker image rm -f "$P:latest" >/dev/null 2>&1
[ -f "$W/opt/compose.yml" ] && (cd "$W/opt" && docker compose down -v --rmi local >/dev/null 2>&1)
[ -n "${daemon:-}" ] && kill "$daemon" 2>/dev/null
rm -rf "$W"
}
trap cleanup EXIT
health() { docker exec "$C" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen("http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null; }
wait_for() { # wait_for <version> <seconds>
for _ in $(seq 1 "$2"); do [ "$(health)" = "$1" ] && return 0; sleep 1; done; return 1; }
commit() { git -C "$W/work" add -A && git -C "$W/work" commit -qm "$1" && git -C "$W/work" push -q origin "$branch" && git -C "$W/work" rev-parse --short HEAD; }
step "copy project to $W and create a remote"
mkdir -p "$W/work"
tar -C "$project" --exclude=.git --exclude=.env --exclude=data -cf - . | tar -C "$W/work" -xf -
git -C "$W/work" init -q -b "$branch"
git -C "$W/work" -c user.name=verify -c user.email=verify@localhost add -A
git -C "$W/work" -c user.name=verify -c user.email=verify@localhost commit -qm "initial"
git clone -q --bare "$W/work" "$W/seed.git"
git -C "$W/work" remote add origin "$W/seed.git"
git -C "$W/work" config user.name verify; git -C "$W/work" config user.email verify@localhost
c1=$(git -C "$W/work" rev-parse --short HEAD)
sed -e "s|^REPO_URL=.*|REPO_URL=/seed.git|" -e "s|^REPO_REF=.*|REPO_REF=$branch|" \
-e "s|^GIT_TOKEN=.*|GIT_TOKEN=verify-dummy-token|" "$W/work/.env.example" > "$W/work/.env"
echo "VERIFY_SETTING=from-dotenv" >> "$W/work/.env"
chmod 600 "$W/work/.env"
cat > "$W/verify.yml" <<EOF
services:
app:
image: $P:latest
container_name: $C
environment:
CONTAINER_NAME: $C
ports: !reset []
volumes:
- $W/seed.git:/seed.git:ro
EOF
cat > "$W/verify-dev.yml" <<EOF
services:
app:
image: $P:latest
container_name: $C-dev
ports: !reset []
EOF
pass "remote at $W/seed.git, initial commit $c1"
step "1. build and start"
if dc up -d --build >"$W/build.log" 2>&1 && wait_for "$c1" 120; then pass "healthy at $c1 (cloned from REPO_URL in .env)"
else fail "did not come up healthy; build log and container log:"; tail -20 "$W/build.log"; docker logs --tail 40 "$C" 2>&1; exit 1; fi
image0=$(docker inspect -f '{{.Image}}' "$C"); started0=$(docker inspect -f '{{.State.StartedAt}}' "$C")
appenv=$(docker exec "$C" sh -c 'for d in /proc/[0-9]*; do grep -q uvicorn "$d/cmdline" 2>/dev/null && tr "\0" "\n" < "$d/environ"; done')
grep -qx 'VERIFY_SETTING=from-dotenv' <<<"$appenv" && pass "app sees settings from .env" || fail "app does not see VERIFY_SETTING from .env"
grep -q 'verify-dummy-token' <<<"$appenv" && fail "app process can see GIT_TOKEN" || pass "app process cannot see GIT_TOKEN"
docker exec "$C" grep -rqs 'verify-dummy-token' /srv/src/.git/config /srv/state && fail "token written to disk" || pass "token not written into the checkout or state"
[ "$(docker exec "$C" git -C /srv/src config --get remote.origin.url)" = /seed.git ] && pass "origin is the REPO_URL from .env" || fail "origin URL is not REPO_URL"
step "2. tests (dev setup)"
if docker compose -p "$P-dev" -f "$W/work/compose.yml" -f "$W/work/compose.dev.yml" -f "$W/verify-dev.yml" run --rm app pytest -q >"$W/test.log" 2>&1; then
pass "pytest: $(grep -E 'passed|failed' "$W/test.log" | tail -1)"
else fail "pytest failed:"; tail -30 "$W/test.log"; fi
step "3. update to a new commit"
echo "idna>=3" >> "$W/work/requirements.txt"
c2=$(commit "add a requirement")
if out=$(docker exec "$C" update 2>&1) && [ "$(health)" = "$c2" ]; then pass "update -> $c2"; else fail "update to $c2 failed:"; echo "$out"; fi
[ "$(docker inspect -f '{{.Image}}' "$C")" = "$image0" ] && pass "same image (no rebuild)" || fail "image changed"
[ "$(docker inspect -f '{{.State.StartedAt}}' "$C")" = "$started0" ] && pass "same container start time (no container restart)" || fail "container restarted"
docker exec "$C" /srv/venv/bin/python -c 'import idna' 2>/dev/null && pass "new requirement installed" || fail "new requirement missing"
out=$(docker exec "$C" update 2>&1); [[ $out == already* ]] && pass "second update is a no-op ($out)" || fail "second update: $out"
step "4. update to code that does not import"
cp "$W/work/app/main.py" "$W/main.py.good"
echo 'raise RuntimeError("broken on purpose by verify.sh")' >> "$W/work/app/main.py"
c3=$(commit "broken import")
if docker exec "$C" update >"$W/u4.log" 2>&1; then fail "update to broken $c3 reported success"; else pass "update refused (exit non-zero)"; fi
[ "$(health)" = "$c2" ] && pass "still serving $c2" || fail "serving '$(health)', expected $c2"
[ "$(docker exec "$C" git -C /srv/src rev-parse --short HEAD)" = "$c2" ] && pass "checkout back at $c2" || fail "checkout not restored"
step "5. update to code that crashes at startup"
cp "$W/main.py.good" "$W/work/app/main.py"
sed -i 's| DATA_DIR.mkdir(parents=True, exist_ok=True)| raise RuntimeError("startup failure on purpose by verify.sh")|' "$W/work/app/main.py"
grep -q 'startup failure on purpose' "$W/work/app/main.py" || fail "could not plant the startup failure"
c4=$(commit "broken startup")
if docker exec -e HEALTH_TIMEOUT=10 "$C" update >"$W/u5.log" 2>&1; then fail "update to crashing $c4 reported success"; else pass "update rolled back (exit non-zero)"; fi
wait_for "$c2" 30 && pass "still serving $c2" || { fail "serving '$(health)', expected $c2"; cat "$W/u5.log"; docker logs --tail 20 "$C"; }
[ "$(docker inspect -f '{{.State.StartedAt}}' "$C")" = "$started0" ] && pass "container stayed up" || fail "container restarted"
step "6. rollback"
cp "$W/main.py.good" "$W/work/app/main.py"; commit "fixed" >/dev/null
if docker exec "$C" update --rollback >"$W/u6.log" 2>&1 && [ "$(health)" = "$c1" ]; then pass "rolled back to $c1"; else fail "rollback failed:"; cat "$W/u6.log"; fi
step "7. install.sh on a fresh host"
iname="$P-i"
pname=$(sed -n 's/^name: //p' "$project/compose.yml")
mkdir -p "$W/isrc" "$W/bin"
tar -C "$project" --exclude=.git --exclude=.env --exclude=data -cf - . | tar -C "$W/isrc" -xf -
grep -rl -- "$pname" "$W/isrc" | xargs sed -i "s/$pname/$iname/g"
git -C "$W/isrc" init -q -b "$branch" && git -C "$W/isrc" add -A && git -C "$W/isrc" -c user.name=verify -c user.email=verify@localhost commit -qm initial
ic=$(git -C "$W/isrc" rev-parse --short HEAD)
git clone -q --bare "$W/isrc" "$W/serve/iseed.git"
gport=$(python3 -c 'import socket; s=socket.socket(); s.bind(("",0)); print(s.getsockname()[1])')
hport=$(python3 -c 'import socket; s=socket.socket(); s.bind(("",0)); print(s.getsockname()[1])')
hostip=$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p')
git daemon --export-all --reuseaddr --listen=0.0.0.0 --port="$gport" --base-path="$W/serve" "$W/serve" >/dev/null 2>&1 & daemon=$!
sleep 1
printf '#!/bin/sh\necho "sudo was called: $*" >&2; exit 1\n' > "$W/bin/sudo"; chmod +x "$W/bin/sudo"
irun() { PATH="$W/bin:$PATH" INSTALL_DIR="$W/opt" REPO_URL="git://$hostip:$gport/iseed.git" "$@" bash < "$W/isrc/install.sh"; }
if irun env HOST_PORT="$hport" >"$W/i1.log" 2>&1; then pass "installer exit 0 (piped into bash, no sudo needed)"; else fail "installer failed:"; tail -30 "$W/i1.log"; fi
iv=$(docker exec "$iname" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen("http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null)
[ "$iv" = "$ic" ] && pass "container $iname healthy at $ic" || fail "container not healthy at $ic (got '$iv')"
[ "$(stat -c '%u %a' "$W/opt/.env" 2>/dev/null)" = "1000 640" ] && pass ".env owned by uid 1000, mode 640" || fail ".env ownership/mode: $(stat -c '%u %a' "$W/opt/.env" 2>&1)"
grep -qx "REPO_URL=git://$hostip:$gport/iseed.git" "$W/opt/.env" && grep -qx "HOST_PORT=$hport" "$W/opt/.env" && pass ".env has REPO_URL and HOST_PORT" || fail ".env missing REPO_URL/HOST_PORT"
curl -fsS "http://127.0.0.1:$hport/healthz" >/dev/null && pass "reachable on 127.0.0.1:$hport" || fail "not reachable on host port $hport"
if PATH="$W/bin:$PATH" INSTALL_DIR="$W/opt" GIT_USERNAME=verify-user bash < "$W/isrc/install.sh" >"$W/i2.log" 2>&1; then pass "re-run exit 0"; else fail "re-run failed:"; tail -30 "$W/i2.log"; fi
grep -qx "GIT_USERNAME=verify-user" "$W/opt/.env" && grep -qx "HOST_PORT=$hport" "$W/opt/.env" && pass "re-run replaced only the passed key, kept the rest" || fail ".env after re-run: $(grep -E '^(GIT_USERNAME|HOST_PORT|REPO_URL)=' "$W/opt/.env")"
docker exec "$iname" update --check 2>&1 | grep -q "up to date" && pass "update works in the installed container" || fail "update --check in installed container"
(cd "$W/opt" && docker compose down -v --rmi local >/dev/null 2>&1)
echo
if [ "$fails" = 0 ]; then echo "VERIFY: PASS"; exit 0; fi
echo "VERIFY: FAIL ($fails)"; keep=1; exit 1

View file

@ -0,0 +1,3 @@
# The image is built from container/ only; the source reaches the container through git.
*
!container/

View file

@ -0,0 +1,21 @@
# install.sh writes .env from this file on the server (see README).
# Gitignored. The container reads it at startup and on every `update`, so edits apply on the
# next update or restart; no rebuild. Plain KEY=value lines; quotes optional; not executed.
# The remote the container pulls the source from, and the branch/tag it follows.
REPO_URL=__REPO_URL__
REPO_REF=__BRANCH__
# Private repo over https: a read-only access token (GitHub fine-grained token with
# Contents: read, GitLab deploy token, ...). Leave empty for a public repo.
GIT_USERNAME=
GIT_TOKEN=
# Or private repo over SSH: an ssh REPO_URL (git@host:owner/repo.git) and a read-only deploy
# key, base64-encoded on one line: base64 -w0 deploy_key
GIT_SSH_KEY=
# Host port on 127.0.0.1 (used by compose, not the app).
HOST_PORT=__PORT__
# App settings go below; the app sees them as environment variables.

View file

@ -0,0 +1,6 @@
.env
deploy_key*
__pycache__/
.venv/
.pytest_cache/
data/

View file

@ -0,0 +1,89 @@
# __TITLE__
A FastAPI backend serving a plain HTML/CSS/JS frontend, in one container. Nothing is compiled: no bundler, no TypeScript, no Sass. The image holds only the runtime. The source lives in a git checkout inside a volume, so a deploy is one command and needs no image rebuild.
## Layout
```
app/main.py FastAPI app: /healthz, /api, static files, index page
app/api.py JSON API routes (under /api)
app/static/ the frontend, served as is (vendor libraries into static/vendor/)
tests/ pytest
container/ Dockerfile, entrypoint (setup + supervisor), update script
compose.yml production
compose.dev.yml development overlay (bind-mounted source, auto reload)
requirements.txt runtime dependencies (pinned); requirements-dev.txt for tests
```
## Develop
The host needs only Docker and git.
```bash
docker compose -f compose.yml -f compose.dev.yml up --build # http://127.0.0.1:__PORT__
docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
```
Python changes reload on save; frontend changes show on the next page load.
## Install on a server
On a fresh Linux server (Debian, Ubuntu, Fedora, RHEL and others), paste one line:
```bash
# public repo
curl -fsSL __INSTALL_URL__ | bash
# private repo: asks for a read-only token without echoing it
read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "__TOKEN_HEADER__$GIT_TOKEN" __INSTALL_URL__ | bash
```
`install.sh` does the whole setup:
- installs git and Docker (Engine and Compose) if they're missing
- checks it can read `__REPO_URL__`
- clones it into `/opt/__NAME__`
- writes `/opt/__NAME__/.env` (the repo URL, branch, credentials and port that `update` uses)
- builds the image, starts the container and waits until it is healthy
Settings such as `INSTALL_DIR`, `REPO_REF`, `HOST_PORT`, `GIT_TOKEN` and `GIT_SSH_KEY` can be passed as environment variables; the top of `install.sh` lists them. For an SSH-only private repo, copy `install.sh` to the server and run `GIT_SSH_KEY="$(base64 -w0 deploy_key)" bash install.sh`.
Re-running the installer is safe. It keeps `.env`, replacing only the keys you pass, then updates the checkout, rebuilds and restarts. Re-run it whenever `container/` changes, or to rotate a credential.
After that, every deploy is:
```bash
git push # from your machine
docker exec __NAME__ update # on the server
```
`update` fetches, checks out the new commit, installs the requirements if they changed, checks that `app.main` imports, restarts the app process and waits until `/healthz` reports the new commit. If any step fails it goes back to the previous commit and exits non-zero. Other forms:
```bash
docker exec __NAME__ update --check # what an update would bring in
docker exec __NAME__ update v1.4.0 # a tag, branch or commit
docker exec __NAME__ update --rollback # back to the commit before the last update
```
The app restarts in place, so there is a second or two of downtime while it restarts. The container itself keeps running.
A rebuild is needed only when `container/` or the Python version changes. For that, re-run the install command, or run `docker compose up -d --build` in `/opt/__NAME__`. `update` prints a reminder when an update touches `container/`.
## The `.env` file
`.env` is gitignored and stays on the machine. It is mounted read-only into the container, which reads it at startup and again on every `update`. So a changed URL, branch or rotated token takes effect on the next update, with no rebuild or recreate.
| Variable | Meaning |
|---|---|
| `REPO_URL` | The remote the container pulls from (https or SSH). Keep credentials out of the URL. |
| `REPO_REF` | The branch (or tag) that `update` follows. |
| `GIT_TOKEN`, `GIT_USERNAME` | Private repo over https: a read-only token. A git credential helper supplies it, so it is never written into the checkout. |
| `GIT_SSH_KEY` | Private repo over SSH: a read-only deploy key, base64-encoded on one line (`base64 -w0 deploy_key`). |
| anything else | App settings. The app sees them as environment variables; it never sees the git credentials. |
`install.sh` writes `.env` owned by uid 1000 (the container's user) with mode 640. If you set up by hand, do the same, and create `.env` before the first `docker compose up`: if it is missing, Docker creates an empty directory in its place, and the container stops with an error saying so.
## Data and config
- Persistent app data goes under `$DATA_DIR` (`/data`, the `data` volume). Back up that volume.
- Configuration and secrets live in `.env`, never in the repo.
- Do startup work (creating tables, migrations) in `lifespan` in `app/main.py`, and make it idempotent. Don't do it at import time: `update` imports the app as a check before it restarts it.

View file

@ -0,0 +1,12 @@
"""JSON API, mounted under /api. Split into a package (app/api/<area>.py) as it grows."""
import os
from fastapi import APIRouter
router = APIRouter()
@router.get("/info")
def info() -> dict:
return {"name": "__TITLE__", "version": os.environ.get("APP_VERSION", "dev")}

View file

@ -0,0 +1,50 @@
"""__TITLE__: FastAPI backend serving a no-build static frontend from app/static."""
import contextlib
import os
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from app import api
VERSION = os.environ.get("APP_VERSION", "dev")
STATIC = Path(__file__).parent / "static"
DATA_DIR = Path(os.environ.get("DATA_DIR", "data"))
@contextlib.asynccontextmanager
async def lifespan(_app: FastAPI):
# Startup work goes here, not at import time: `update` imports this module as a check
# before restarting. Create tables or run migrations idempotently here.
DATA_DIR.mkdir(parents=True, exist_ok=True)
yield
app = FastAPI(title="__TITLE__", version=VERSION, lifespan=lifespan, docs_url="/api/docs", redoc_url=None, openapi_url="/api/openapi.json")
app.include_router(api.router, prefix="/api")
@app.get("/healthz", include_in_schema=False)
def healthz() -> dict:
# `update` waits for this to report the new commit before it calls the update done.
return {"status": "ok", "version": VERSION}
class Assets(StaticFiles):
"""Browsers revalidate on every load (cheap 304s), so an update shows up at once."""
async def get_response(self, path, scope):
response = await super().get_response(path, scope)
response.headers["Cache-Control"] = "no-cache"
return response
app.mount("/static", Assets(directory=STATIC), name="static")
@app.get("/", include_in_schema=False)
def index() -> FileResponse:
return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"})

View file

@ -0,0 +1,20 @@
/* App styles on top of tokens.css. Plain CSS, no preprocessor. */
.wrap { max-width: var(--content-max); margin-inline: auto; padding-inline: var(--gutter); }
.topbar { border-bottom: 1px solid var(--border); background: var(--surface); }
.topbar-inner { display: flex; align-items: center; justify-content: space-between; gap: var(--space-4); height: 3.5rem; }
.brand { font-weight: var(--weight-semibold); color: var(--fg); text-decoration: none; }
main.wrap { display: grid; gap: var(--space-6); padding-block: var(--space-12); }
.lead { font-size: var(--text-lg); color: var(--fg-muted); max-width: var(--measure); margin: 0; }
h1 { margin: 0; text-wrap: balance; }
.card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius-md); padding: var(--space-5); max-width: 32rem; }
.card h2 { margin: 0 0 var(--space-2); }
.card p { margin: 0; }
.badge { display: inline-flex; align-items: center; height: 1.375rem; padding-inline: var(--space-2);
font: var(--weight-medium) var(--text-xs) / 1 var(--font-mono); border-radius: var(--radius-full);
background: var(--surface-2); color: var(--fg-muted); }
.ok { color: var(--ok); }
.error { color: var(--danger); }

View file

@ -0,0 +1,27 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>__TITLE__</title>
<link rel="stylesheet" href="/static/css/tokens.css">
<link rel="stylesheet" href="/static/css/app.css">
<script type="module" src="/static/js/main.js"></script>
</head>
<body>
<header class="topbar">
<div class="wrap topbar-inner">
<a class="brand" href="/">__TITLE__</a>
<span class="badge" id="version" title="Running commit">…</span>
</div>
</header>
<main class="wrap">
<h1>__TITLE__</h1>
<p class="lead">FastAPI serves this page and the JSON API under <code>/api</code>. Edit <code>app/static</code> and reload; there is no build step.</p>
<section class="card" aria-labelledby="status-heading">
<h2 id="status-heading" class="label">Server</h2>
<p id="status" aria-live="polite">Checking…</p>
</section>
</main>
</body>
</html>

View file

@ -0,0 +1,14 @@
// Small fetch wrapper: JSON in, JSON out, errors carry the server's message.
export async function getJSON(path, options = {}) {
const response = await fetch(path, { headers: { Accept: "application/json" }, ...options });
if (!response.ok) {
let detail = response.statusText;
try { detail = (await response.json()).detail ?? detail; } catch {}
throw new Error(`${response.status} ${detail}`);
}
return response.json();
}
export function postJSON(path, body) {
return getJSON(path, { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify(body) });
}

View file

@ -0,0 +1,15 @@
// Plain ES modules, no bundler. Vendor any library into /static/vendor and import it by path.
import { getJSON } from "./api.js";
const status = document.getElementById("status");
const version = document.getElementById("version");
try {
const info = await getJSON("/api/info");
version.textContent = info.version;
status.textContent = `Running ${info.name} at commit ${info.version}.`;
status.className = "ok";
} catch (err) {
status.textContent = `Could not reach the API: ${err.message}`;
status.className = "error";
}

View file

@ -0,0 +1,13 @@
# Local development: the source is this folder, bind-mounted, and uvicorn reloads on save.
# docker compose -f compose.yml -f compose.dev.yml up --build
# docker compose -f compose.yml -f compose.dev.yml run --rm app pytest
# `update` is disabled in dev; use git on the host. Separate project name = separate volumes.
name: __NAME__-dev
services:
app:
container_name: __NAME__-dev
environment:
DEV: "1"
CONTAINER_NAME: __NAME__-dev
volumes:
- .:/srv/src

View file

@ -0,0 +1,40 @@
# Production. install.sh sets this up on a server (see README); by hand it is:
# clone into /opt/__NAME__, write .env from .env.example, docker compose up -d --build
# Deploys after that: docker exec __NAME__ update
name: __NAME__
services:
app:
build:
context: .
dockerfile: container/Dockerfile
image: __NAME__:latest
container_name: __NAME__
restart: unless-stopped
environment:
CONTAINER_NAME: __NAME__
# Only a reverse proxy at these addresses may set X-Forwarded-For.
FORWARDED_ALLOW_IPS: ${FORWARDED_ALLOW_IPS:-127.0.0.1}
# Loopback only: put a reverse proxy or tunnel in front of it.
ports:
- "127.0.0.1:${HOST_PORT:-__PORT__}:8000"
volumes:
- runtime:/srv # source checkout, venv, update state
- data:/data # the app's persistent data
# Repo URL, credentials and app settings, read on every start and every update.
# Not env_file: a mounted file can change without recreating the container.
- ./.env:/run/config/app.env:ro
read_only: true
tmpfs:
- /tmp
cap_drop: [ALL]
security_opt:
- no-new-privileges:true
mem_limit: 256m
logging:
driver: json-file
options:
max-size: 10m
max-file: "3"
volumes:
runtime:
data:

View file

@ -0,0 +1,35 @@
# The image is the runtime only: Python, git and the scripts in this folder. The app's
# source is cloned into the /srv volume on first start and updated in place by `update`,
# so a rebuild is needed only when this folder or the Python version changes.
ARG PYTHON_VERSION=__PYTHON__
FROM python:${PYTHON_VERSION}-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends git openssh-client tini \
&& rm -rf /var/lib/apt/lists/*
ARG UID=1000
ARG GID=1000
RUN groupadd --gid "$GID" app \
&& useradd --uid "$UID" --gid app --create-home --shell /usr/sbin/nologin app \
&& mkdir -p /srv/src /srv/venv /srv/state /data \
&& chown -R app:app /srv /data \
&& git config --system --add safe.directory '*'
COPY container/lib.sh /usr/local/lib/app/lib.sh
COPY --chmod=755 container/entrypoint.sh /usr/local/bin/entrypoint
COPY --chmod=755 container/update.sh /usr/local/bin/update
ENV PATH=/srv/venv/bin:$PATH \
PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_NO_CACHE_DIR=1 \
DATA_DIR=/data \
PORT=8000
USER app
WORKDIR /srv/src
EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \
CMD python3 -c "import os, urllib.request; urllib.request.urlopen(f'http://127.0.0.1:{os.environ[\"PORT\"]}/healthz', timeout=3)"
ENTRYPOINT ["tini", "--", "entrypoint"]

View file

@ -0,0 +1,58 @@
#!/usr/bin/env bash
# Container entrypoint (runs under tini). Gets the source and venv ready, then supervises
# uvicorn: SIGHUP restarts the app on the current checkout (that's how `update` swaps code
# in without restarting the container); SIGTERM stops it. If the app dies on its own, the
# container exits and Docker's restart policy takes over.
#
# With arguments, it runs them in the source dir after setup instead, e.g.
# docker compose run --rm app pytest
set -uo pipefail
. /usr/local/lib/app/lib.sh
load_env
ensure_source || exit 1
sync_deps || die "installing requirements failed"
cd "$SRC"
if [ $# -gt 0 ]; then
export PATH="$VENV/bin:$PATH"
exec "$@"
fi
child=
stopping=0
restart=0
trap 'stopping=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' TERM INT
trap 'restart=1; [ -n "$child" ] && kill -TERM "$child" 2>/dev/null' HUP
echo $$ > "$PIDFILE"
start_app() {
local args=(app.main:app --host 0.0.0.0 --port "$PORT"
--proxy-headers --forwarded-allow-ips "${FORWARDED_ALLOW_IPS:-127.0.0.1}"
--no-server-header --timeout-graceful-shutdown 10)
[ "${DEV:-}" = 1 ] && args+=(--reload)
export APP_VERSION
APP_VERSION=$(current_version)
log "starting app at $APP_VERSION"
env "${APP_ENV_UNSET[@]}" "$VENV/bin/uvicorn" "${args[@]}" &
child=$!
}
while :; do
start_app
wait "$child"; rc=$?
# A trapped signal interrupts `wait` while the child is still shutting down.
while kill -0 "$child" 2>/dev/null; do wait "$child"; rc=$?; done
[ "$stopping" = 1 ] && exit 0
if [ "$restart" = 1 ]; then restart=0; continue; fi
log "app exited with status $rc"
# New code that crashes at startup must not take the container down mid-update, or
# `update` dies with it and can't roll back. Wait for its restart signal instead.
if ! flock -n /tmp/app-update.lock true; then
log "an update is running; waiting for it to restart the app"
while [ "$restart" = 0 ] && [ "$stopping" = 0 ]; do sleep 1 & wait $!; done
[ "$stopping" = 1 ] && exit 0
restart=0; continue
fi
exit "$rc"
done

View file

@ -0,0 +1,122 @@
# Shared by entrypoint and update. Installed at /usr/local/lib/app/lib.sh.
# Config: the project .env, mounted at /run/config/app.env, read by load_env.
# Layout inside the container:
# /srv/src git checkout of the app (cloned from REPO_URL on first start, or bind-mounted in dev)
# /srv/venv virtualenv built from requirements.txt (rebuilt when requirements or Python change)
# /srv/state update bookkeeping (previous commit, ssh known_hosts)
# /data the app's own persistent data
# /srv is one named volume, so source, venv and state survive container recreation.
SRC=${SRC:-/srv/src}
VENV=${VENV:-/srv/venv}
STATE=${STATE:-/srv/state}
PORT=${PORT:-8000}
PIDFILE=/tmp/app-supervisor.pid
ENV_FILE=${ENV_FILE:-/run/config/app.env}
log() { echo "[$(basename "$0")] $*" >&2; }
die() { log "error: $*"; exit 1; }
# Read the project's .env (bind-mounted read-only at $ENV_FILE). It runs on every start
# and every update, so a new URL or rotated token takes effect without a rebuild.
# Plain KEY=value lines only; it is parsed, not executed. Values never get printed.
load_env() {
[ -e "$ENV_FILE" ] || return 0
[ -f "$ENV_FILE" ] || die "$ENV_FILE is not a file (create .env before 'docker compose up'; Docker made a directory in its place)"
[ -r "$ENV_FILE" ] || die "$ENV_FILE is not readable by uid $(id -u): chown $(id -u) .env && chmod 600 .env on the host"
local line key val
while IFS= read -r line || [ -n "$line" ]; do
line=${line%$'\r'}
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
export "$key=$val"
done < "$ENV_FILE"
setup_git_auth
}
# Credentials for REPO_URL, from the environment only. Nothing is written into the checkout:
# https: GIT_TOKEN (+ GIT_USERNAME, default x-access-token) answered by a credential helper
# ssh: GIT_SSH_KEY, the private key base64-encoded (base64 -w0 deploy_key)
setup_git_auth() {
if [ -n "${GIT_TOKEN:-}" ]; then
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
fi
local ssh="ssh -o UserKnownHostsFile=$STATE/known_hosts -o StrictHostKeyChecking=accept-new"
if [ -n "${GIT_SSH_KEY:-}" ]; then
local key=/tmp/git-deploy-key
(umask 077; printf '%s' "$GIT_SSH_KEY" | base64 -d > "$key") || die "GIT_SSH_KEY is not valid base64"
ssh="$ssh -i $key -o IdentitiesOnly=yes"
fi
export GIT_SSH_COMMAND="$ssh" GIT_TERMINAL_PROMPT=0
}
# Hide user:password@ if someone put credentials in the URL anyway.
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
# The app gets the .env settings but not the repo credentials.
APP_ENV_UNSET=(-u GIT_TOKEN -u GIT_USERNAME -u GIT_SSH_KEY -u GIT_CONFIG_COUNT -u GIT_CONFIG_KEY_0 -u GIT_CONFIG_VALUE_0)
# Clone the source on first start. A bind-mounted checkout (dev) already has .git.
ensure_source() {
mkdir -p "$STATE"
[ -d "$SRC/.git" ] && return 0
[ -n "${REPO_URL:-}" ] || die "no source at $SRC and REPO_URL is not set in .env"
log "cloning $(redact "$REPO_URL") (${REPO_REF:-main}) into $SRC"
# $SRC may exist as an empty dir; clone into it.
git clone --quiet --branch "${REPO_REF:-main}" "$REPO_URL" "$SRC"
}
# Follow REPO_URL if .env changed it. Credentials are never part of the stored URL.
sync_remote() {
[ -n "${REPO_URL:-}" ] || return 0
[ "$(git -C "$SRC" remote get-url origin 2>/dev/null)" = "$REPO_URL" ] || git -C "$SRC" remote set-url origin "$REPO_URL"
}
requirement_files() {
echo "$SRC/requirements.txt"
if [ "${DEV:-}" = 1 ] && [ -f "$SRC/requirements-dev.txt" ]; then echo "$SRC/requirements-dev.txt"; fi
}
# Bring the venv in line with the checkout. A no-op when nothing changed.
sync_deps() {
local py want files
py=$(python3 -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])')
mapfile -t files < <(requirement_files)
want="$py $(cat "${files[@]}" | sha256sum | cut -d' ' -f1)"
if [ "$(cat "$VENV/.python" 2>/dev/null)" != "$py" ]; then
log "creating venv for Python $py"
rm -rf "$VENV"
python3 -m venv "$VENV"
echo "$py" > "$VENV/.python"
fi
[ "$(cat "$VENV/.synced" 2>/dev/null)" = "$want" ] && return 0
log "installing requirements"
local args=()
for f in "${files[@]}"; do args+=(-r "$f"); done
"$VENV/bin/pip" install --quiet --disable-pip-version-check --no-cache-dir "${args[@]}" || return 1
echo "$want" > "$VENV/.synced"
}
# The new code must at least import before it replaces the running app.
check_import() {
(cd "$SRC" && "$VENV/bin/python" -c 'import app.main') || return 1
}
current_version() { git -C "$SRC" rev-parse --short HEAD 2>/dev/null || echo dev; }
# Wait until /healthz answers with the expected version (or any version if none given).
wait_healthy() {
local want=${1:-} timeout=${HEALTH_TIMEOUT:-30} got
for _ in $(seq 1 "$timeout"); do
got=$(python3 - "$PORT" <<'PY' 2>/dev/null
import json, sys, urllib.request
r = urllib.request.urlopen(f"http://127.0.0.1:{sys.argv[1]}/healthz", timeout=2)
print(json.load(r).get("version", ""))
PY
) && { [ -z "$want" ] || [ "$got" = "$want" ]; } && return 0
sleep 1
done
return 1
}

View file

@ -0,0 +1,81 @@
#!/usr/bin/env bash
# Pull the latest source from the remote repo in .env (REPO_URL, REPO_REF and credentials)
# into the running container and restart the app on it. No rebuild.
# docker exec <container> update # to the tip of REPO_REF
# docker exec <container> update <ref> # to a tag, branch or commit
# docker exec <container> update --check # show what an update would bring in
# docker exec <container> update --rollback # back to the commit before the last update
# Steps: fetch, check out, sync requirements, import check, restart, wait for /healthz to
# report the new commit. If any step fails, it puts the previous commit back and exits 1.
set -euo pipefail
. /usr/local/lib/app/lib.sh
usage() { sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//'; exit "${1:-0}"; }
mode=update force=0 ref=
while [ $# -gt 0 ]; do
case $1 in
--check) mode=check ;;
--rollback) mode=rollback ;;
--force) force=1 ;;
-h|--help) usage ;;
-*) usage 1 ;;
*) ref=$1 ;;
esac
shift
done
load_env
[ "${DEV:-}" = 1 ] && die "dev mode: the source is bind-mounted from the host; update it with git there"
[ -d "$SRC/.git" ] || die "no checkout at $SRC"
exec 9>/tmp/app-update.lock
flock -n 9 || die "another update is running"
cd "$SRC"
old=$(git rev-parse HEAD)
if [ "$mode" = rollback ]; then
new=$(cat "$STATE/previous" 2>/dev/null) || die "no previous commit recorded"
else
sync_remote
git fetch --quiet --prune --tags origin
target=${ref:-${REPO_REF:-main}}
# A branch resolves on the remote; a tag or commit as given.
new=$(git rev-parse --verify --quiet "origin/$target^{commit}" || git rev-parse --verify --quiet "$target^{commit}") \
|| die "unknown ref: $target"
fi
short() { git rev-parse --short "$1"; }
if [ "$mode" = check ]; then
if [ "$old" = "$new" ]; then echo "up to date at $(short "$old")"; else
echo "$(short "$old") -> $(short "$new")"
git log --oneline "$old..$new" 2>/dev/null || true
fi
exit 0
fi
[ "$old" = "$new" ] && { echo "already at $(short "$new")"; exit 0; }
if [ "$force" = 0 ] && [ -n "$(git status --porcelain --untracked-files=no)" ]; then
die "the checkout has local changes (inspect with: docker exec ${CONTAINER_NAME:-<container>} git -C $SRC status); --force discards them"
fi
restart_app() { kill -HUP "$(cat "$PIDFILE")" || return 1; sleep 1; }
apply() { git reset --quiet --hard "$1" && sync_deps && check_import; }
restarted=0
log "updating $(short "$old") -> $(short "$new")"
if apply "$new" && restarted=1 && restart_app && wait_healthy "$(short "$new")"; then
echo "$old" > "$STATE/previous"
git log --oneline "$old..$new" 2>/dev/null | head -20 || true
if [ -n "$(git diff --name-only "$old" "$new" -- container/)" ]; then
log "note: container/ changed; rebuild the image to pick that up (docker compose up -d --build)"
fi
echo "updated to $(short "$new")"
exit 0
fi
log "update failed; going back to $(short "$old")"
apply "$old" || die "could not restore $(short "$old"): the app may be down, check: docker logs ${CONTAINER_NAME:-<container>}"
[ "$restarted" = 1 ] || { log "the running app was never touched"; exit 1; }
restart_app && wait_healthy "$(short "$old")" || die "restored $(short "$old") but it is not healthy; check: docker logs ${CONTAINER_NAME:-<container>}"
log "running $(short "$old") again"
exit 1

View file

@ -0,0 +1,232 @@
#!/usr/bin/env bash
# Install (or upgrade) __TITLE__ on a Linux server. Paste one line into a fresh server:
#
# Public repo:
# curl -fsSL __INSTALL_URL__ | bash
#
# Private repo over https (the token is asked for, not typed into history):
# read -rsp 'Git token: ' GIT_TOKEN && export GIT_TOKEN && curl -fsSL -H "__TOKEN_HEADER__$GIT_TOKEN" __INSTALL_URL__ | bash
#
# Private repo over SSH: copy this file to the server, then
# GIT_SSH_KEY="$(base64 -w0 deploy_key)" bash install.sh
#
# What it does: installs git and Docker (Engine + Compose) if missing, clones the repo into
# $INSTALL_DIR, writes $INSTALL_DIR/.env (repo URL, branch, credentials, port) for the
# container's `update`, builds the image, starts the container and waits until it is
# healthy. Re-running it is safe: it keeps .env (values you pass replace those keys),
# pulls the checkout, rebuilds the image and restarts. Run it again whenever container/
# changes; for ordinary deploys use `docker exec __NAME__ update`.
#
# Settings (environment variables, all optional):
# INSTALL_DIR default /opt/__NAME__
# REPO_URL default __REPO_URL__
# REPO_REF default __BRANCH__
# GIT_TOKEN, GIT_USERNAME private repo over https
# GIT_SSH_KEY private repo over SSH (base64-encoded deploy key)
# HOST_PORT default __PORT__ (bound to 127.0.0.1)
#
# Everything is inside main(), so a partial download runs nothing.
main() {
set -euo pipefail
local NAME=__NAME__
INSTALL_DIR=${INSTALL_DIR:-/opt/$NAME}
local DEFAULT_REPO_URL="__REPO_URL__" DEFAULT_REF="__BRANCH__" DEFAULT_PORT="__PORT__"
# Which keys the caller passed explicitly (these replace values in an existing .env).
local passed=()
for k in REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT; do
[ -n "${!k:-}" ] && passed+=("$k")
done
[ "$(uname -s)" = Linux ] || die "this installer is for Linux servers"
SUDO=
if [ "$(id -u)" != 0 ]; then
command -v sudo >/dev/null || die "run as root, or install sudo"
SUDO=sudo
fi
step "prerequisites"
install_packages
install_docker
step "source"
load_existing_env
REPO_URL=${REPO_URL:-$DEFAULT_REPO_URL}
REPO_REF=${REPO_REF:-$DEFAULT_REF}
HOST_PORT=${HOST_PORT:-$DEFAULT_PORT}
git_auth
check_access
checkout
step "configuration"
write_env
step "container"
(cd "$INSTALL_DIR" && $DOCKER compose up -d --build --remove-orphans)
wait_healthy
step "done"
cat <<EOF
$NAME is running at $(health_version) on http://127.0.0.1:$HOST_PORT (loopback; put a reverse proxy or tunnel in front).
deploy a new commit: docker exec $NAME update
see what's new: docker exec $NAME update --check
undo the last update: docker exec $NAME update --rollback
logs: docker logs -f $NAME
settings: $INSTALL_DIR/.env (re-read on every update)
rebuild/upgrade: run this installer again
EOF
[ "$DOCKER" = docker ] || echo " (prefix docker with sudo, or add yourself to the docker group)"
}
# Run a command directly, and only with sudo if that fails (no password prompt when not needed).
priv() { "$@" 2>/dev/null || { [ -n "$SUDO" ] && $SUDO "$@"; }; }
read_file() { if [ -r "$1" ]; then cat "$1"; else $SUDO cat "$1"; fi; }
step() { printf '\n==> %s\n' "$*"; }
log() { printf ' %s\n' "$*"; }
die() { printf '\nerror: %s\n' "$*" >&2; exit 1; }
install_packages() {
local need=()
command -v git >/dev/null || need+=(git)
command -v curl >/dev/null || need+=(curl)
command -v ssh >/dev/null || need+=(ssh)
[ ${#need[@]} -eq 0 ] && { log "git, curl, ssh: present"; return; }
log "installing ${need[*]}"
if command -v apt-get >/dev/null; then
local pkgs=("${need[@]/ssh/openssh-client}")
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get update -qq
$SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq ca-certificates "${pkgs[@]}" >/dev/null
elif command -v dnf >/dev/null; then
$SUDO dnf install -y -q ca-certificates "${need[@]/ssh/openssh-clients}"
elif command -v apk >/dev/null; then
$SUDO apk add -q ca-certificates "${need[@]/ssh/openssh-client}"
else
die "no apt-get, dnf or apk: install ${need[*]} yourself and re-run"
fi
}
install_docker() {
if ! command -v docker >/dev/null; then
log "installing Docker Engine + Compose (get.docker.com)"
local dlog; dlog=$(mktemp)
curl -fsSL https://get.docker.com | $SUDO sh >"$dlog" 2>&1 || { tail -20 "$dlog" >&2; die "Docker install failed (full log: $dlog)"; }
rm -f "$dlog"
fi
if ! docker info >/dev/null 2>&1 && ! $SUDO docker info >/dev/null 2>&1 \
&& command -v systemctl >/dev/null && [ -d /run/systemd/system ]; then
$SUDO systemctl enable --now docker >/dev/null 2>&1 || true
fi
if docker info >/dev/null 2>&1; then DOCKER=docker; else DOCKER="$SUDO docker"; fi
$DOCKER info >/dev/null 2>&1 || die "Docker is installed but the daemon is not running"
$DOCKER compose version >/dev/null 2>&1 || die "the Docker Compose plugin is missing (apt-get install docker-compose-plugin)"
log "docker $($DOCKER version --format '{{.Server.Version}}'), compose $($DOCKER compose version --short)"
}
# Values already in .env fill in whatever the caller did not pass.
load_existing_env() {
local f="$INSTALL_DIR/.env" line key val
[ -f "$f" ] || return 0
log "keeping existing $f"
while IFS= read -r line || [ -n "$line" ]; do
line=${line%$'\r'}
[[ $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
key=${BASH_REMATCH[2]} val=${BASH_REMATCH[3]}
if [[ $val =~ ^\"(.*)\"$ || $val =~ ^\'(.*)\'$ ]]; then val=${BASH_REMATCH[1]}; fi
case $key in REPO_URL|REPO_REF|GIT_TOKEN|GIT_USERNAME|GIT_SSH_KEY|HOST_PORT)
[ -n "${!key:-}" ] || printf -v "$key" '%s' "$val" ;;
esac
done < <(read_file "$f")
}
# Credentials reach git through the environment only; nothing is stored in the checkout.
git_auth() {
export GIT_TERMINAL_PROMPT=0
if [ -n "${GIT_TOKEN:-}" ]; then
export GIT_TOKEN GIT_USERNAME="${GIT_USERNAME:-}"
export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=credential.helper
export GIT_CONFIG_VALUE_0='!f() { [ "$1" = get ] || exit 0; echo "username=${GIT_USERNAME:-x-access-token}"; echo "password=$GIT_TOKEN"; }; f'
fi
local ssh="ssh -o StrictHostKeyChecking=accept-new"
if [ -n "${GIT_SSH_KEY:-}" ]; then
KEYFILE=$(mktemp); trap 'rm -f "$KEYFILE"' EXIT
printf '%s' "$GIT_SSH_KEY" | base64 -d > "$KEYFILE" 2>/dev/null || die "GIT_SSH_KEY is not valid base64 (use: base64 -w0 deploy_key)"
ssh="$ssh -i $KEYFILE -o IdentitiesOnly=yes"
fi
export GIT_SSH_COMMAND="$ssh"
}
check_access() {
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable: $(redact "$REPO_URL") ($REPO_REF)"; return; }
# Private https repo and no token yet: ask on the terminal (stdin is this script).
if [ -z "${GIT_TOKEN:-}" ] && [[ $REPO_URL == https://* ]] && [ -r /dev/tty ]; then
printf ' %s needs a token. Git token (read-only): ' "$(redact "$REPO_URL")" > /dev/tty
IFS= read -rs GIT_TOKEN < /dev/tty; echo > /dev/tty
passed+=(GIT_TOKEN)
git_auth
git ls-remote --exit-code --heads --tags "$REPO_URL" "$REPO_REF" >/dev/null 2>&1 && { log "repo reachable with token"; return; }
fi
die "cannot read $REPO_REF from $(redact "$REPO_URL"). Check REPO_URL/REPO_REF, and pass GIT_TOKEN (https) or GIT_SSH_KEY (ssh) for a private repo"
}
# The host checkout holds compose.yml and container/ (what the image is built from).
# The app itself runs from the container's own checkout, which `update` manages.
checkout() {
if [ ! -d "$INSTALL_DIR/.git" ]; then
priv mkdir -p "$INSTALL_DIR"
[ -w "$INSTALL_DIR" ] || $SUDO chown "$(id -u):$(id -g)" "$INSTALL_DIR"
[ -z "$(ls -A "$INSTALL_DIR" | grep -vx .env || true)" ] || die "$INSTALL_DIR exists and is not a checkout of $NAME"
log "new checkout in $INSTALL_DIR"
git -C "$INSTALL_DIR" init --quiet
git -C "$INSTALL_DIR" remote add origin "$REPO_URL"
fi
# First install and re-runs alike: fetch and check out REPO_REF.
git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL"
git -C "$INSTALL_DIR" fetch --quiet --prune --tags origin
local target
target=$(git -C "$INSTALL_DIR" rev-parse --verify --quiet "origin/$REPO_REF^{commit}" || git -C "$INSTALL_DIR" rev-parse --verify "$REPO_REF^{commit}")
git -C "$INSTALL_DIR" reset --quiet --hard "$target"
log "at $(git -C "$INSTALL_DIR" log -1 --format='%h %s')"
}
# .env: created from .env.example on first install; on re-runs only the keys the caller
# passed are replaced. Owned by uid 1000 (the container's user), group = installer, mode 640.
write_env() {
local f="$INSTALL_DIR/.env" tmp line key out=() seen=" "
if [ -f "$f" ]; then mapfile -t lines < <(read_file "$f"); else
mapfile -t lines < "$INSTALL_DIR/.env.example"
passed=(REPO_URL REPO_REF GIT_TOKEN GIT_USERNAME GIT_SSH_KEY HOST_PORT)
log "writing $f"
fi
for line in "${lines[@]}"; do
key=${line%%=*}
if [[ $line =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] && [[ " ${passed[*]} " == *" $key "* ]]; then
out+=("$key=${!key:-}"); seen+="$key "
else out+=("$line"); fi
done
for key in "${passed[@]}"; do [[ $seen == *" $key "* ]] || out+=("$key=${!key:-}"); done
tmp=$(mktemp)
printf '%s\n' "${out[@]}" > "$tmp"
priv install -m 640 -o 1000 -g "$(id -g)" "$tmp" "$f" || die "could not write $f"
rm -f "$tmp"
[ ${#passed[@]} -eq 0 ] || log "set in .env: ${passed[*]}"
}
health_version() {
$DOCKER exec "$NAME" python3 -c 'import json,urllib.request;print(json.load(urllib.request.urlopen(f"http://127.0.0.1:8000/healthz",timeout=2))["version"])' 2>/dev/null
}
wait_healthy() {
log "waiting for the app (first start clones the repo and installs requirements)"
for _ in $(seq 1 180); do
[ -n "$(health_version)" ] && { log "healthy at $(health_version)"; return; }
[ "$($DOCKER inspect -f '{{.State.Running}}' "$NAME" 2>/dev/null)" = false ] && break
sleep 1
done
$DOCKER logs --tail 40 "$NAME" >&2 || true
die "$NAME did not become healthy (logs above)"
}
redact() { printf '%s' "$1" | sed -E 's#://[^/@]+@#://***@#'; }
main "$@"

View file

@ -0,0 +1,5 @@
[pytest]
testpaths = tests
pythonpath = .
# The source may be a read-only or foreign-owned bind mount; don't write a cache into it.
addopts = -p no:cacheprovider

View file

@ -0,0 +1,2 @@
pytest==__PYTEST__
httpx2==__HTTPX__

View file

@ -0,0 +1,2 @@
fastapi==__FASTAPI__
uvicorn[standard]==__UVICORN__

View file

@ -0,0 +1,23 @@
from fastapi.testclient import TestClient
from app.main import app
def test_healthz():
with TestClient(app) as client:
response = client.get("/healthz")
assert response.status_code == 200
assert response.json()["status"] == "ok"
def test_index_and_assets():
with TestClient(app) as client:
page = client.get("/")
css = client.get("/static/css/app.css")
assert page.status_code == 200 and "__TITLE__" in page.text
assert css.status_code == 200 and css.headers["cache-control"] == "no-cache"
def test_info():
with TestClient(app) as client:
assert client.get("/api/info").json()["name"] == "__TITLE__"