diff --git a/docker-compose.yml b/docker-compose.yml index 3638510..821e4b0 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -110,7 +110,7 @@ services: - vigilcare_net minio: - image: quay.io/minio/minio:RELEASE.2024-07-04T14-25-45Z + image: git.vectur45.com/trent/ci-minio:latest container_name: vigilcare_minio command: server /data --console-address ":9001" ports: diff --git a/docs/CICD/README.md b/docs/CICD/README.md new file mode 100644 index 0000000..0110fc5 --- /dev/null +++ b/docs/CICD/README.md @@ -0,0 +1,87 @@ +# CICD + +Reusable CI/CD practice for every project in this monorepo and the standalone repos +(.NET 8, Node, Vue 3, React, Nuxt, React Native, Python). Platform is Gitea Actions on a +self-hosted runner, images in the Gitea registry, Compose on one VM per environment. + +## Start here + +**[`platform/observed-state.md`](platform/observed-state.md)** — what this Gitea instance and +runner *actually* do, measured. Every rule in the playbooks below is written against it, and +several rules were wrong until it existed. Re-measure after any Gitea or runner upgrade. + +**Adding a project?** → [`onboarding-a-project.md`](onboarding-a-project.md). +**Wondering why something is the way it is?** → [`platform/change-log.md`](platform/change-log.md). + +## Which document + +| You are… | Read | +| --- | --- | +| Wondering what the runner supports, or whether a rule still holds | [`platform/observed-state.md`](platform/observed-state.md) | +| Reproducing the runner config on a new VM | [`platform/config/runner.yaml`](platform/config/runner.yaml) | +| Fixing slow builds or slow CI | [`ci-cd-build-cache.md`](ci-cd-build-cache.md) | +| Wiring a deploy host, Tailscale deps, or connection strings | [`hybrid-gcp-tailscale-cicd.md`](hybrid-gcp-tailscale-cicd.md) | +| Putting another project on this CI/CD | [`onboarding-a-project.md`](onboarding-a-project.md) | +| Starting CD from scratch, or copying the bake | [`templates/`](templates/) — placeholders only, no product names | +| Asking why a rule exists, or what the platform looked like before | [`platform/change-log.md`](platform/change-log.md) | +| Editing a shared pipeline | [`infra/`](infra/) — staged source for `infra/ci-workflows` | +| Gitea is 504 / the VM is wedged during CD | [Host budget → If Gitea returns 504](platform/observed-state.md#if-gitea-returns-504-during-cd), then [`scripts/runner-host.sh`](scripts/runner-host.sh) | +| Capping the bake so it cannot starve Gitea | [`scripts/cap-buildx-builder.sh`](scripts/cap-buildx-builder.sh) | +| Needing a broker (RabbitMQ) in CI — `services:` will not work | [`scripts/start-job-sidecars.sh`](scripts/start-job-sidecars.sh) + `infra/ci-workflows/.../node-service-ci.yml` | +| Asking which toolchain image built a past release | [Toolchain image log](platform/observed-state.md#toolchain-image-log) | +| Capping BuildKit so CD cannot freeze Gitea | [`scripts/cap-buildx-builder.sh`](scripts/cap-buildx-builder.sh) | +| Reclaiming a wedged runner host (after GCP **Reset** if 504) | [`scripts/runner-host.sh`](scripts/runner-host.sh) | + +## Rules that depend on the runner, not on your repo + +These changed on 2026-09-28 / 2026-09-29 and will change again. Never copy them from a plan +document — check `platform/observed-state.md`: + +| Behaviour | Governed by | +| --- | --- | +| Whether `Host=postgres` resolves in CI | `container.network` | +| Whether jobs run concurrently | `runner.capacity` | +| Whether `actions/cache` does anything | `cache.*` reachability from job containers | +| Whether `--shm-size` reaches a service container | runner version + `container.privileged` | +| Which expressions work (`failure()`, `always()`) | runner version — **not** what the docs say | +| Which toolchain a job gets | `runner.labels` (the label *is* the image) — mirrored and digest-pinned; see the [toolchain log](platform/observed-state.md#toolchain-image-log) | +| Whether a `container.options` flag has any effect | the runner's parser subset — `--memory` was silently ignored on v0.6.1; retest on 4.x | +| Whether a job can write to this Gitea | `GITEA_TOKEN` is injected; the instance is reachable from job containers | +| How many cores a job may use | Host is **e2-standard-2** (2 vCPU / 8 GB); Gitea shares the box — cap **every** test/eval step | +| Whether CD bake leaves Gitea alive | buildkitd cgroup (`cap-buildx-builder.sh`) + one bake target at a time; parallelism=1 alone is not enough | +| Whether CI Postgres is ready | `pg_isready` can pass in crash recovery (`57P03`); tests wait for queries | +| Whether migrate extract works after bake | scratch `migrate-bundle` needs `CMD` + `docker create IMAGE /out/migrate-api` | + +## Verifying + +[`.gitea/workflows/probe.yml`](../.gitea/workflows/probe.yml) measures the expression, cache, shm, and service-DNS rows. It is +`workflow_dispatch`-only. Run it after any runner or Gitea upgrade and update +`platform/observed-state.md` §5. The `expressions` job fails by design — that is the measurement. + +## Standardization status + +| Step | State | +| --- | --- | +| Measure the platform | ✅ done — `platform/observed-state.md` | +| Runner config version-controlled | ✅ done — `platform/config/runner.yaml` | +| `ci.yml` uses service DNS, no published DB ports | ✅ done | +| Testhost cap on **every** test/eval step (`DOTNET_PROCESSOR_COUNT=1`) | ✅ done — GrowthOS backend 2026-09-28: build 10m12s (was 20–30 min), unit 4m34s, integration 6m0s green | +| Integration tests wait for Postgres queries (`57P03`) | ✅ done | +| CD bake capped (buildkitd cgroup + one target at a time) | ✅ done — GrowthOS CD 2026-09-29: bake 14m29s, Gitea stayed up; `cap-buildx-builder.sh` | +| Scratch `migrate-bundle` extract (`CMD` + `docker create … /path`) | ✅ done — bare `docker create` failed with `no command specified` after green bake | +| Copy-paste templates carry placeholders, not product names | ✅ done 2026-09-30 — `templates/` replaced `.gitea_example/`, which had `fleet-telemetry` baked into 10+ places | +| `runner.capacity` > 1 | ⬜ blocked — host is e2-standard-2; needs a bigger VM or a second runner | +| Mirror + digest-pin the label image, then `force_pull: false` | ✅ done 2026-09-29 — needs a monthly re-mirror owner | +| Runner → `gitea/runner:4.x` | ✅ done 2026-09-29 — 4.0.0; probe, CI and CD green | +| Artifact actions on `@v4` (both ends together) | ✅ done 2026-09-29 — round trip verified; the v3 pin retired | +| `builtin:checkout` (no Node, no github.com) | ✅ CI + CD green — only the `changes` job stays on `actions/checkout@v4`, pending a `fetch-depth: 0` result | +| Reusable workflows (`workflow_call`) | ✅ done 2026-09-30 — `infra/ci-workflows@v1`; GrowthOS `ci.yml` 267 → 145 lines | +| Onboarding guide for other projects | ✅ done — [`onboarding-a-project.md`](onboarding-a-project.md) | +| Platform change log (initial → current state) | ✅ done — [`platform/change-log.md`](platform/change-log.md) | +| Onboard further projects | ✅ three done 2026-09-30 (fleet-telemetry, pos, inline-inspection). `dotnet8-ci.yml` needed **no new inputs** across all three — the interface generalizes. `node-ci.yml` needed one (`post_build_command`). | +| Fold project-kit improvements back | ✅ done 2026-09-30 — see [`platform/change-log.md`](platform/change-log.md) | +| Shared composite actions (`infra/ci-actions`: capped bake, bundle extract, deploy, smoke) | ⬜ after project two | +| Golden CI base images per stack + label taxonomy | ⬜ | +| Scoped workflows for enforced invariants (Gitea 1.27+) | ⬜ | +| Per-stack templates (Node, Vue, React, Nuxt, RN, Python) | ⬜ | +| Promote ephemeral git VM IP to regional static | ⬜ — avoids DNS redo if Stop is ever used | diff --git a/docs/CICD/ci-cd-build-cache.md b/docs/CICD/ci-cd-build-cache.md new file mode 100644 index 0000000..cda64e4 --- /dev/null +++ b/docs/CICD/ci-cd-build-cache.md @@ -0,0 +1,398 @@ +# CI/CD build cache — apply to any repo + +Copy this into another service when CI or tag-deploy is slow. It is stack-agnostic. The worked example is GrowthOS ([phase-3b-plan.md](../docs/plans/phase-3b-plan.md), live [`.gitea/workflows/`](../.gitea/workflows/)). A one-image copy-paste is [`templates/`](templates/). + +**Objective:** cut wall-clock, not image size. Engineer wait and runner minutes first. + +Assumes: Gitea Actions + `act_runner` labelled `ubuntu-latest`, host Docker, a Gitea registry, Compose on one VM. One runner unless the checklist says otherwise. BuildKit is the default builder. No QEMU/`--platform` unless you measured a real multi-arch need. + +Gitea **queues** jobs; [Gitea Runner](https://docs.gitea.com/runner/) executes them. `runs-on: ubuntu-latest` is a **registered label**, not a GitHub-hosted VM. + +Runner behaviour is a **variable, not a constant**. Labels, `container.network`, `capacity`, cache reachability, and whether workflow-supplied container options survive all come from the runner's `config.yaml` and its version. Measure them; do not inherit them from a blog post or from this file. [`platform/observed-state.md`](platform/observed-state.md) is this fleet's measured state and the source of truth for every runner-dependent rule below — including two that were wrong here until 2026-09-28. + +Assumed execution mode: **Docker with the host socket**. Jobs are isolated from each other; they share the daemon. That is why BuildKit cache mounts and a named `buildx` builder survive across tags. DinD wipes that persistence; host mode has no job isolation. Do not copy this playbook onto those modes without re-measuring. + +`GITEA_TOKEN` cannot publish to the container registry. CD must keep `REGISTRY_USERNAME` / `REGISTRY_TOKEN` (a PAT). The same token **is** injected into every job and the instance is reachable from job containers — see §8. Do not let product code treat it as an app PAT. + +A second registered runner is the first time extra Gitea jobs shorten wall clock. Until then, parallelism is bake and BuildKit stages only. + +--- + +## 1. Measure before changing flags + +`docker build --progress=plain` (CD) and the last green job timestamps (CI). Attribute every minute to one bucket: + +| Bucket | Symptom | Usual fix | +| --- | --- | --- | +| Context upload | Pause before the first step | `.dockerignore` at the **context root** | +| Dependency install | `restore` / `npm ci` / `pip` dominates | Layer order, then cache mounts + a CI cache backend | +| Compilation | `publish` / `vite` / `go build` | Native arch first; then incremental caches | +| Push | Job sits after “exporting to image” | One `buildx --push` with all tags; smaller final image last; turn off default provenance | +| Serialisation | Independent work in one chain | Bake / parallel **stages**, not more **jobs** on one runner | + +Record the numbers in the PR. Do not add `cache-to` until this baseline exists. + +GrowthOS backend on this fleet (2026-09-28, green, `e2-standard-2`): restore **2m7s**, build **10m12s** (was 20–30 min), unit **4m34s** (was 13m31s abort), integration **6m0s** green. GrowthOS CD tag (2026-09-29, green, capped bake): build-and-push **15m48s** (bake **14m29s**), migrate **1m32s**, deploy **1m12s** — Gitea stayed up. Source: [`platform/observed-state.md` Host budget](platform/observed-state.md#host-budget). + +Emulation (QEMU, `--platform linux/amd64` on arm64) is 5–20× on compile. If you see it, fix architecture before Dockerfiles. + +--- + +## 2. Symptoms that mean “do this guide” + +| You see | It means | +| --- | --- | +| `COPY . .` then `dotnet restore` / `npm ci` / `pip install` | Every source edit reinstalls. Junior cache miss. | +| CD builds `--target final`, next job builds `--target migrate` | Fourth cold SDK restore. Same graph, thrown away. | +| Three `docker build` + two `docker push` each | Sequential images + extra tag round-trips. | +| `Cache export is not supported for the docker driver` | Bake used the default builder. Need `docker-container` for `cache-to`. | +| `Could not find file '…/.nuget/packages/…/*.nuspec'` | Concurrent restores wrote the same cache `id`. Split ids or lock restore only. | +| `setup-node` has `cache: npm`, `setup-dotnet` has none | .NET pays a cold NuGet every job. | +| Unit tests abort / hang-dump / OOM on a large `AppDbContext` | A new EF InMemory provider per database name recompiles the model. Share one internal provider and one `InMemoryDatabaseRoot`; isolate by **name**. | +| Integration tests fail with `57P03` (recovery mode) after a few minutes | Testhost used both vCPUs and crashed the service Postgres. Cap **every** `dotnet test` step (`DOTNET_PROCESSOR_COUNT=1`). `pg_isready` can still pass — wait for queries. | +| CD bake / registry push stalls Gitea (**504**) or freezes the VM | Bake compiled every target at once, or one compile used both cores and swap. One Gitea job, `cap-buildx-builder.sh` (`--cpus=1 --memory=3g --memory-swap=3g`), bake one target at a time. `BUILDKIT_STEP_MAX_PARALLELISM=1` is not enough. | +| `docker create` fails: `no command specified` after a green migrate bake | Scratch `migrate-bundle` has no `CMD`. Set `CMD ["/out/migrate-api"]` and `docker create IMAGE /out/migrate-api`. | +| `importing cache manifest …:buildcache: not found` | First tag (or pruned cache). Non-fatal — bake continues; `cache-to` creates the ref. Gate on the **second** tag. | +| A second job that only runs fixture tests | Second SDK + restore + implicit build. | +| `vue-tsc` in lint **and** in `npm run build` | Typecheck twice. | +| Path filter is `**` / the whole app tree | Vue-only PR starts Postgres and restores the sln. | +| Three CI jobs on one `act_runner` | Wall clock is the **sum**, not the max. | + +--- + +## 3. Dockerfile: restore-first, then cache mounts + +Layer cache is per instruction. The first miss invalidates everything after it. + +**Wrong** + +```dockerfile +COPY . . +RUN npm ci +``` + +**Right — lockfile, install, then source** + +```dockerfile +# syntax=docker/dockerfile:1 +COPY package.json package-lock.json ./ +RUN --mount=type=cache,id=npm,target=/root/.npm \ + npm ci +COPY . . +``` + +Same shape everywhere. Copy **each manifest into its own directory** — `COPY src/*/*.csproj ./src/` flattens paths and breaks restore. + +| Ecosystem | Copy first | Then | Cache mount | +| --- | --- | --- | --- | +| Node | `package.json` + `package-lock.json` | `npm ci` | `/root/.npm` (`id=npm`) | +| .NET | `*.sln` + each `*.csproj` + `.config/dotnet-tools.json` | `dotnet restore` the **startup project**, not the sln if the sln lists tests you excluded | `/root/.nuget/packages` (`id=nuget-api` / `nuget-worker`) | +| Python | `requirements.txt` / `uv.lock` / `poetry.lock` | `pip` / `uv sync` | `/root/.cache/pip` | +| Go | `go.mod` + `go.sum` | `go mod download` | `/go/pkg/mod` and `/root/.cache/go-build` | +| Rust | `Cargo.toml` + `Cargo.lock` | `cargo fetch` | `/usr/local/cargo/registry` | + +Same `id=` only when restores are **not** concurrent. Bake of API + Worker needs one id per image (`nuget-api`, `nuget-worker`). A shared `id=nuget` with default `sharing=shared` corrupts NuGet (`*.nuspec` missing, leftover extract files). + +`sharing=locked` on **restore only**. Publish / `ef bundle` remount `sharing=shared`. A locked mount is held for the whole `RUN`, so locking publish serializes compile across bake targets. + +### Shared restore for sibling stages + +If `build` and `migrate` (or `api` and `worker`) both start `FROM sdk` + `COPY . .` + restore, they do not share a layer. One `restore` stage, then: + +```dockerfile +FROM restore AS build +COPY . . +RUN --mount=type=cache,id=nuget-api,sharing=shared,target=/root/.nuget/packages \ + dotnet publish src/Api/Api.csproj -c Release -o /app/publish --no-restore + +FROM restore AS migrate +COPY . . +RUN --mount=type=cache,id=nuget-api,sharing=shared,target=/root/.nuget/packages \ + dotnet ef migrations bundle ... --output /out/migrate-api --force + +# Slim image for `type=docker` load — do not export the SDK stage to the daemon. +# scratch has no default command; without CMD, `docker create` fails with +# "no command specified". +FROM scratch AS migrate-bundle +COPY --from=migrate /out/migrate-api /out/migrate-api +CMD ["/out/migrate-api"] + +FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final +COPY --from=build /app/publish . +ENTRYPOINT ["dotnet", "Api.dll"] +``` + +Restore itself uses `sharing=locked` on the same `id=nuget-api`. Worker’s Dockerfile uses `id=nuget-worker`. + +`final` **must stay last** so a bare `docker build` cannot ship the SDK. CD pins `--target final` for the runtime image and `--target migrate-bundle` for the artefact. Do not `COPY --from=build` the publish folder into migrate — `ef bundle` needs the SDK and project graph. + +Cache mounts are **builder-local**. They survive on a persistent Docker-mode `act_runner` (shared host daemon). They do nothing on DinD or a wiped builder until §5. + +--- + +## 4. Context + +`.dockerignore` sits next to the context root (the directory you pass to `docker build`), not next to a Dockerfile in a subdirectory unless that subdirectory **is** the context. + +Exclude whatever the image does not compile: + +- `web/` and `tests/` from an API/Worker context so a Vue or test edit cannot bust restore +- `node_modules`, `bin/`, `obj/`, `.git`, `.env*`, `dist/` + +A fat context costs transfer, cache keys, and leaked secrets. Name all three when you add the file. + +--- + +## 5. CD: one bake, registry cache, no second compile + +Replace sequential `docker build` + `docker push` + `docker push :latest` with `docker buildx bake`. One graph, both tags, **one Gitea job**. + +On **one** runner, do not split API/Worker/Web into three Gitea jobs — they queue. Bake is how those images share a graph. “Scale the runner” means a **second registered runner**, not more YAML. + +On **this** fleet (e2-standard-2 + Gitea) do **not** let bake compile every target at once, and do **not** trust `BUILDKIT_STEP_MAX_PARALLELISM=1` to leave Gitea a core. A single `dotnet publish` still uses both vCPUs and will swap-thrash 8 GB (UI **504**). Keep **one** Gitea job. Before bake, run [`scripts/cap-buildx-builder.sh`](scripts/cap-buildx-builder.sh) so buildkitd is `--cpus=1 --memory=3g --memory-swap=3g`. Then `docker buildx bake ` **one target at a time** so registry push cannot overlap the next compile. SDK stages set `DOTNET_PROCESSOR_COUNT=1`; Node stages keep a small heap (`NODE_OPTIONS=--max-old-space-size=512`). Measured 2026-09-29: bake **14m29s**, Gitea stayed up. + +If Gitea is already 504: GCP **Reset** (keeps the ephemeral IP — never Stop/Start), then [`scripts/runner-host.sh`](scripts/runner-host.sh) `reclaim`. The Actions UI cannot cancel a wedged job. + +`cache-to` (registry) needs the **docker-container** driver. The default `docker` builder cannot export cache even when `buildx` is installed. Inspect of a missing builder is expected: keep it inside `cap-buildx-builder.sh` so `bash -e -o pipefail` does not abort the step. + +```hcl +# Paths: bake resolves relative to the HCL file unless you use cwd:// +# CD from git root → cwd:// +variable "REGISTRY" {} +variable "TAG" {} + +group "default" { + targets = ["api", "migrate", "worker", "web"] +} + +target "api" { + context = "cwd://app" + dockerfile = "src/Api/Dockerfile" + target = "final" + tags = ["${REGISTRY}/api:${TAG}", "${REGISTRY}/api:latest"] + cache-from = ["type=registry,ref=${REGISTRY}/api:buildcache"] + cache-to = ["type=registry,ref=${REGISTRY}/api:buildcache,mode=max"] +} + +target "migrate" { + context = "cwd://app" + dockerfile = "src/Api/Dockerfile" + target = "migrate-bundle" + tags = ["migrate-bundle:local"] + cache-from = ["type=registry,ref=${REGISTRY}/api:buildcache"] + # no cache-to — api already exports this Dockerfile at mode=max +} +``` + +`mode=max` exports intermediate stages (`restore`, `build`, `migrate`). Default `min` only keeps `final` (runtime) and looks like “cache does not work.” + +`mode=max` is a second registry write. On a small service it is cheaper than a cold SDK restore. If cache export dominates the log, drop `cache-to` on the smallest image first. + +```bash +bash CICD/scripts/cap-buildx-builder.sh app-builder +bake_one() { + local target="$1" + shift + BUILDX_NO_DEFAULT_ATTESTATIONS=1 docker buildx bake \ + --progress=plain \ + "$target" \ + "$@" \ + -f docker-bake.hcl +} +bake_one api --push --set api.output=type=image,push=true +sleep 8 +bake_one worker --push --set worker.output=type=image,push=true +sleep 8 +bake_one web --push --set web.output=type=image,push=true +sleep 8 +bake_one migrate --set migrate.output=type=docker +``` + +`--push` on bake plus `type=docker` on the **slim** `migrate-bundle` target: runtime images go to the registry; the SDK stage is **not** loaded into the daemon and is **not** published. + +Restrict `--cache-to` to trusted tag / `workflow_dispatch` workflows. Fork PR CI must not write `buildcache` (cache poisoning). + +### Migrate / extra artefact + +Do not rebuild `--target migrate` in a later job. Bake the slim bundle in `build-and-push`, then: + +1. `docker create IMAGE /out/migrate-api` + `docker cp` the binary (act_runner bind mounts resolve on the **Docker host**, not the job workspace — never `docker run -v` for this). Pass the path as the create command, or set `CMD` on the scratch stage — otherwise Docker returns `no command specified`. +2. `actions/upload-artifact` the file +3. The migrate/deploy job `download-artifact`, SCP, run on the host that can reach Postgres + +Do not rely on “the previous job left an image on the host.” That dies on prune or a second runner. + +Do not push the migrate/SDK image. Do not `type=docker` the SDK `migrate` stage — that load is most of the tail. + +--- + +## 6. CI: cache installs, fold jobs, skip the other stack + +CI is not an image-build problem. Do **not** `docker build` in CI because CD is slow. + +### Cache the toolchain the frontend already cached + +```yaml +- uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + cache: true + cache-dependency-path: "**/*.csproj" # lockfile if you have one + +- uses: actions/setup-node@v4 + with: + node-version: "22" + cache: npm + cache-dependency-path: web/package-lock.json +``` + +Gitea `actions/cache` (behind `cache: true`) is **runner config**, not something the workflow can invent. On this fleet it **hits** — `setup-dotnet cache:` and `setup-node cache: npm` are real. If a copy-paste job no-ops, the operator must enable the runner’s cache backend — or set `NUGET_PACKAGES` / `npm_config_cache` to a **host path the Docker-mode runner keeps**. One mechanism, then measure. See [`platform/observed-state.md`](platform/observed-state.md). + +### Cap testhost on every test step + +Not only unit tests. Copy onto **unit, integration, and eval** steps: + +```yaml +env: + DOTNET_PROCESSOR_COUNT: "1" + DOTNET_gcServer: "0" + DOTNET_GCHeapCount: "1" +``` + +Serialize xUnit (`xunit.runner.json` `maxParallelThreads: 1` plus `-- xUnit.MaxParallelThreads=1`). Tests that `--no-build` after the sln compile. InMemory unit tests in a job whose env points at service Postgres/Redis must blank those connection strings for the unit-test step, or `AppDbContextFactory` will hammer the live DB. + +Postgres service: `--shm-size=256mb` (honoured on this runner with `Privileged=false`) and a start-period long enough that `pg_isready` is not the only gate. Tests wait until queries work — `57P03` is crash recovery, not a flaky assertion. + +### Fold jobs that only exist to compile again + +A fixture/eval assembly that the sln already builds belongs **after** `dotnet build` with `--no-build`. A second job is a second `checkout` + SDK + restore. + +Keep assemblies **sequential** in one job if they would share a TRX filename. Splitting unit vs integration on one runner makes the queue longer. + +### Path-filter so the other stack does not run + +Workflow-level `paths:` still lists the app. Job-level: skip backend (and its Postgres/Redis **services**) when only the SPA changed. + +| Changed | Run | +| --- | --- | +| `web/**` only | frontend | +| `src/**`, `tests/**`, `*.sln`, `.config/**` | backend | +| `.gitea/workflows/**` | both | +| both stacks | both | + +On one runner, a cheap `changes` job (checkout + `git diff`) is worth it because it avoids starting service containers. Native `paths:` on **two workflow files** is the same outcome with no extra job. + +Not running is faster than any cache. + +### Typecheck / lint once + +If `lint` is `vue-tsc --noEmit` and `build` is `vue-tsc -b && vite build`, CI should run one `vue-tsc` then `vite build`. Keep the full script for laptops. + +--- + +## 7. Runner economics (one `act_runner`) + +| Parallelism | Use when | +| --- | --- | +| BuildKit stages + `bake` | Independent images/stages in **one** CD job | +| `cap-buildx-builder.sh` + one bake target at a time | This host — leave Gitea a vCPU; `--cpus=1` on buildkitd | +| Fewer CI jobs + path filters | Same runner; skip work | +| More Gitea jobs | Once `runner.capacity` > 1, or a **second** runner exists | + +Adding Gitea jobs to a runner with `capacity: 1` queues them — wall clock is the sum, not the max. + +The first lever is **`runner.capacity`** in the runner's `config.yaml` (default `1`), *not* a second machine: it runs N jobs concurrently on the same runner. **Do not raise it on this fleet.** The host is GCP **e2-standard-2** (2 vCPU / 8 GB) and also runs Gitea — see [`platform/observed-state.md` Host budget](platform/observed-state.md#host-budget). Two concurrent .NET jobs plus service containers will starve Gitea. Path filters skip unused jobs; a standalone frontend job only overlaps once the VM is bigger or a second runner exists. + +Cap **every** `dotnet test` / eval step in the job (`DOTNET_PROCESSOR_COUNT=1`, workstation GC), not only unit tests. Default `ProcessorCount` is 2 — the whole machine. Uncapped integration testhost crashed service Postgres (`57P03`). Same idea for Node if a job pegs both cores. + +A **second registered runner** comes after capacity is exhausted, and is what `cache.external_server` (a shared cache server) exists for — caches are per-runner otherwise. + +Persistent Docker-mode host Docker **is** the “persistent builder” in the docker reference — the only place cache mounts survive without exporting cache. Do not buy Depot / bigger runners until layer order + registry cache + path filters are in. + +--- + +## 8. Invariants to keep while speeding up + +Copy these only if they already apply. Do not invent them for a repo that does not have them. + +| Rule | Why it exists | +| --- | --- | +| `final` last; CD `--target final` | Bare `docker build` must not ship SDK/`CMD bash` | +| Slim `migrate-bundle` + `CMD` + `docker create IMAGE /out/migrate-api` + `docker cp` | act_runner bind mounts are host-scoped; do not load the SDK image. Scratch without `CMD` fails create with `no command specified`. | +| Migrate on the deploy network, not the runner | Postgres is not on the runner; `Host=postgres` only resolves there | +| Connection strings as SCP files | Remote shell splits on `;` | +| Job graph `build → migrate → deploy → smoke → image rollback` | Do not flatten migrate into deploy | +| CI DB/Redis by **service name**, never published on host ports | With `container.network: ""` the runner builds a per-job network with DNS aliases, so `Host=postgres` / `redis:6379` work. Publishing collides with the runner host's own `5432`/`6379`. (Under `container.network: bridge` there are no aliases — that is what the old high-port + host-discovery workaround existed for. Check `platform/observed-state.md` before assuming either.) | +| Testcontainers only when CI env is unset | CI services already provide the database | +| No `continue-on-error` on tests | A red suite must fail the job | +| PAT for registry login | `GITEA_TOKEN` cannot push packages | +| Toolchain image mirrored into the Gitea registry, digest-pinned, `force_pull: false` | `runs-on:` resolves to a **label**, and the label **is** the image every job runs in. A third-party moving tag on a public registry is an unpinned toolchain re-pulled on the critical path of every build. Mirror it, pin by digest, keep the package public so the runner pulls anonymously, and record the digest — see the toolchain log in [`platform/observed-state.md`](platform/observed-state.md#toolchain-image-log). A pinned base receives no upstream fixes until someone re-mirrors it, so the cadence needs an owner. | +| Blank `GITEA_TOKEN` + product Gitea BaseUrl/DryRun in CI when tests must stay offline | Every job receives `GITEA_TOKEN`; job containers can reach this Gitea. Appsettings `DryRun: true` loses to env. Live Contents/Pulls from CI is a product write, not a fixture. See [`platform/observed-state.md`](platform/observed-state.md). | +| Cap testhost cores/GC on **every** test/eval step (`DOTNET_PROCESSOR_COUNT=1`, workstation GC) | Host is e2-standard-2 (2 vCPU / 8 GB) and also runs Gitea + the runner. Default testhost uses every core. Uncapped integration testhost crashed service Postgres (`57P03`). | +| Cap CD bake (`cap-buildx-builder.sh` cgroup + one target at a time; `DOTNET_PROCESSOR_COUNT=1` in SDK stages) | Default bake compiles every target at once. `BUILDKIT_STEP_MAX_PARALLELISM=1` still lets one compile take both cores and 504 Gitea. Keep one job; cap buildkitd; serialize targets. | +| Wait for Postgres **queries**, not only `pg_isready`; `--shm-size` on the service | `pg_isready` can pass while the engine is in crash recovery (`57P03`). Tests retry until `SELECT` works. | +| One EF InMemory provider + one `InMemoryDatabaseRoot` per test assembly; isolate by database name | A new provider per name recompiles a large `AppDbContext` and OOMs this VM. A new root under `UseInternalServiceProvider` throws. | + +--- + +## 9. Order of work on the next repo + +1. Measure CD (`--progress=plain`) and CI timestamps; write the five buckets in the PR. +2. `.dockerignore` + restore-first Dockerfiles + shared `restore` if two stages restore the same graph. +3. Cache mounts: `sharing=locked` on restore, `sharing=shared` on compile; split ids if bake restores in parallel. +4. `docker-bake.hcl` + `cap-buildx-builder.sh` + one `buildx bake ` at a time + `BUILDX_NO_DEFAULT_ATTESTATIONS=1`; slim `migrate-bundle` (`CMD` + `type=docker`); `docker create IMAGE /out/migrate-api`; artefact the binary. +5. Registry `cache-from` / `cache-to` `mode=max` on trusted CD only. +6. CI: NuGet/npm cache (runner cache backend or host path), fold eval jobs, path filters, one typecheck, testhost cap on **every** test step. +7. Gate on the **second** run (unchanged lockfiles) and a frontend-only push that does not start Postgres. + +Do not start with image-size work, Bazel, hermetic graphs, or a second runner. + +--- + +## 10. Gate checklist + +**CD** + +- [ ] Second tag uses the container builder (no `Cache export is not supported for the docker driver`) +- [ ] Builder container is `--cpus=1 --memory=3g` (`docker inspect` HostConfig); CD bakes one target at a time +- [ ] Scratch `migrate-bundle` has `CMD`; extract uses `docker create IMAGE /out/migrate-api` (not bare create) +- [ ] Second tag on unchanged lockfiles/csproj: restore layer `CACHED` (or NuGet mount skips the network) +- [ ] First-tag `buildcache: not found` did not fail the job; second tag imports cache +- [ ] Migrate/extra job has **no** `docker build` +- [ ] No SDK/migrate image in the registry +- [ ] Smoke + image-tag rollback unchanged +- [ ] Gitea UI stayed responsive during bake (no 504) + +**CI** + +- [ ] Second push on unchanged lockfiles: NuGet and/or npm cache hit +- [ ] Fixture/eval tests use `--no-build` on the sln output +- [ ] `web/**`-only push does not start the backend job (no Postgres) +- [ ] `src/**`-only push does not run the frontend job +- [ ] CI does not `docker build` +- [ ] Every `dotnet test` / eval step sets `DOTNET_PROCESSOR_COUNT=1` (workstation GC) +- [ ] Integration tests wait for Postgres queries (`57P03`), not only `pg_isready` +- [ ] xUnit collections are serial (`maxParallelThreads=1`) + +--- + +## Worked example + +GrowthOS (this repo): [docs/plans/phase-3b-plan.md](../docs/plans/phase-3b-plan.md). One-image template: [`templates/`](templates/). + +| Piece | Path | +| --- | --- | +| API restore + migrate + final | `GrowthOS/src/GrowthOS.Api/Dockerfile` | +| Worker | `GrowthOS/src/GrowthOS.Worker/Dockerfile` | +| Web npm cache mount | `GrowthOS/web/Dockerfile` | +| Bake | `GrowthOS/docker-bake.hcl` | +| Cap BuildKit cgroup | `CICD/scripts/cap-buildx-builder.sh` | +| Reclaim wedged host | `CICD/scripts/runner-host.sh` | +| CD bake + artefact | `.gitea/workflows/cd.yml` | +| CI changes + folded evals | `.gitea/workflows/ci.yml` | +| One-image bake example | `CICD/templates/docker-bake.hcl` | +| One-image CD example | `CICD/templates/workflows/cd.yml` | + +Measured runner state (labels, network, capacity, cache, versions): [`platform/observed-state.md`](platform/observed-state.md). + +Interview depth behind the levers: [docs/Reference/junior/docker](../docs/Reference/junior/docker/docker.json) (layer order, context), [mid](../docs/Reference/mid/docker/docker.json) (cache mounts, CI cache, measuring), [senior](../docs/Reference/senior/docker/docker.json) (build less, persistent builder, `mode=max` cost). diff --git a/docs/CICD/hybrid-gcp-tailscale-cicd.md b/docs/CICD/hybrid-gcp-tailscale-cicd.md new file mode 100644 index 0000000..792991d --- /dev/null +++ b/docs/CICD/hybrid-gcp-tailscale-cicd.md @@ -0,0 +1,237 @@ +# Hybrid CI/CD playbook: cloud VM + home-lab Tailscale deps + +Reusable pattern for any app that deploys containers to a **cloud VM** (e.g. GCP) while some dependencies stay on a **home server** reached over **Tailscale**. + +Canonical layout: + +| Piece | Where it runs | +|---|---| +| App containers (API, UI, workers, …) | Cloud VM under `/opt//` | +| Local deps (often Postgres, Redis) | **Same cloud VM** on external Docker network `shared-services` (Docker DNS names) | +| Remote deps (often RabbitMQ, Seq, …) | Home lab over **Tailscale** (`100.x` IP — not MagicDNS) | +| CI/CD | Build/push images → migrate (if any) → SSH deploy → smoke → optional image rollback | + +**Rule of thumb:** app containers stay on **bridge + `shared-services`**. Do **not** put the app on host networking just to reach Tailscale — that breaks Docker DNS for same-host services (e.g. `Host=postgres`). + +This playbook is project-agnostic. Substitute ``, image names, ports, and env keys for each repo. The live application of it in this repository is **GrowthOS** (`/opt/growth-os`, [`GrowthOS/docker-compose.prod.yml`](../GrowthOS/docker-compose.prod.yml), deployed by [`.gitea/workflows/cd.yml`](../.gitea/workflows/cd.yml)); the archived FleetTelemetry variant (`/opt/fleet-telemetry`) is in [`Completed/FleetTelemetryAPI/`](../Completed/FleetTelemetryAPI/). The `shared-services` network itself is described in §1–§2 below. + +--- + +## 1. Topology rules + +1. **Same-host deps** → Docker DNS on `shared-services` (`postgres`, `redis`, …). +2. **Remote Tailscale deps** → peer **CGNAT IP** in `100.64.0.0/10` (e.g. `100.102.185.124`). +3. **Never** put Tailscale MagicDNS short names inside containers — Docker cannot resolve them. +4. **Never** point same-host Postgres at `127.0.0.1` / `localhost` from a bridge container — you often hit a different instance (`28P01` / wrong DB). +5. **Public browser origins** (API base URL, SPA origin, CORS) stay operator-reachable (usually public HTTPS), not Tailscale-only, unless every client is always on the tailnet. +6. Deploy host **`.env` stays on the VM** (`chmod 600`). CD should not upload secrets; it may only patch `IMAGE_TAG` (or equivalent). +7. **CI service containers are not deploy-host services.** They live on the runner's per-job network and are reached by service name (`Host=postgres`), never by a published host port. This depends on the runner's `container.network` — confirm in [`platform/observed-state.md`](platform/observed-state.md) before copying rule 7 into a new project. + +--- + +## 2. Choose where each dependency lives + +| Dependency | On cloud VM (`shared-services`) | On home via Tailscale | +|---|---|---| +| Connection / host value | Service name, e.g. `Host=postgres` | `100.x.y.z` | +| Migrate / one-shot network | `--network shared-services` | `--network host` (or equivalent) + Tailscale/`127.0.0.1` host | +| Typical split | Postgres, Redis | RabbitMQ, Seq, optional extras | + +Mixed splits are fine (Postgres on GCP, broker on home). Keep the **app on bridge** either way. + +--- + +## 3. One-time: Tailscale + reachability + +On **cloud VM** and **home server**: + +```bash +tailscale up +tailscale status # record the home peer's 100.x address +``` + +From the **cloud VM host**: + +```bash +HOME_TS=100.x.y.z # home Tailscale IP +nc -vz "$HOME_TS" +nc -vz "$HOME_TS" # e.g. Seq 5341 +``` + +From a **bridge container on `shared-services`** (same path the app uses): + +```bash +docker network create shared-services 2>/dev/null || true +docker run --rm --network shared-services curlimages/curl:8.5.0 \ + -sS -o /dev/null -w '%{http_code}\n' --connect-timeout 5 \ + "http://${HOME_TS}:" +``` + +| Result | Action | +|---|---| +| Host OK, container OK | Proceed | +| Host OK, container fail | Fix Tailscale/Docker routing on the VM (Tailscale state, IP forwarding). Do **not** switch the app to host networking | +| Host fail | Tailscale/firewall on home or cloud — fix before deploy | + +On the **home server**, allow the cloud node’s Tailscale IP to the published ports you expose (firewall / compose binds / `tailscale serve` as appropriate). + +--- + +## 4. One-time: cloud deploy host + +```bash +APP=my-app # e.g. fleet-telemetry, pos +docker network create shared-services +sudo mkdir -p "/opt/${APP}" +sudo chown "$USER":"$USER" "/opt/${APP}" +``` + +Start **same-host** infra (Postgres, …) on `shared-services`. Leave remote deps on the home peer. + +```bash +cp .env.example "/opt/${APP}/.env" # from the app repo +chmod 600 "/opt/${APP}/.env" +# edit secrets in place — CI/CD should not overwrite this file +``` + +### Example hybrid `.env` (Postgres on VM, broker + Seq on Tailscale) + +Names vary by project; keep the **hosting pattern**: + +```bash +# Same-host DB — Docker DNS +PG_CONNECTION=Host=postgres;Port=5432;Database=;Username=;Password=;SSL Mode=Disable + +# Remote over Tailscale — 100.x only (not MagicDNS, not "rabbitmq"/"seq") +RABBITMQ_HOST=100.x.y.z +RABBITMQ_PORT=5672 +RABBITMQ_USERNAME=... +RABBITMQ_PASSWORD=... + +SEQ_URL=http://100.x.y.z:5341 +SEQ_API_KEY=... + +# Browser-facing (often baked into a UI image at CD build time) +PUBLIC_API_ORIGIN=https://api.example.com +PUBLIC_UI_ORIGIN=https://app.example.com + +API_PORT=8100 +UI_PORT=8101 +``` + +Recommended CD validation on deploy: + +- DB connection string is Npgsql-style `Host=...;Password=...` (or your stack’s equivalent), **no wrapping quotes**, no accidental URI if the tool expects key=value. +- Reject `Host=127.0.0.1` / `localhost` when the app is on bridge + same-host Postgres. +- Reject MagicDNS short names for remote deps (heuristic: hostname with no `.` that isn’t `localhost`). + +--- + +## 5. One-time: CI/CD secrets & variables (Gitea / GitHub Actions / etc.) + +Adapt names to your workflow; the **roles** are what matter. + +### Secrets + +| Role | Typical name | Hybrid notes | +|---|---|---| +| Registry login | `REGISTRY_USERNAME`, `REGISTRY_TOKEN` | Push from CI; pull on deploy host. Gitea job token (`GITEA_TOKEN`) cannot push packages — `REGISTRY_TOKEN` must be a PAT. | +| Offline Gitea in CI tests | Workflow `env:` `GITEA_TOKEN: ""`, product `Gitea__BaseUrl: ""`, `Gitea__DryRun: "true"` | Actions injects `GITEA_TOKEN` into every job; job containers can reach this instance. An app that binds that token will make live Contents/Pulls calls. | +| SSH deploy | `DEPLOY_HOST`, `DEPLOY_USER`, `DEPLOY_SSH_KEY` | Cloud VM only | +| Schema migrator | `PG_CONNECTION_DDL` (or URI for node-pg) | **Same reachability as runtime Postgres** | + +When Postgres is on the cloud VM: + +```text +Host=postgres;Port=5432;Database=;Username=;Password=...;SSL Mode=Disable +``` + +Paste secret values only (no `KEY=` prefix). Prefer a **file + SCP** for connection strings that contain `;` / spaces — never pass them as bare remote shell argv. + +### Variables + +| Role | Typical name | Hybrid notes | +|---|---|---| +| Public API origin for UI bake | `UI_API_BASE_URL` / `PUBLIC_API_ORIGIN` | Required if the SPA bakes the API base at build time | +| Feature flags / optional URLs | project-specific | Optional | +| Registry namespace override | `REGISTRY` | Optional | +| Migrator Docker network | `MIGRATE_DOCKER_NETWORK` | Default `shared-services` if Postgres is on the VM; `host` only if Postgres is on Tailscale | + +--- + +## 6. CD pipeline shape (each release) + +Trigger: version tag (`v*`) or manual dispatch with an image tag. + +1. **Build & push** app images to the registry (bake public origins into frontends at build time). +2. **Migrate** (if applicable) — copy bundle + connection file to the VM; run a one-shot container: + - Postgres on VM → `--network shared-services` + `Host=postgres` + - Postgres on Tailscale → `--network host` + `Host=100.x` +3. **Deploy** — copy `docker-compose.prod.yml` (or project equivalent), validate `.env`, set image tag, `docker compose pull && up -d`. +4. **Smoke** — hit readiness/liveness and a static UI route on `localhost` ports until healthy; dump compose ps/logs on failure. +5. **Rollback** — restore previous image tag only (DDL is usually not reverted; use expand/contract migrations). + +```bash +git tag v1.2.3 +git push origin v1.2.3 +``` + +Production compose should attach app services to external `shared-services` and map host ports for API/UI. It should **not** start shared infra (Postgres/Rabbit/Seq live elsewhere). + +--- + +## 7. Verify after first deploy + +```bash +APP=my-app +cd "/opt/${APP}" +docker compose -f docker-compose.prod.yml --env-file .env ps +curl -sS "http://localhost:${API_PORT}/health/ready" # or your readiness path +curl -sSI "http://localhost:${UI_PORT}/" | head +``` + +| Symptom | Likely cause | +|---|---| +| DB auth failure (`28P01`) / wrong database | Bad credentials, or `Host=127.0.0.1` hitting another Postgres — use `Host=postgres` on `shared-services` | +| CI: `Bind for 0.0.0.0:5432 failed: port is already allocated` | Workflow published `ports: ["5432:5432"]` on the Postgres service while the runner host already uses 5432 — drop host port publish and use `Host=postgres` (job + service share Docker DNS under act_runner) | +| CI integration test 500s / hangs talking to Gitea | Job has `GITEA_TOKEN` and a configured BaseUrl — blank `GITEA_TOKEN` and `Gitea__BaseUrl` in workflow `env:` (see §5) | +| Gitea / SSH stalls while CI tests run | Host is e2-standard-2 (2 vCPU / 8 GB). Testhost defaults to both cores — set `DOTNET_PROCESSOR_COUNT=1` on **every** `dotnet test` / eval step, not only unit tests. See [`platform/observed-state.md` Host budget](platform/observed-state.md#host-budget). | +| CD bake / registry push stalls Gitea or SSH; UI **504** | Default bake compiles every image at once; even one compile uses both cores and swap-thrashes 8 GB. One job, `cap-buildx-builder.sh` (cgroup `--cpus=1 --memory=3g`), then bake one target at a time. If already 504: GCP **Reset** (keeps ephemeral IP — never Stop/Start), then `runner-host.sh reclaim`. See [`platform/observed-state.md` Host budget](platform/observed-state.md#host-budget). | +| CD fails after green bake: `docker create` → `no command specified` | Scratch `migrate-bundle` has no `CMD`. Set `CMD ["/out/migrate-api"]` and pass `/out/migrate-api` to `docker create`. | +| CI integration `57P03` / “database system is in recovery mode” | Same host budget: uncapped testhost crashed the service Postgres. Cap testhost, give the service `--shm-size=256mb`, and wait for **queries** (`pg_isready` can pass during recovery). | +| CI unit tests OOM / hang-dump on a large EF model | Share one InMemory provider and one `InMemoryDatabaseRoot`; isolate by database name. Blank `ConnectionStrings__Postgres` on the unit-test step so InMemory tests do not hit the service DB. | +| Broker / remote dep timeout | Bridge cannot reach `100.x`, wrong IP, or home firewall — retest from a `shared-services` container | +| Smoke connection refused (`000`) | Process not listening — image entrypoint, crash loop, wrong port | +| UI OK, API readiness 503 | Fix dependency checks in the readiness payload | + +--- + +## 8. Checklist (copy per project) + +- [ ] Tailscale up on cloud VM and home peer; home `100.x` recorded +- [ ] Host `nc` to remote ports succeeds +- [ ] `shared-services` container can reach remote HTTP/AMQP deps +- [ ] `docker network create shared-services`; same-host deps attached +- [ ] `/opt//.env` from `.env.example`, `chmod 600`; local DNS for same-host, `100.x` for remote +- [ ] CI secrets: registry, deploy SSH, migrator connection (matching Postgres location) +- [ ] CI var for public API origin if UI is baked at build time +- [ ] CD copies `cap-buildx-builder.sh` and bakes one target at a time on this e2-standard-2 +- [ ] Scratch migrate-bundle has `CMD`; extract uses `docker create IMAGE /path` +- [ ] Migrator network matches Postgres location (`shared-services` vs `host`) +- [ ] Tag/deploy smoke shows readiness healthy +- [ ] Git VM external IP promoted to regional static (optional but recommended) + +--- + +## 9. Anti-patterns + +| Avoid | Why | +|---|---| +| App `network_mode: host` to “fix” Tailscale | Loses Docker DNS; same-host `postgres` breaks; `127.0.0.1` is fragile | +| MagicDNS names in container env | Unresolvable inside Docker | +| Uploading `.env` from CI every release | Secret sprawl; prefer host-owned file + tag patch only | +| URI form for tools that expect Npgsql key=value (or the reverse) | Silent parse / auth failures | +| Assuming host Tailscale routes always work from bridge | Always verify with a test container on `shared-services` | +| CI service `ports: ["5432:5432"]` + `Host=localhost` on the runner | Host bind collides with the runner host's own Postgres. Use service DNS (`Host=postgres`) with no host publish. **Valid only when the runner sets `container.network: ""`** (per-job network, DNS aliases). Under `container.network: bridge` there are no aliases and the high-port workaround is required instead — see [`platform/observed-state.md`](platform/observed-state.md) | +| Default / uncapped `buildx bake` of every image on this VM | Takes both cores; Gitea 504s. Cap buildkitd and bake one target at a time | +| GCP Stop/Start of the git VM to clear a hung bake | Releases ephemeral external IP; DNS must be redone. Use **Reset** | diff --git a/docs/CICD/infra/README.md b/docs/CICD/infra/README.md new file mode 100644 index 0000000..9f0fbdb --- /dev/null +++ b/docs/CICD/infra/README.md @@ -0,0 +1,77 @@ +# infra — shared CI, staged + +Staging area for the two repositories that hold CI once it stops being per-repo. Nothing here +is live yet: these files are reviewed in the monorepo, then pushed to their own repos on +`git.vectur45.com`. + +| Repo to create | Holds | From | +| --- | --- | --- | +| `infra/ci-workflows` | reusable pipelines (`on: workflow_call`) — `dotnet8-ci`, `node-ci`, `node-service-ci` | [`ci-workflows/`](ci-workflows/) | +| `infra/ci-actions` | composite actions (capped bake, bundle extract, compose deploy, smoke) | not written yet | + +## Why an org rather than `trent` + +`self:` references and `workflow_call` paths both embed the owner, so moving later means editing +every caller. An org is also the right home for the mirrored `ci-ubuntu` package. If you keep +`trent`, substitute it everywhere below — but decide once. + +## Creating them + +1. Create the `infra` organisation on `git.vectur45.com`. +2. Create `ci-workflows` (private is fine) and push the contents of `ci-workflows/` to it. +3. In that repo: **Settings → Actions → General → collaborative owners**, add the owners whose + private repos need to read it. Gitea 1.26+ requires this for private reusable workflows. +4. Tag it `v1`. Callers pin the tag, never a branch. + +**Currently staged for `v1.1`** (additive — `@v1` callers keep working): +`node-ci.yml` gains `post_build_command` with a documented phase order; `node-service-ci.yml` +is new. Push and tag `v1.1`, then move callers when they need the new inputs. + +## Referencing + +```yaml +jobs: + backend: + uses: infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml@v1 + with: + working_directory: GrowthOS + solution: GrowthOS.sln + test_projects: | + tests/GrowthOS.UnitTests/GrowthOS.UnitTests.csproj + tests/GrowthOS.IntegrationTests/GrowthOS.IntegrationTests.csproj + tests/GrowthOS.AgentEvals/GrowthOS.AgentEvals.csproj +``` + +Runner 4.0 also added `uses: self:{owner}/{repo}@{ref}` for **actions** on this instance. Whether +that prefix works for reusable **workflows** is unverified — use the plain `owner/repo/path@ref` +form above until it is. + +## Gitea-specific constraints these encode + +| Constraint | Why | +| --- | --- | +| `inputs:` are explicit, never `gitea.event.inputs` | Not propagated into reusable workflows as of Gitea 1.27.2 | +| One label in `runs_on` | Multi-label `runs-on: [a, b]` is documented incomplete | +| No `jobs..environment` | Ignored by Gitea — there are no approval gates | +| Artifact actions on `@v4`, both ends | v3 and v4 use different backends and do not interoperate | +| `builtin:checkout` | Runner 4.0; no Node runtime, no github.com round-trip | +| Service containers by name, never published | The runner builds a per-job network with DNS aliases | +| `DOTNET_PROCESSOR_COUNT=1` on every test step | 2 vCPU shared with Gitea; uncapped testhost crashes service Postgres | + +Source of truth for all of these: [`../platform/observed-state.md`](../platform/observed-state.md). + +## What stays in the caller + +A reusable workflow cannot accept injected steps, so anything repo-specific arrives as an input +(`pre_build_command`, `test_env`, `extra_check_command`) or stays in the caller as its own job. +GrowthOS's change-detection job is the latter: it needs `fetch-depth: 0` and a repo-specific path +map, so it remains in `.gitea/workflows/ci.yml`. + +## Next + +1. Push `ci-workflows`, tag `v1`. +2. Convert GrowthOS's `backend` and `frontend` jobs to callers; confirm green. +3. Extract the CD composite actions into `ci-actions` — the capped bake, the `docker create` / + `docker cp` bundle extract, the compose deploy, the smoke test. +4. **Onboard a second project.** That is the step that proves the inputs are sufficient; design + alone will not. diff --git a/docs/CICD/infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml b/docs/CICD/infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml new file mode 100644 index 0000000..b894e04 --- /dev/null +++ b/docs/CICD/infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml @@ -0,0 +1,207 @@ +# Reusable .NET 8 CI pipeline for this Gitea instance. +# +# Every constraint below is measured, not assumed — see the source of truth at +# CICD/platform/observed-state.md in the marketing monorepo: +# * service containers are reached BY NAME on the runner's per-job network; +# never publish 5432/6379, the runner host already uses them +# * the host is 2 vCPU / 8 GB shared with Gitea, so every `dotnet test` caps +# testhost to one core or the service Postgres crashes (57P03) +# * artifact actions are @v4 (both ends together — v3 and v4 do not interoperate) +# * `builtin:checkout` needs no Node runtime and no github.com round-trip +# +# Callers that still use Testcontainers (especially RabbitMQ) leave this workflow's +# Postgres/Redis services idle — extend this workflow with inputs rather than forking. +# RabbitMQ cannot be a workflow `services:` entry on this fleet at all; see +# node-service-ci.yml and observed-state.md. +# +# Caller: +# jobs: +# backend: +# uses: infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml@v1 +# with: +# working_directory: GrowthOS +# solution: GrowthOS.sln +# test_projects: | +# tests/Foo.UnitTests/Foo.UnitTests.csproj +# tests/Foo.IntegrationTests/Foo.IntegrationTests.csproj +name: dotnet8-ci + +on: + workflow_call: + inputs: + runs_on: + description: "Runner label. One label only — multi-label runs-on is unreliable." + type: string + default: ubuntu-latest + working_directory: + description: "Directory holding the solution, relative to the repo root." + type: string + default: "." + solution: + description: "Solution file, relative to working_directory." + type: string + required: true + dotnet_version: + type: string + default: "8.0.x" + cache_dependency_path: + description: "Glob for setup-dotnet's NuGet cache key." + type: string + default: "**/*.csproj" + postgres_image: + type: string + default: "postgres:16" + postgres_db: + type: string + default: "app_test" + redis_image: + type: string + default: "redis:7" + pre_build_command: + description: "Optional shell run at the REPO ROOT before restore (schema checks, codegen)." + type: string + default: "" + isolated_test_projects: + description: | + Test projects that must NOT see the service database — typically unit tests on an + in-memory provider. Run first, with ConnectionStrings__* blanked, because a context + factory (or a stray UseNpgsql) will otherwise connect to the live Postgres and retry + until it thrashes the runner. One .csproj path per line. + type: string + default: "" + test_projects: + description: "Test projects that DO use the service containers. One .csproj path per line." + type: string + required: true + test_env: + description: "Optional extra KEY=VALUE lines exported for every test step." + type: string + default: "" + blame_hang_timeout: + description: "Kill testhost if a test stops completing." + type: string + default: "2m" + +jobs: + build-and-test: + runs-on: ${{ inputs.runs_on }} + defaults: + run: + working-directory: ${{ inputs.working_directory }} + services: + postgres: + image: ${{ inputs.postgres_image }} + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: ${{ inputs.postgres_db }} + # --shm-size is NOT stripped by the runner (verified on Runner 4.0). + # pg_isready can pass while Postgres is still in crash recovery, so the + # start-period is generous and tests must wait for queries, not health. + options: >- + --shm-size=256mb + --health-cmd "pg_isready -U postgres -d ${{ inputs.postgres_db }}" + --health-interval 2s + --health-timeout 5s + --health-retries 30 + --health-start-period=20s + redis: + image: ${{ inputs.redis_image }} + options: >- + --health-cmd "redis-cli ping" + --health-interval 5s + --health-timeout 3s + --health-retries 10 + env: + ASPNETCORE_ENVIRONMENT: Testing + ConnectionStrings__Postgres: "Host=postgres;Port=5432;Database=${{ inputs.postgres_db }};Username=postgres;Password=postgres;SSL Mode=Disable" + ConnectionStrings__Redis: "redis:6379" + # GITEA_TOKEN is injected into every job and job containers CAN reach this + # Gitea. Product code holding the token will make live API calls from CI + # unless it is blanked. Tests are fixtures, not writes. + GITEA_TOKEN: "" + steps: + - uses: builtin:checkout + + - name: Pre-build checks + if: inputs.pre_build_command != '' + working-directory: . + run: ${{ inputs.pre_build_command }} + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: ${{ inputs.dotnet_version }} + cache: true + cache-dependency-path: ${{ inputs.working_directory }}/${{ inputs.cache_dependency_path }} + + - name: Restore + run: dotnet restore ${{ inputs.solution }} + + - name: Build + run: dotnet build ${{ inputs.solution }} -c Release --no-restore + + # Two steps, not one, because the connection strings differ. Both loop rather + # than becoming separate jobs: extra jobs queue at capacity 1 rather than + # running in parallel, and --no-build means the cost is the test run itself. + - name: Test (isolated — no service database) + if: inputs.isolated_test_projects != '' + env: + ConnectionStrings__Postgres: "" + ConnectionStrings__Redis: "" + DOTNET_PROCESSOR_COUNT: "1" + DOTNET_gcServer: "0" + DOTNET_GCHeapCount: "1" + run: | + set -euo pipefail + while IFS= read -r line; do + [ -n "$line" ] || continue + export "${line?}" + done <<< "${{ inputs.test_env }}" + + while IFS= read -r proj; do + [ -n "$proj" ] || continue + name="$(basename "$proj" .csproj)" + echo "::group::$name" + dotnet test "$proj" -c Release --no-build \ + --filter "Category!=Live" \ + --blame-hang-timeout ${{ inputs.blame_hang_timeout }} \ + --logger "trx;LogFileName=${name}.trx" \ + --results-directory ./TestResults \ + -- xUnit.MaxParallelThreads=1 + echo "::endgroup::" + done <<< "${{ inputs.isolated_test_projects }}" + + - name: Test (against the service containers) + env: + # 2 vCPU shared with Gitea. Uncapped testhost takes both cores, the + # service Postgres container dies, and later tests fail with 57P03. + DOTNET_PROCESSOR_COUNT: "1" + DOTNET_gcServer: "0" + DOTNET_GCHeapCount: "1" + run: | + set -euo pipefail + while IFS= read -r line; do + [ -n "$line" ] || continue + export "${line?}" + done <<< "${{ inputs.test_env }}" + + while IFS= read -r proj; do + [ -n "$proj" ] || continue + name="$(basename "$proj" .csproj)" + echo "::group::$name" + dotnet test "$proj" -c Release --no-build \ + --filter "Category!=Live" \ + --blame-hang-timeout ${{ inputs.blame_hang_timeout }} \ + --logger "trx;LogFileName=${name}.trx" \ + --results-directory ./TestResults \ + -- xUnit.MaxParallelThreads=1 + echo "::endgroup::" + done <<< "${{ inputs.test_projects }}" + + - name: Publish test results + if: always() + uses: actions/upload-artifact@v4 + with: + name: test-results + path: ${{ inputs.working_directory }}/TestResults diff --git a/docs/CICD/infra/ci-workflows/.gitea/workflows/node-ci.yml b/docs/CICD/infra/ci-workflows/.gitea/workflows/node-ci.yml new file mode 100644 index 0000000..0e0350a --- /dev/null +++ b/docs/CICD/infra/ci-workflows/.gitea/workflows/node-ci.yml @@ -0,0 +1,111 @@ +# Reusable Node CI pipeline — covers Vue 3, React and Nuxt front ends. +# Typecheck runs ONCE (in lint); the build step must not re-run vue-tsc/tsc. +# +# Phase order (do not reorder in callers): +# 1. lint_command — lint + typecheck (no dist) +# 2. extra_check_command — audit, unit tests, source checks (no dist) +# 3. build_command — production build only (produces dist) +# 4. post_build_command — bundle budget, e2e, anything that needs dist +# build_env is exported for Build and Post-build only. +name: node-ci + +on: + workflow_call: + inputs: + runs_on: + type: string + default: ubuntu-latest + working_directory: + description: "Directory holding package.json, relative to the repo root." + type: string + required: true + node_version: + type: string + default: "22" + package_manager: + description: "npm | pnpm" + type: string + default: npm + lock_file: + type: string + default: package-lock.json + lint_command: + type: string + default: "npm run lint" + extra_check_command: + description: "Optional checks between lint and build. Must NOT require dist/." + type: string + default: "" + build_command: + description: "Build only. Typechecking belongs in lint_command, not here." + type: string + default: "npx vite build" + build_env: + description: "Optional KEY=VALUE lines exported for Build and Post-build." + type: string + default: "" + post_build_command: + description: "Optional checks after build that may use dist/ (bundle budget, e2e)." + type: string + default: "" + artifact_path: + description: "Optional build output to upload. Empty uploads nothing." + type: string + default: "" + +jobs: + build: + runs-on: ${{ inputs.runs_on }} + defaults: + run: + working-directory: ${{ inputs.working_directory }} + steps: + - uses: builtin:checkout + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: ${{ inputs.node_version }} + cache: ${{ inputs.package_manager }} + cache-dependency-path: ${{ inputs.working_directory }}/${{ inputs.lock_file }} + + - name: Install + run: | + if [ "${{ inputs.package_manager }}" = "pnpm" ]; then + corepack enable && pnpm install --frozen-lockfile + else + npm ci + fi + + - name: Lint (and typecheck) + run: ${{ inputs.lint_command }} + + - name: Extra check + if: inputs.extra_check_command != '' + run: ${{ inputs.extra_check_command }} + + - name: Build + run: | + set -euo pipefail + while IFS= read -r line; do + [ -n "$line" ] || continue + export "${line?}" + done <<< "${{ inputs.build_env }}" + ${{ inputs.build_command }} + + - name: Post-build check + if: inputs.post_build_command != '' + run: | + set -euo pipefail + while IFS= read -r line; do + [ -n "$line" ] || continue + export "${line?}" + done <<< "${{ inputs.build_env }}" + ${{ inputs.post_build_command }} + + - name: Upload build output + if: inputs.artifact_path != '' + uses: actions/upload-artifact@v4 + with: + name: build-output + path: ${{ inputs.working_directory }}/${{ inputs.artifact_path }} diff --git a/docs/CICD/infra/ci-workflows/.gitea/workflows/node-service-ci.yml b/docs/CICD/infra/ci-workflows/.gitea/workflows/node-service-ci.yml new file mode 100644 index 0000000..9fb3dbd --- /dev/null +++ b/docs/CICD/infra/ci-workflows/.gitea/workflows/node-service-ci.yml @@ -0,0 +1,129 @@ +# Reusable Node service CI — install, migrate, test against job sidecars. +# +# Do NOT use workflow services: for RabbitMQ on this runner — the broker fails +# health before steps run. Sidecars via start-job-sidecars.sh (Docker socket). +# See CICD/platform/observed-state.md. +# +# Caller (after this file is tagged in infra/ci-workflows@v1): +# jobs: +# api-service: +# uses: infra/ci-workflows/.gitea/workflows/node-service-ci.yml@v1 +# with: +# working_directory: api-service +# migrate_command: npm run migrate +# test_command: npm test -- --runInBand --forceExit +# sidecars_script: scripts/start-job-sidecars.sh +name: node-service-ci + +on: + workflow_call: + inputs: + runs_on: + type: string + default: ubuntu-latest + working_directory: + description: "Directory holding package.json, relative to the repo root." + type: string + required: true + node_version: + # Matches node-ci.yml. Pin this explicitly in every caller — a shared + # default that moves is a silent toolchain change across projects. + type: string + default: "22" + package_manager: + type: string + default: npm + lock_file: + type: string + default: package-lock.json + install_command: + type: string + default: "" + migrate_command: + description: "Shell run after sidecars are up (working_directory)." + type: string + default: "" + test_command: + description: "Shell run after migrate (working_directory)." + type: string + default: "npm test -- --runInBand --forceExit" + sidecars_script: + description: "Path from repo root to start-job-sidecars.sh (copy from the CICD kit)." + type: string + default: "scripts/start-job-sidecars.sh" + database_url_var: + description: "Env var name for the Postgres URL written by the sidecar script." + type: string + default: DATABASE_URL + amqp_url_var: + type: string + default: AMQP_URL + redis_url_var: + type: string + default: REDIS_URL + postgres_db: + type: string + default: app_test + test_env: + description: "Optional KEY=VALUE lines exported for migrate and test." + type: string + default: "" + +jobs: + test: + runs-on: ${{ inputs.runs_on }} + steps: + - uses: builtin:checkout + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: ${{ inputs.node_version }} + cache: ${{ inputs.package_manager }} + cache-dependency-path: ${{ inputs.working_directory }}/${{ inputs.lock_file }} + + - name: Start job sidecars + env: + CI_PG_DB: ${{ inputs.postgres_db }} + CI_DATABASE_URL_VAR: ${{ inputs.database_url_var }} + CI_AMQP_URL_VAR: ${{ inputs.amqp_url_var }} + CI_REDIS_URL_VAR: ${{ inputs.redis_url_var }} + run: bash ${{ inputs.sidecars_script }} + + - name: Install + working-directory: ${{ inputs.working_directory }} + run: | + set -euo pipefail + if [ -n "${{ inputs.install_command }}" ]; then + ${{ inputs.install_command }} + elif [ "${{ inputs.package_manager }}" = "pnpm" ]; then + corepack enable && pnpm install --frozen-lockfile + else + npm ci + fi + + - name: Migrate + if: inputs.migrate_command != '' + working-directory: ${{ inputs.working_directory }} + run: | + set -euo pipefail + while IFS= read -r line; do + [ -n "$line" ] || continue + export "${line?}" + done <<< "${{ inputs.test_env }}" + ${{ inputs.migrate_command }} + + - name: Test + working-directory: ${{ inputs.working_directory }} + run: | + set -euo pipefail + while IFS= read -r line; do + [ -n "$line" ] || continue + export "${line?}" + done <<< "${{ inputs.test_env }}" + ${{ inputs.test_command }} + + - name: Stop job sidecars + if: always() + run: | + docker rm -f "${CI_PG_NAME:-}" "${CI_RMQ_NAME:-}" "${CI_REDIS_NAME:-}" 2>/dev/null || true diff --git a/docs/CICD/infra/examples/caller-dotnet-node.yml b/docs/CICD/infra/examples/caller-dotnet-node.yml new file mode 100644 index 0000000..9a642b6 --- /dev/null +++ b/docs/CICD/infra/examples/caller-dotnet-node.yml @@ -0,0 +1,44 @@ +# Generic single-product CI caller — copy into .gitea/workflows/ci.yml and rename paths. +# Requires infra/ci-workflows@v1 (collaborative owners must include this repo's owner). +name: CI + +on: + push: + branches: [main, master] + paths: + - "src/**" + - "web/**" + - "MyApp.sln" + - ".gitea/workflows/**" + pull_request: + branches: [main, master] + paths: + - "src/**" + - "web/**" + - "MyApp.sln" + - ".gitea/workflows/**" + +jobs: + backend: + uses: infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml@v1 + with: + working_directory: . + solution: MyApp.sln + postgres_db: myapp_test + isolated_test_projects: | + tests/MyApp.UnitTests/MyApp.UnitTests.csproj + test_projects: | + tests/MyApp.IntegrationTests/MyApp.IntegrationTests.csproj + test_env: | + Jwt__SigningKey=ci-test-jwt-secret-at-least-32-bytes-long!! + + frontend: + uses: infra/ci-workflows/.gitea/workflows/node-ci.yml@v1 + with: + working_directory: web + node_version: "22" + lint_command: npm run lint && npm run typecheck + extra_check_command: npm test + build_command: npx vite build + build_env: | + VITE_API_BASE_URL= diff --git a/docs/CICD/infra/examples/caller-monorepo.yml b/docs/CICD/infra/examples/caller-monorepo.yml new file mode 100644 index 0000000..708c2f5 --- /dev/null +++ b/docs/CICD/infra/examples/caller-monorepo.yml @@ -0,0 +1,112 @@ +# Generic monorepo CI caller — path map is always repo-specific; keep this job local. +# Pin @v1. Until node-service-ci is tagged live, the node-service job stays in-repo +# and uses CICD/scripts/start-job-sidecars.sh (Docker socket required). +name: CI + +on: + push: + branches: [main, master] + paths: + - "backend/**" + - "web/**" + - "api-service/**" + - ".gitea/workflows/**" + pull_request: + branches: [main, master] + paths: + - "backend/**" + - "web/**" + - "api-service/**" + - ".gitea/workflows/**" + +jobs: + # Stays local: repo-specific path map + needs fetch-depth: 0. + # Keep actions/checkout@v4 here until builtin:checkout is proven with fetch-depth: 0. + changes: + runs-on: ubuntu-latest + outputs: + backend: ${{ steps.filter.outputs.backend }} + frontend: ${{ steps.filter.outputs.frontend }} + api_service: ${{ steps.filter.outputs.api_service }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Detect changed stacks + id: filter + run: | + set -euo pipefail + if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then + BASE="origin/${GITHUB_BASE_REF}" + git fetch --no-tags --depth=1 origin "${GITHUB_BASE_REF}" 2>/dev/null \ + || git fetch --no-tags origin "${GITHUB_BASE_REF}" + RANGE="${BASE}...HEAD" + elif [ -n "${GITHUB_EVENT_BEFORE:-}" ] \ + && [ "${GITHUB_EVENT_BEFORE}" != "0000000000000000000000000000000000000000" ]; then + RANGE="${GITHUB_EVENT_BEFORE}...HEAD" + else + RANGE="HEAD~1...HEAD" + fi + changed="$(git diff --name-only ${RANGE} 2>/dev/null || git diff --name-only HEAD)" + backend=false; frontend=false; api_service=false + if echo "${changed}" | grep -qE '^\.gitea/workflows/'; then + backend=true; frontend=true; api_service=true + else + echo "${changed}" | grep -qE '^backend/' && backend=true || true + echo "${changed}" | grep -qE '^web/' && frontend=true || true + echo "${changed}" | grep -qE '^api-service/' && api_service=true || true + fi + { + echo "backend=${backend}" + echo "frontend=${frontend}" + echo "api_service=${api_service}" + } >> "$GITHUB_OUTPUT" + + backend: + needs: changes + if: needs.changes.outputs.backend == 'true' + uses: infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml@v1 + with: + working_directory: backend + solution: MyApp.sln + postgres_db: myapp_test + test_projects: | + tests/MyApp.IntegrationTests/MyApp.IntegrationTests.csproj + + frontend: + needs: changes + if: needs.changes.outputs.frontend == 'true' + uses: infra/ci-workflows/.gitea/workflows/node-ci.yml@v1 + with: + working_directory: web + node_version: "22" + lint_command: npm run lint && npm run typecheck + build_command: npx vite build + + # Prefer uses: infra/ci-workflows/.../node-service-ci.yml@v1 once tagged. + # Until then: local job + start-job-sidecars.sh (do NOT use RabbitMQ as services:). + api-service: + needs: changes + if: needs.changes.outputs.api_service == 'true' + runs-on: ubuntu-latest + steps: + - uses: builtin:checkout + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: "20" + cache: npm + cache-dependency-path: api-service/package-lock.json + - name: Start sidecars + run: bash CICD/scripts/start-job-sidecars.sh + # Or: bash CICD/scripts/start-job-sidecars.sh if you copied the kit to ./CICD + - name: Install / migrate / test + working-directory: api-service + run: | + npm ci + npm run migrate + npm test -- --runInBand --forceExit + - name: Stop sidecars + if: always() + run: | + docker rm -f "${CI_PG_NAME:-}" "${CI_RMQ_NAME:-}" "${CI_REDIS_NAME:-}" 2>/dev/null || true diff --git a/docs/CICD/infra/examples/growthos-ci-caller.yml b/docs/CICD/infra/examples/growthos-ci-caller.yml new file mode 100644 index 0000000..acc3100 --- /dev/null +++ b/docs/CICD/infra/examples/growthos-ci-caller.yml @@ -0,0 +1,83 @@ +# What .gitea/workflows/ci.yml becomes once infra/ci-workflows exists and is tagged v1. +# STAGED — do not copy into .gitea/workflows/ until that repo is pushed and tagged, +# or every run fails to resolve the `uses:` reference. +# +# 241 lines -> ~75. What stays here is what a reusable workflow cannot take: +# the change-detection job needs fetch-depth: 0 and a repo-specific path map. +name: CI + +on: + push: + branches: [main, master] + paths: + - "GrowthOS/**" + - ".gitea/workflows/**" + pull_request: + branches: [master, main] + paths: + - "GrowthOS/**" + - ".gitea/workflows/**" + +jobs: + # Stays local: repo-specific path map, and it needs full history to diff against + # the merge base. Keep actions/checkout@v4 here unless the probe proves + # builtin:checkout honours fetch-depth: 0 — a silently shallow clone would make + # this filter skip real work while the run stays green. + changes: + runs-on: ubuntu-latest + outputs: + backend: ${{ steps.filter.outputs.backend }} + frontend: ${{ steps.filter.outputs.frontend }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Detect changed stacks + id: filter + run: | + # ... unchanged from the current ci.yml ... + echo "see .gitea/workflows/ci.yml for the body" + + backend: + needs: changes + if: needs.changes.outputs.backend == 'true' + uses: infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml@v1 + with: + working_directory: GrowthOS + solution: GrowthOS.sln + postgres_db: growth_os_test + # Unit tests are InMemory. They must not see the service Postgres, or + # AppDbContextFactory connects to it and retries until the runner thrashes. + isolated_test_projects: | + tests/GrowthOS.UnitTests/GrowthOS.UnitTests.csproj + test_projects: | + tests/GrowthOS.IntegrationTests/GrowthOS.IntegrationTests.csproj + tests/GrowthOS.AgentEvals/GrowthOS.AgentEvals.csproj + test_env: | + Jwt__SigningKey=ci-test-jwt-secret-at-least-32-bytes-long!! + Gitea__DryRun=true + Gitea__BaseUrl= + Gitea__Token= + pre_build_command: | + set -euo pipefail + venv=/tmp/growth-seed + if ! python3 -m venv "$venv"; then + (sudo apt-get update -qq && sudo apt-get install -y -qq python3-venv) \ + || (apt-get update -qq && apt-get install -y -qq python3-venv) + python3 -m venv "$venv" + fi + "$venv/bin/pip" install --quiet --disable-pip-version-check pyyaml + "$venv/bin/python" GrowthOS/scripts/sync-growth-memory-seed.py --check + + frontend: + needs: changes + if: needs.changes.outputs.frontend == 'true' + uses: infra/ci-workflows/.gitea/workflows/node-ci.yml@v1 + with: + working_directory: GrowthOS/web + node_version: "22" + lint_command: npm run lint + extra_check_command: node scripts/check-prod-routing.mjs + build_command: npx vite build + build_env: | + VITE_API_BASE_URL= diff --git a/docs/CICD/onboarding-a-project.md b/docs/CICD/onboarding-a-project.md new file mode 100644 index 0000000..ddeb8db --- /dev/null +++ b/docs/CICD/onboarding-a-project.md @@ -0,0 +1,191 @@ +# Putting a project on this CI/CD + +How to give another repository CI and CD on `git.vectur45.com`. Assumes the platform is already +set up — you are adding a project, not a runner. + +Read [`platform/observed-state.md`](platform/observed-state.md) if anything here surprises you; +it is the source of truth and this document is downstream of it. + +--- + +## 0. Before you start + +| You need | Where | +| --- | --- | +| A repo on `git.vectur45.com` | | +| Read access to `infra/ci-workflows` | its Settings → Actions → General → **collaborative owners** must list your repo's owner | +| A deploy host with Docker + Compose | for CD only | +| A PAT with `write:package` | for CD only — `GITEA_TOKEN` **cannot** push to the container registry | + +There is **one runner** (`gcp-runner-01`, label `ubuntu-latest`) on a 2 vCPU / 8 GB box shared with +Gitea and the demo stacks. Jobs run **one at a time**. Budget wall clock accordingly: an extra job +is queued, not parallel. + +--- + +## 1. Does your project fit the shared pipelines? + +| Stack | Reusable workflow | Status | +| --- | --- | --- | +| .NET 8 service with Postgres/Redis | `dotnet8-ci.yml` | ✅ in use | +| Vue 3 / React / Nuxt front end | `node-ci.yml` | ✅ in use | +| Node service with Postgres/RabbitMQ/Redis | `node-service-ci.yml` | ✅ sidecars, not `services:` | +| Python, React Native, something else | — | not written yet; see §6 | + +If it fits, you write a **caller**: a `ci.yml` that declares `uses:` and passes inputs. You do not +copy pipeline steps. If you find yourself copying steps, that is a signal the workflow needs an +input, not that you need a fork. + +--- + +## 2. CI — write the caller + +`.gitea/workflows/ci.yml` in your repo: + +```yaml +name: CI + +on: + push: + branches: [main, master] + paths: ["src/**", ".gitea/workflows/**"] + pull_request: + branches: [main, master] + paths: ["src/**", ".gitea/workflows/**"] + +jobs: + backend: + uses: infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml@v1 + with: + working_directory: . # dir holding the .sln + solution: MyApp.sln + postgres_db: myapp_test + # Tests that must NOT see the service database — in-memory unit tests. + # Leaving the connection strings set lets a context factory reach the live + # Postgres and retry until it thrashes the runner. + isolated_test_projects: | + tests/MyApp.UnitTests/MyApp.UnitTests.csproj + test_projects: | + tests/MyApp.IntegrationTests/MyApp.IntegrationTests.csproj + test_env: | + Jwt__SigningKey=ci-test-jwt-secret-at-least-32-bytes-long!! +``` + +Front end, in the same file or its own job: + +```yaml + frontend: + uses: infra/ci-workflows/.gitea/workflows/node-ci.yml@v1 + with: + working_directory: web + node_version: "22" + lint_command: npm run lint # typecheck belongs HERE, once + build_command: npx vite build # the build must not re-run vue-tsc/tsc +``` + +**Pin `@v1`.** Never a branch — otherwise every project's CI changes the moment someone edits the +shared repo. + +**Monorepo?** Add a `changes` job that sets outputs from a path diff and gate the callers on it +(`if: needs.changes.outputs.backend == 'true'`). That job stays in your repo: the path map is +repo-specific and it needs `fetch-depth: 0`. See [`../.gitea/workflows/ci.yml`](../.gitea/workflows/ci.yml). + +--- + +## 3. CD + +CD is **not** extracted into a reusable workflow yet, because deployment shape varies more than +CI. Copy [`templates/workflows/cd.yml`](templates/workflows/cd.yml) and +[`templates/docker-bake.hcl`](templates/docker-bake.hcl), then fill the placeholders +(``, ``) — the templates carry no product names, so nothing has to be +grepped out afterwards. See [`templates/README.md`](templates/README.md) for the copy-to table. + +Four things it must keep, all learned the hard way — each links to the reason: + +| Keep | Why | +| --- | --- | +| `cap-buildx-builder.sh` before the bake, and **one bake target at a time** | A default parallel bake takes both cores and returns Gitea **504**. `BUILDKIT_STEP_MAX_PARALLELISM=1` alone is not enough. | +| Migrate as its own job, downloading an artifact — never a second `docker build` | Bind mounts resolve on the Docker **host**, not the job workspace | +| Scratch `migrate-bundle` with `CMD` **and** `docker create IMAGE /out/migrate-api` | `FROM scratch` has no default command; bare `docker create` fails with `no command specified` | +| Expand-then-contract migrations | Migrate runs while the previous release still serves traffic. Rollback restores the image tag, **not** the schema. | + +**Secrets** (repo → Settings → Actions → Secrets): `REGISTRY_USERNAME`, `REGISTRY_TOKEN` (the PAT), +`DEPLOY_HOST`, `DEPLOY_USER`, `DEPLOY_SSH_KEY`, plus a migration connection string if you migrate. +**Variables:** `REGISTRY`, and any public origin baked into a UI image at build time. + +Connection strings must be Npgsql `key=value` form (`Host=…;Port=…;Username=…;Password=…`), never +URI form, with no wrapping quotes — see [`hybrid-gcp-tailscale-cicd.md`](hybrid-gcp-tailscale-cicd.md). + +--- + +## 4. Deploy host + +Covered in [`hybrid-gcp-tailscale-cicd.md`](hybrid-gcp-tailscale-cicd.md). In short: `/opt//` +with a `docker-compose.prod.yml` and a host-owned `.env` (`chmod 600`) that CD patches only for +the image tag. Same-host dependencies join the external `shared-services` network and are reached +by Docker DNS; remote ones over Tailscale by `100.x` address, never MagicDNS. + +Copy [`templates/docker-compose.prod.yml`](templates/docker-compose.prod.yml) and +[`templates/.env.example`](templates/.env.example). + +--- + +## 5. Verify before you call it done + +- [ ] CI is green, and the run shows `uses:` resolving — not a copied pipeline +- [ ] For .NET: the **isolated** test step ran **before** the service-backed one +- [ ] A change touching only the front end does **not** start Postgres +- [ ] Second CI run on an unchanged lockfile shows a **cache hit** in restore/install +- [ ] CD on a tag: bake → migrate → deploy → smoke, and **Gitea stayed up** during the bake +- [ ] Rollback path tested once, deliberately +- [ ] No published database ports anywhere in CI +- [ ] `upload-artifact` / `download-artifact` both `@v4` — they do not interoperate with v3 + +--- + +## 6. When the shared workflow does not fit + +In order of preference: + +1. **Add an input** to the shared workflow, tag `v1.x`, update your caller. Callers on `@v1` are + unaffected until they move. +2. **Use the escape hatches already there** — `pre_build_command`, `test_env`, + `extra_check_command` — for genuinely repo-specific steps. A reusable workflow cannot accept + injected steps, which is why these exist. +3. **Write a new pipeline** in `infra/ci-workflows` for a genuinely different stack (Python, + React Native). Model it on `dotnet8-ci.yml`: same job names, same artifact names, same + host-budget caps. +4. **Fork the steps into your repo** — last resort, and record why in the repo's README, because + it will not receive fixes made to the shared one. + +Breaking changes get a new major tag (`v2`). Projects migrate when they choose. Additive changes +get a minor (`v1.1`) and existing `@v1` callers keep working. + +**Do not fork this directory.** Three project kits were created as copies of `CICD/` in +2026-09-30 and had diverged within days — one of them made a script strictly worse by replacing +an enumerated builder cleanup with a hardcoded name. A project keeps its **caller**, its `cd.yml`, +its compose/env files, and a link back here. The pipelines live in `infra/ci-workflows` and the +platform facts live in [`platform/observed-state.md`](platform/observed-state.md), which describes +one runner on one VM — copies of it will disagree, and its whole value is being the one file you +can trust. + +--- + +## 7. Gitea-specific things that will surprise you + +| Expectation | Reality here | +| --- | --- | +| `jobs..environment` gates a deploy | **Ignored.** No approval gates — use tag patterns. | +| `runs-on: [label-a, label-b]` | Documented incomplete. **One label.** | +| `gitea.event.inputs` reaches a reusable workflow | It does not (1.27.x). Pass explicit `inputs:`. | +| `GITEA_TOKEN` can push a package | It cannot. PAT required. | +| Tests cannot reach Gitea | They can. `GITEA_TOKEN` is injected into every job — blank it if product code would make live API calls. | +| A broker works as a `services:` entry like Postgres does | **RabbitMQ does not.** It fails health before any step runs and no step-level fix is reachable. Use `scripts/start-job-sidecars.sh`, or `node-service-ci.yml` which wraps it. | +| `actions/*` comes from your instance | It comes from **github.com** by default. `builtin:checkout` avoids that entirely. | +| A second CI job runs in parallel | It queues. `capacity: 1`. | + +--- + +**Source of truth:** [`platform/observed-state.md`](platform/observed-state.md) · +**How it got this way:** [`platform/change-log.md`](platform/change-log.md) · +**Build speed:** [`ci-cd-build-cache.md`](ci-cd-build-cache.md) diff --git a/docs/CICD/platform/change-log.md b/docs/CICD/platform/change-log.md new file mode 100644 index 0000000..5b1d952 --- /dev/null +++ b/docs/CICD/platform/change-log.md @@ -0,0 +1,128 @@ +# Platform change log + +What changed on this CI/CD platform, why, and what evidence justified it. +[`observed-state.md`](observed-state.md) says what is true **now**; this file says how it got +there, so a decision can be re-opened without re-deriving it. + +Period covered: **2026-09-27 → 2026-09-30**. + +--- + +## Initial state (as found, 2026-09-27) + +| Area | State | +| --- | --- | +| Gitea | 1.27.1, image `docker.gitea.com/gitea:latest` — unpinned | +| Runner | `gitea/act_runner:latest` → v0.6.1. **Deprecated and frozen since 2026-04-30**; `:latest` could never advance past it because the project had been renamed to `gitea/runner`. No security fixes. | +| Runner config | Four lines: `container.network: bridge` and one `--add-host`. Everything else defaults, nothing in version control. | +| Toolchain image | `ghcr.io/catthehacker/ubuntu:act-latest` — a third-party **moving tag** on a public registry, re-pulled on every job (`force_pull: true`). ~2m37s on a cold pull. | +| Labels | From `GITEA_RUNNER_LABELS` in compose, not reviewable | +| Cache | `actions/cache` enabled, but `cache.dir` defaulted to a path **inside the container** — discarded on every recreate | +| Capacity | 1, never measured against the host | +| Host | GCP `e2-standard-2` (2 vCPU / 8 GB), shared with Gitea and ~15 application containers. **Unrecorded anywhere.** | +| CI | Postgres/Redis published on host ports `54329`/`63799` plus a 40-line host-discovery step; `upload-artifact@v3`; `actions/checkout@v4` | +| CD | Artifact actions `@v3` both ends | +| Docs | Two playbooks giving **contradictory** rules for CI service networking. Neither named the variable that decided it. The same act_runner assumptions were re-derived in four places. | + +## Current state (2026-09-30) + +| Area | State | +| --- | --- | +| Gitea | 1.27.1, pinned | +| Runner | **`gitea/runner:4.0.0`** — four majors forward, registration preserved | +| Runner config | [`config/runner.yaml`](config/runner.yaml), version-controlled and mirrored from the VM | +| Toolchain image | Mirrored to `git.vectur45.com/trent/ci-ubuntu`, **digest-pinned**, package public, `force_pull: false`. Set up job: **5–22s**. | +| Cache | `dir: /data/cache` on the runner volume, `offline_mode: true`, survives restarts and upgrades | +| Guards | `health_check` pauses fetching below 10 GB free; `metrics` on loopback | +| Host | Measured under CI **and** CD load and recorded, with a capacity rule derived from it | +| CI | Service containers **by name** on a per-job network; artifacts `@v4`; `builtin:checkout`; testhost capped to one core on every test step | +| CD | Same, plus a cgroup-capped BuildKit builder and one bake target at a time | +| Pipelines | Extracted to `infra/ci-workflows@v1`. GrowthOS's `ci.yml`: **267 → 145 lines** | +| Docs | [`observed-state.md`](observed-state.md) is the single source of truth; both playbooks corrected and cross-linked to it; [`probe.yml`](../../.gitea/workflows/probe.yml) is a standing regression check | + +--- + +## What changed, in order + +| Date | Change | Why / evidence | +| --- | --- | --- | +| 09-27 | Measured the platform into `observed-state.md` | Nothing recorded the Gitea version, runner version, runner config or host. Four documents were guessing. | +| 09-28 | `container.network: bridge` → `""` | `bridge` gives no Docker DNS aliases. Probe confirmed `postgres`/`redis` resolve on a per-job network. | +| 09-28 | Removed published DB ports + 40-line host discovery from `ci.yml` | Made obsolete by the above. −53 lines. | +| 09-28 | `cache.dir` → `/data/cache` | The default lived inside the container and was lost on every recreate. | +| 09-28 | Labels moved from env into `config.yaml` | Reviewable, and a prerequisite for runner 2.0+, which removed env-var config overrides. | +| 09-28 | `shutdown_timeout: 3m` + compose `stop_grace_period` | Default `0s` cancelled in-flight jobs on restart. | +| 09-28 | `metrics.enabled: true` | The build-cache playbook opens with "measure first" and had no source of numbers. | +| 09-28 | Testhost capped (`DOTNET_PROCESSOR_COUNT=1`) on **every** test step | Uncapped testhost took both cores, crashed the service Postgres, and later tests failed `57P03`. Unit 13m31s abort → 4m34s green. | +| 09-29 | CD bake capped (`cap-buildx-builder.sh`, one target at a time) | Default parallel bake froze the VM and returned Gitea 504. | +| 09-29 | Both images pinned; `gitea/act_runner` documented as retired | Gitea cannot be downgraded after a migration; the runner tag was a dead end. | +| 09-29 | Toolchain mirrored, digest-pinned, `force_pull: false` | Removed a third-party moving tag and a per-job ghcr.io round-trip. Set up job 2m37s → 12s. | +| 09-29 | Runner → `gitea/runner:4.0.0` | The 0.6.x line is deprecated and frozen; it holds the Docker socket and the deploy key. Probe green afterwards. | +| 09-29 | `health_check`, `tool_cache_mode: shared`, `cache.offline_mode`, `default_image` | All impossible on 0.6.1. | +| 09-29 | Artifact actions → `@v4`, both ends in one commit | Round trip verified first: v3 and v4 use different backends and do not interoperate. | +| 09-29 | `builtin:checkout` in CI, then CD | No Node runtime, no github.com round-trip. `changes` stays on `actions/checkout@v4` pending a `fetch-depth` result. | +| 09-30 | Pipelines extracted to `infra/ci-workflows@v1` | First change that pays off per project rather than per repo. | + +--- + +## 2026-09-30 — three projects onboarded, improvements folded back + +`CICD/` was copied into three project kits (`fleet_telemetry`, `pos`, `inline_inspection`) while +onboarding those repos. What came back: + +| Taken | From | Why | +| --- | --- | --- | +| RabbitMQ cannot be a workflow `services:` entry; `start-job-sidecars.sh` + `node-service-ci.yml` | pos | A **measurement that contradicted a generalization in these docs**. "Service containers by name" holds for Postgres/Redis and fails for RabbitMQ — health fails before any step runs. | +| `runner-host.sh` enumerates docker-container builders instead of naming them | pos | The hardcoded list went stale on every onboarding. `inline_inspection` changed it the other way, to one hardcoded name — a regression, not taken. | +| `node-ci.yml` gains `post_build_command` and a documented phase order | fleet_telemetry | There was nowhere to put a check that needs `dist/` (bundle budget, e2e); `extra_check_command` runs before the build. | +| `templates/` replaces `.gitea_example/` + the two loose `*_example` files | fleet_telemetry | `.gitea_example/` had `fleet-telemetry` baked into 10+ places — registry namespace, builder name, bundle name, `/tmp` paths, compose project name. Anyone copying it inherited another product's identity. | +| Testcontainers note on `dotnet8-ci.yml` | fleet_telemetry | Names the exact point where someone would otherwise fork the workflow. | +| Generic monorepo and dotnet+node caller examples | pos | The only example was GrowthOS-specific. | + +**Not taken:** path rewrites local to each kit (`docs/CICD/…`, "in this kit"); inline's hardcoded +builder name. **Reconciled:** `node-service-ci.yml` defaulted Node 20 against `node-ci.yml`'s 22 — +now 22 in both, with a note telling callers to pin it explicitly. + +### The result worth recording + +**`dotnet8-ci.yml` diverged across all three kits only in comments and example values.** Not one +needed a new input to build and test a .NET service. That is the validation the extraction was +waiting for. `node-ci.yml` needed exactly one new input. + +### The failure mode it also demonstrated + +Four copies of `dotnet8-ci.yml`, `runner.yaml`, `observed-state.md` and the scripts existed +simultaneously and had already diverged — one making a script worse. That is the duplication the +shared repo exists to end, reintroduced one directory up. `onboarding-a-project.md` §6 now says +a project keeps its caller, `cd.yml` and templates, and links back here for everything else. + +--- + +## Conclusions that were wrong, and what corrected them + +Kept deliberately. Each of these was stated with confidence and then disproved by a measurement; +the pattern is the reason `observed-state.md` exists. + +| Claim | Reality | Corrected by | +| --- | --- | --- | +| "Service DNS already works, `bridge` was innocent" | It was not. The probe had been run **after** the config change. `bridge` really was the cause. | Reading the job's network name against the change timeline | +| "Disk hygiene is the urgent risk" | 239 GB free, 19 % used. **Memory** was the constraint — 1.9 GB available, no swap. | `df` + `docker system df` | +| "A backend CI job needs 3–4 GB" | 832 MiB peak. | `docker stats` under load | +| "Cap job containers with `container.options: --memory=3g`" | Silently ignored on 0.6.1 — `HostConfig.Memory: 0`. act's parser supports a subset of `docker run` flags. | `docker inspect` on a job container | +| "`--shm-size` may be stripped by runner 3.0" | Not stripped. The strip list covers container-**escaping** flags only. | Probe, `ShmSize=268435456` | +| "Only `always()` is supported" (Gitea docs) | `failure()`, `success()` and `cancelled()` all behave like GitHub Actions, on 0.6.1 **and** 4.0.0. | Probe `expressions` job | +| "`upload-artifact@v4` is broken on Gitea" | True on 0.6.1; works on 4.0.0 with `patch_actions` + `cache.v2`. | Probe, then a production CD round trip | +| "CD bake regressed from 14m29s to 26m1s" | Not a regression — bake time is a function of registry cache state. A warm bake is **1m9s**; a cold one ~26 min. | A later warm run | + +--- + +## Open + +| Item | Status | +| --- | --- | +| CI slower through the reusable workflow (Setup .NET 2m51s, Restore 1m10s, Build 9m59s) | ⬜ Re-run on an unchanged tree. Candidates: host contention, a cold NuGet cache from a changed key, or `tool_cache_mode: shared` — which has risen monotonically since it was enabled. | +| `builtin:checkout` with `fetch-depth: 0` | ⬜ `probe.yml` job `builtin-checkout-depth` answers it; decides whether the `changes` job can migrate | +| Runner image digest pin | ⬜ `docker image inspect docker.io/gitea/runner:4.0.0 -f '{{index .RepoDigests 0}}'` | +| Monthly toolchain re-mirror | ⬜ needs an owner; a pinned base receives no upstream fixes | +| Swapfile, memory alerting, `gitea-data` backup + **restore test** | ⬜ see [observed-state §7](observed-state.md#7-host-raw-measurements) | +| Second project onboarded | ⬜ the only real test of whether the shared workflows generalize | diff --git a/docs/CICD/platform/config/runner.yaml b/docs/CICD/platform/config/runner.yaml new file mode 100644 index 0000000..5be9e0f --- /dev/null +++ b/docs/CICD/platform/config/runner.yaml @@ -0,0 +1,72 @@ +# gcp-runner-01 — Gitea Runner 4.0.0 (upgraded from act_runner 0.6.1 on 2026-09-29) +# +# Only non-default values. Full schema: `gitea-runner config init`. +# No hot-reload: `docker compose restart runner` after any edit. +# Host is e2-standard-2 (2 vCPU / 8 GB) shared with Gitea and ~15 app containers — +# see ../observed-state.md#host-budget before raising anything here. + +log: + level: info + +runner: + # 2 vCPU / 8 GB shared with Gitea. Measured: one backend job costs ~1 GB of + # availability, leaving ~900 MB. Two would land near zero. Do not raise. + capacity: 1 + + # Let an in-flight job drain on restart instead of being cancelled (default 0s). + # compose stop_grace_period must exceed this. + shutdown_timeout: 3m + + # The label IS the toolchain image. Mirrored from ghcr.io/catthehacker/ubuntu:act-latest + # on 2026-09-29 and digest-pinned; the package is public so the runner pulls anonymously + # (runner 2.0 removed implicit pull credentials). Toolchain log: ../observed-state.md. + labels: + - "ubuntu-latest:docker://git.vectur45.com/trent/ci-ubuntu:act-2026-09-29@sha256:62d572b92f9f32d3427b6d220ad1f9dca9c7b6ffad37d295425037dbff78abaf" + + # A job whose runs-on matches no label above would otherwise pull + # docker.gitea.com/runner-images:ubuntu-latest from an external registry. + default_image: "git.vectur45.com/trent/ci-ubuntu:act-2026-09-29" + + # One RUNNER_TOOL_CACHE across jobs, so setup-dotnet / setup-node stop re-installing + # the same SDK every run. Documented safe ONLY at capacity 1. + tool_cache_mode: shared + +cache: + enabled: true + # Default is $HOME/.cache/actcache INSIDE the container, discarded on every recreate. + # On the runner-data volume it survives restarts and image pins. + dir: /data/cache + # Reuse a cached copy of an action instead of fetching it from github.com on every job. + # Trade-off: a moved tag stays at the cached commit until the entry expires. + offline_mode: true + +container: + # Per-job network with DNS aliases, so `Host=postgres` / `redis:6379` resolve. + # Under `bridge` there are no aliases — that is what the old high-port workaround + # in ci.yml existed for. + network: "" + + # Still wanted for anything genuinely published on the host. + # `--memory=3g` was silently ignored on 0.6.1 (HostConfig.Memory: 0). 4.x says + # runner-level options keep working where a workflow's are stripped — retest before + # trusting it, and re-check ExtraHosts after any edit, since one unparsed flag can + # invalidate the whole string. + options: >- + --add-host=host.docker.internal:host-gateway + + privileged: false + valid_volumes: [] + # 4.x default is already false, and a digest-pinned image is never re-pulled anyway. + # Kept explicit so the intent survives a future label change. + force_pull: false + +# Pauses task fetching (running jobs continue) when free space drops below the floor. +# Also bounds cache eviction. Impossible on 0.6.1. +health_check: + enabled: true + min_free_disk_space_mb: 10240 + +metrics: + # /metrics, /healthz and /readyz — loopback only, no authentication. + enabled: true + addr: "127.0.0.1:9101" diff --git a/docs/CICD/platform/observed-state.md b/docs/CICD/platform/observed-state.md new file mode 100644 index 0000000..5b2cd62 --- /dev/null +++ b/docs/CICD/platform/observed-state.md @@ -0,0 +1,633 @@ +# Observed platform state + +What this Gitea instance and runner **actually** do, measured — not what the docs describe. +Every standard in `CICD/` is written against this file. Re-measure after any Gitea or runner +upgrade, because several rows are version-gated. + +- **Measured:** 2026-09-27 (host size 2026-09-28; GrowthOS CI 2026-09-28; GrowthOS CD bake 2026-09-29) +- **Instance:** `git.vectur45.com` · **Runner:** `gcp-runner-01` (single, GCP VM) +- **Host:** GCP **e2-standard-2** — **2 vCPU / 8 GB**. Gitea, the runner, host Postgres/Redis, and every job share this box. +- **Refresh:** see [How to re-measure](#how-to-re-measure) + +--- + +## Host budget + +This is the constraint every job and `runner.capacity` decision is written against. It is not +a GitHub-hosted 4-core runner. + +| Fact | Value | +| --- | --- | +| Machine type | `e2-standard-2` | +| vCPU | **2** | +| Memory | **8 GB** | +| Colocated | Gitea, `act_runner` (`network_mode: host` + Docker socket), host Postgres/Redis on `5432`/`6379`, the job container, CI service containers | + +Consequences: + +- **`runner.capacity` stays 1.** Two concurrent .NET jobs, each with Postgres + Redis services, will starve Gitea or OOM. Do not treat capacity as a one-line speed-up on this VM. +- **Testhost defaults to every core.** `Environment.ProcessorCount` is 2 — the whole machine. **Every** test/eval step (`dotnet test`, not only unit tests) must set `DOTNET_PROCESSOR_COUNT=1` with workstation GC (`DOTNET_gcServer=0`, `DOTNET_GCHeapCount=1`) so Gitea and the service Postgres keep a vCPU. Uncapped integration testhost crashed the service container mid-run; later tests then failed with `57P03` (database system is in recovery mode). `pg_isready` can pass during that recovery — wait until queries work (`PostgresStartup.WaitUntilAcceptingQueriesAsync`), do not treat the healthcheck as sufficient. +- **CD bake is the same budget.** Default `docker buildx bake` compiles api + worker + web + migrate in parallel inside one job and starves Gitea (UI **504**, SSH dead). Keep **one** bake job (do not split into three Gitea jobs). `BUILDKIT_STEP_MAX_PARALLELISM=1` only serializes steps — a single `dotnet publish` still uses both cores and will swap-thrash 8 GB. CD must (1) `docker update --cpus=1 --memory=3g --memory-swap=3g` on the buildkitd container (`CICD/scripts/cap-buildx-builder.sh`) and (2) bake **one target at a time** so push cannot overlap the next compile. SDK stages keep `DOTNET_PROCESSOR_COUNT=1`. Web stages keep a small Node heap (`NODE_OPTIONS=--max-old-space-size=512`, `UV_THREADPOOL_SIZE=1`). +- **8 GB is the ceiling, not headroom.** A new EF InMemory internal service provider per database name recompiles the full `AppDbContext` model and will OOM. Share **one** provider **and** one `InMemoryDatabaseRoot` for the assembly; isolate tests with unique database **names**. `InMemoryDatabaseRoot` is a singleton option under `UseInternalServiceProvider` — a new root per test throws. Testcontainers *plus* CI service Postgres is a second database the host cannot afford. +- **Scratch `migrate-bundle` needs a command.** `FROM scratch` with only `COPY` has no `CMD`. Bare `docker create IMAGE` fails with `no command specified` after a green bake. Set `CMD ["/out/migrate-api"]` on the stage **and** pass `/out/migrate-api` to `docker create`. + +### If Gitea returns 504 during CD + +The Actions UI cannot cancel the job. SSH will not recover in time. + +Do **not** Stop/Start. An ephemeral external IP is released on Stop and DNS for `git.vectur45.com` (and SSH) would have to be redone. **Reset** is a hard reboot: the instance stays RUNNING and **keeps the ephemeral IP**. + +1. Prefer serial console if it still accepts a login: `docker stop $(docker ps -qf name=buildx_buildkit)` then `./CICD/scripts/runner-host.sh reclaim` from SSH. That is enough when only BuildKit is wedged. +2. If the guest is frozen (serial console too): GCP Console → the git VM → **Reset** (or `gcloud compute instances reset NAME --zone=ZONE`). Never Stop. +3. After boot, if Gitea is still slow: from a machine that can SSH, `./CICD/scripts/runner-host.sh reclaim ` (stops leftover `buildx_buildkit` / `GITEA-ACTIONS` containers). +4. In Gitea, cancel the CD run if it is still listed. +5. Do not re-run CD until that ref's `cd.yml` calls `cap-buildx-builder.sh` and bakes one target at a time. + +After Gitea is up, promote the current ephemeral IP to a regional static address (same number) so a future Stop cannot change DNS. + +### Measured CI — GrowthOS backend, 2026-09-28 (green) + +After the testhost cap on **all** test steps, shared InMemory provider/root, and `Host=postgres` (no published ports). Same `e2-standard-2`. + +| Step | This run | Before | +| --- | --- | --- | +| Setup .NET 8 | 1m8s | — | +| Restore (`setup-dotnet cache: true` hit) | 2m7s | cold NuGet, folded into compile | +| Build (`dotnet build --no-restore`) | **10m12s** | **20–30 min** (swap + cold restore) | +| Unit tests (`--no-build`, 370 passed) | **4m34s** | **13m31s abort** (20 fails, hang dump) | +| Integration tests (`--no-build`) | **6m0s** green | ~6.5 min with five `57P03` failures | +| Agent evals (`--no-build`) | 24s | — | + +Build is still the long pole on two cores with a large EF model. Test time is no longer the thing that makes the job look stuck. Re-record these after a runner or VM change. + +### Measured CI + CD — 2026-09-30, first run through `infra/ci-workflows@v1` + +Structurally faithful — isolated unit tests ran before the service-backed ones, artifacts +uploaded, CD green with `builtin:checkout`. **But CI got slower and the cause is not established.** + +| CI step | Via reusable (#67) | Local (2026-09-29) | 2026-09-28 | +| --- | --- | --- | --- | +| Set up job | 22s | — | — | +| `builtin:checkout` | 31s | 14s | — | +| Pre-build checks (seed manifests) | 42s | 18s | 22s | +| **Setup .NET** | **2m51s** ⚠️ | 1m25s | 56s | +| **Restore** | **1m10s** ⚠️ | 18s | 2m21s | +| **Build** | **9m59s** ⚠️ | 5m33s | 8m10s | +| Test — isolated (unit, 370) | 1m26s | 2m19s | 3m41s | +| Test — service-backed (integration + evals) | 3m2s | 3m4s combined | — | +| **backend total** | **20m31s** | — | — | +| frontend | 2m8s | ~2m18s | — | +| changes | 32s | — | — | + +| CD step (#68) | Via `builtin:checkout` | Previous | +| --- | --- | --- | +| Bake and push images | 1m29s | 1m9s | +| Upload migration bundle | 29s | 15s | +| build-and-push / migrate / deploy | 2m21s / 1m8s / 1m18s | — | + +**Open: why is CI slower?** Three candidates, in order of likelihood: + +1. **Host contention.** 2 vCPU shared with ~15 app containers. Single samples on this box vary, + and Build has ranged 5m33s–10m12s across runs with no pipeline change. +2. **A changed NuGet cache key.** `setup-dotnet` now receives + `cache-dependency-path: GrowthOS/**/*.csproj` composed from inputs. If the resulting key + differs from the one the local workflow used, the first run through the reusable workflow was + a cold restore — which fits Restore 18s → 1m10s exactly, and would resolve itself on the + next run. +3. **`tool_cache_mode: shared`.** Setup .NET has risen monotonically (56s → 1m25s → 2m51s) across + the runs since it was enabled. That trend is the one that would not fix itself. + +Decisive check: the `Setup .NET` and `Restore` logs for `Cache restored from key` vs +`Cache not found`. Then re-run CI on an unchanged tree — if it returns to ~18s / ~5m30s it was +(1) or (2); if it stays slow, suspect (3) and set `tool_cache_mode: none`. + +### Measured CI + CD — 2026-09-29, after Runner 4.0 + artifacts@v4 + builtin:checkout + +Same `e2-standard-2`. Changes since run #59: Runner 4.0.0, `tool_cache_mode: shared`, +`cache.offline_mode: true`, artifact actions on `@v4`, `builtin:checkout` in CI. + +| CI step | Now | #59 | 2026-09-28 | +| --- | --- | --- | --- | +| `builtin:checkout` | **14s** | 8s (`actions/checkout@v4`) | — | +| Seed manifests | 18s | 22s | — | +| Setup .NET 8 | **1m25s** ⚠️ | 56s | 1m8s | +| **Restore** | **18s** | 2m21s | 2m7s | +| **Build** | **5m33s** | 8m10s | 10m12s | +| Unit tests (370) | **2m19s** | 3m41s | 4m34s | +| Integration tests (47) | **2m37s** | 2m56s | 6m0s | +| Agent evals (12) | 27s | 37s | 24s | +| frontend job (full) | ~2m18s | skipped | — | + +| CD step | Now | #60 | 2026-09-29 (first capped) | +| --- | --- | --- | --- | +| **Bake and push images** | **1m9s** | 26m1s | 14m29s | +| Upload migration bundle (`@v4`) | 15s | 38s | 46s | +| Download migration bundle (`@v4`) | 9s | — | — | +| Apply migrations | 30s | — | — | + +Reads: + +- **The CD #60 anomaly is answered.** A 1m9s bake on an unchanged source tree is a warm registry + cache doing its job; 26m1s was a cold one. The bake time is a function of cache state, not a + regression — but it also means a cold bake costs ~26 min, and that is the number to plan around + after any builder prune or `runner-host.sh reclaim`. +- **Restore 2m21s → 18s** is the largest single CI win; `cache.offline_mode` plus a warm NuGet cache. +- **The artifact v4 round trip works in production**, not just in the probe: `cd.yml` uploads the + EF bundle in `build-and-push` and `migrate` downloads it, 15s / 9s. +- **`builtin:checkout` works in real jobs** — 14s backend, 12s frontend, no Node, no github.com. +- ⚠️ **`Setup .NET 8` went 56s → 1m25s** despite `tool_cache_mode: shared`. Either the shared tool + cache had to be populated on this first post-upgrade run, or it is not helping here. ⬜ Re-check + on the next run before crediting or discarding it. + +### Measured CI — GrowthOS backend, 2026-09-29, run #59 (after the toolchain pin) + +Same `e2-standard-2`. Only change against 2026-09-28 is the mirrored, digest-pinned label image +with `force_pull: false` — plus whatever test work landed in between, so attribute cautiously. + +| Step | Run #59 | 2026-09-28 | Note | +| --- | --- | --- | --- | +| **Set up job** | **12s** | ~2m37s on a cold ghcr.io pull | **The toolchain pin.** Local registry + `force_pull: false`; this is the one delta attributable to that change alone. | +| Checkout | 8s | — | | +| Seed manifests | 22s | — | | +| Setup .NET 8 | 56s | 1m8s | | +| Restore (cache hit) | 2m21s | 2m7s | noise | +| Build | **8m10s** | 10m12s | still the long pole on 2 cores | +| Unit tests | **3m41s** | 4m34s | | +| Integration tests | **2m56s** | 6m0s | | +| Agent evals | 37s | 24s | | +| Publish results | 5s | — | | +| Complete job (post steps / cache save) | 2m31s | — | | +| **backend job total** | **22m0s** | — | `changes` 22s · `frontend` skipped by path filter (1s) | + +Single runs, not averages. The `Set up job` figure is the clean measurement; the test-step +improvements overlap with the testhost-cap work and should not be credited to the toolchain pin. + +### Measured CD — GrowthOS tag deploy, 2026-09-29 (green) + +After `cap-buildx-builder.sh` (`--cpus=1.0 --memory=3g`), one bake target at a time, SDK/Node caps, and scratch `migrate-bundle` `CMD` + `docker create … /out/migrate-api`. Gitea stayed up (no 504). Same `e2-standard-2`. + +| Job / step | This run | Before | +| --- | --- | --- | +| **build-and-push** (total) | **15m48s** | VM frozen / Gitea 504 under default bake | +| Bake and push images | **14m29s** | same failure mode | +| Upload migration bundle | 46s | — | +| **migrate** | **1m32s** | — | +| **deploy** (incl. smoke) | **1m12s** | — | + +First-run `cache-from …:buildcache: not found` is expected and non-fatal; the api bake still wrote `mode=max` cache, and migrate reused it (`inferred cache manifest`). Wall clock is longer than an uncapped parallel bake would be on a bigger machine; the point is Gitea survives. Re-record after a second tag (registry cache warm) or a VM resize. + +--- + +## 1. Versions + +| Fact | Value | Source | +| --- | --- | --- | +| Gitea | **1.27.1** | operator-reported; confirm with `curl -s https://git.vectur45.com/api/v1/version` | +| Runner | **4.0.0** (`gitea-runner`) — upgraded from `act_runner` v0.6.1 on 2026-09-29 | Admin → Actions → Runners | +| Gitea image | `docker.gitea.com/gitea:latest` — ⬜ digest TODO | compose | +| Runner image | `docker.io/gitea/runner:4.0.0` — ⬜ digest TODO | compose | +| Runner name | `gcp-runner-01` | `GITEA_RUNNER_NAME` | +| Labels registered | `ubuntu-latest:docker://git.vectur45.com/trent/ci-ubuntu:act-2026-09-29@sha256:62d572b92f9f…` | `runner.labels` in `platform/config/runner.yaml` | + +### `:latest` here is worse than usual + +Three separate problems, all from the same two tags: + +1. **`gitea/act_runner` is a retired image name.** The project renamed to `gitea/runner` at v1.0.0 + and has since shipped **2.0, 3.0 and 4.0** — v4.0.0 released 2026-09-24. So `act_runner:latest` + will never advance past the 0.6.x line: `:latest` is giving a *false sense of currency* while + pinning by abandonment. This runner is **four majors behind**, and closing that gap means + changing the image **name**, not pulling. Docker Hub now describes `gitea/act_runner` as + *"Deprecated Gitea runner. Moved to gitea/runner"*, and its last image push was + **2026-04-30** — so this runner receives no fixes, security or otherwise, while holding the + host Docker socket and the deploy SSH key. Adoption (checked 2026-09-27): `gitea/act_runner` + 10.15M cumulative pulls vs `gitea/runner` 1.09M in its first ~5 months — the larger number is + accumulated history and existing installs re-pulling `:latest`, not current practice. +2. **`gitea:latest` is a live moving tag.** Gitea applies DB migrations on startup and **does not + support downgrade**, so one `docker compose pull` is a one-way door. +3. ~~The label image is a moving third-party tag re-pulled on every job~~ — **resolved 2026-09-29.** + Mirrored into `git.vectur45.com/trent/ci-ubuntu`, digest-pinned, `force_pull: false`. The + external dependency and the per-job ghcr.io round-trip are gone. **This now needs an owner:** + a pinned base receives no upstream fixes until someone re-mirrors it. Monthly is enough at this + scale ([dock-senior-001](../../docs/Reference/senior/docker/docker.json) — the deliverable is + being able to rebuild within hours of a critical CVE). + +Fix all three by name: `docker.gitea.com/gitea:1.27.1@sha256:…`, `gitea/runner:v4.0.x@sha256:…` +(a deliberate migration), and mirror the label image into `git.vectur45.com` digest-pinned with +`force_pull: false`. Back up `gitea-data` + the DB before the first Gitea bump. +See [dock-junior-012](../../docs/Reference/junior/docker/docker.json), +[dock-senior-018](../../docs/Reference/senior/docker/docker.json), +[dock-senior-006](../../docs/Reference/senior/docker/docker.json) (mirror third-party images). + +Gitea **1.27.3** exists; this instance is two patches behind on the same minor. + +--- + +## 2. Version-gated capabilities (resolved from the versions above) + +| Capability | Available here? | Note | +| --- | --- | --- | +| **Scoped workflows** (`.gitea/scoped_workflows`, org/instance level) | ✅ **Yes** | Landed in Gitea **1.27.0**. Unblocks the enforced-invariants layer. | +| **Reusable workflows** (`on: workflow_call`) | ✅ Yes | | +| Actions / reusable workflows from **private** repos | ✅ Yes | Gitea 1.26+. Needs Settings → Actions → General → collaborative owners. | +| `gitea.event.inputs` propagated into a reusable workflow | ❌ **No** | Open upstream at 1.27.2, so it applies here. Pass everything via explicit `inputs:`. | +| `runner.github_mirror` | ✅ Yes (v0.6.1) | Redirects `uses:` lookups without rewriting YAML or mirroring repos. | +| `act_runner cache-server` (shared cache across runners) | ✅ Yes | v0.6.1 has `cache.external_server` + `cache.external_secret`. | +| `upload-artifact@v4` | ✅ **works on 4.0** | Verified 2026-09-29, `outcome = success`. Was blocked by the GHES support check on 0.6.1; `patch_actions` + `cache.v2` + `ACTIONS_RESULTS_URL` on the cache server changed that. | +| `download-artifact@v4` — the **round trip** | ✅ **works on 4.0** | Verified 2026-09-29: upload in one job, `needs:`, download in another, payload intact. v3 and v4 do not interoperate, so both ends moved in one commit — `ci.yml`, `cd.yml` and the templates. | +| `uses: builtin:checkout` | ✅ **works on 4.0** | Verified 2026-09-29, 11s, correct HEAD. No Node runtime and no github.com round-trip. ⬜ Unknown whether it supports `fetch-depth: 0`, which the `changes` job in `ci.yml` needs — adopt per job, not globally. | +| `jobs..environment` (approval gates) | ❌ Ignored | No manual gate; encode promotion in tag patterns. | +| `runs-on: [a, b]` multi-label matching | ⚠️ Avoid | Documented incomplete; unverified on v0.6.1. One label per job. | +| Digest reference in a label (`…:tag@sha256:…`) | ✅ Yes | Verified 2026-09-29 — v0.6.1 passes the full reference through to the pull. | +| Anonymous pull of a public Gitea package by the runner | ✅ Yes | Verified — runner pulls with `username=` empty. Runner v2.0 changes implicit credentials, so keeping the package **public** is what makes this survive the v4 upgrade. | +| `GITEA_TOKEN` → container registry push | ❌ No | PAT required (`REGISTRY_USERNAME` / `REGISTRY_TOKEN`). | +| `GITEA_TOKEN` injected into every job | ✅ Yes | Job token, not a product PAT. Job containers can reach `git.vectur45.com` (public URL). An app that binds `GITEA_TOKEN` / `Gitea__*` will call this instance unless the workflow blanks those vars. | +| Expressions beyond `always()` | ⬜ TODO — probe | Docs say only `always()`. Rollback in `cd.yml` depends on `failure()`. | + +--- + +## 3. Live runner config + +**As found (2026-09-27)** the mounted `config.yaml` was four lines, everything else a v0.6.1 +default, and labels came from `GITEA_RUNNER_LABELS` in compose: + +```yaml +container: + network: bridge + options: >- + --add-host=host.docker.internal:host-gateway +``` + +**As applied (2026-09-28)** — see `config/runner.yaml`. Changed: `container.network` to `""`, +`cache.dir` to `/data/cache`, labels moved into the file, `shutdown_timeout: 3m`, +`metrics.enabled: true`, `force_pull` made explicit. The table below is the applied state; the +probe results in §5 were measured **after** this was live. + +| Key | Value here | Source | Consequence | +| --- | --- | --- | --- | +| `container.network` | **`""`** (was `bridge`) | explicit | Empty makes the runner build a network per job. **Confirmed working 2026-09-28:** the job landed on `GITEA-ACTIONS-TASK-…-services-network`, and `postgres` / `redis` both resolved *and* accepted TCP by name. Under the previous `bridge` there are no DNS aliases, which is what the high-port + `resolve_host` workaround existed to route around. **That workaround is gone** — `.gitea/workflows/ci.yml` uses `Host=postgres` / `redis:6379` with no published host ports. See [§5](#5-probe-results). | +| `container.options` | `--add-host=host.docker.internal:host-gateway` | explicit | Kept. It was the other half of the `bridge` workaround; still wanted for anything genuinely published on the host. **`--memory=3g` does NOT work here**: added 2026-09-29, the job container came back with `HostConfig.Memory: 0`. act's option parser supports only a subset of `docker run` flags on this version (not the documented escape-flag stripping, which is a v3.0 behaviour and does not list `--memory`). Reverted. A single unparsed flag can invalidate the whole string, so re-check `ExtraHosts` after any change here. Retest on v4 — the parser has been extended since (4.0 added `--umask`). | +| `runner.capacity` | `1` (default) | default | Jobs **serialise**. `changes → backend → frontend` wall clock is the sum. **Do not raise on this host** — see [Host budget](#host-budget). Capacity > 1 wants a bigger VM or a second runner. | +| `runner.labels` | `ubuntu-latest:docker://git.vectur45.com/trent/ci-ubuntu:act-2026-09-29@sha256:62d572b92f9f…` | **config.yaml** (moved off `GITEA_RUNNER_LABELS` 2026-09-28) | **Mirrored 2026-09-29** from `ghcr.io/catthehacker/ubuntu:act-latest`, digest-pinned, package public so the runner pulls anonymously. Full digest in the toolchain log below. | +| `container.force_pull` | **`false`** | explicit | Correct now that the label is an immutable self-hosted reference. Probe confirms `forcePull=false` with a green job. | +| `cache.enabled` | `true` (default) | default | `actions/cache` server runs. `setup-dotnet cache:` and `setup-node cache: npm` **hit** (probe §5). | +| `cache.host` / `port` | `""` / `0` (default) | default | Measured: resolves to `http://10.140.0.2:34585/` (VM internal IP, **random** port) and **is reachable** from job containers. The port changes on every runner restart, so pin `cache.port` before anything firewalls the path between job networks and the host. | +| `cache.external_server` | `""` | default | No shared cache. Fine at one runner; prerequisite for runner #2. | +| `container.privileged` | `false` (default) | default | Measured: workflow-supplied `options` are **not** stripped on v0.6.1 — `--shm-size=256mb` reached the service container with `Privileged=false`. | +| `container.valid_volumes` | `[]` (default) | default | Jobs may mount **no** volumes. | +| `container.docker_host` | `""` (auto) | default | Host socket is mounted → the daemon is shared with jobs. | +| `container.bind_workdir` | `false` (default) | default | Not needed (no DinD). | +| `runner.github_mirror` | `''` (default) | default | `uses: actions/checkout@v4` is fetched from github.com on every run. | +| `metrics.enabled` | **`true`** | explicit | `/metrics` and `/healthz` on `127.0.0.1:9101`. | +| `runner.timeout` | `3h` (default) | default | | + +### Trust posture + +The runner has the **host Docker socket** *and* `network_mode: host` — root on the VM plus the +host's network namespace — and at job time it holds `DEPLOY_SSH_KEY` and the registry PAT. That +is acceptable only because every repo it serves is private and trusted; it is not acceptable for +any repo taking outside pull requests. +See [dock-mid-020](../../docs/Reference/mid/docker/docker.json). + +--- + +### Toolchain image log + +The label image is the toolchain every job runs in. Append a row on each re-mirror; never delete +one — an old digest is the only record of what a past release was built with. + +| Mirrored | Reference | Digest | Source | +| --- | --- | --- | --- | +| 2026-09-29 | `git.vectur45.com/trent/ci-ubuntu:act-2026-09-29` | `sha256:62d572b92f9f32d3427b6d220ad1f9dca9c7b6ffad37d295425037dbff78abaf` | `ghcr.io/catthehacker/ubuntu:act-latest` | + +Recover any past toolchain exactly: `docker pull git.vectur45.com/trent/ci-ubuntu@`. + +--- + +## 4. Runner version — the v4 upgrade + +Upgraded 2026-09-29: `gitea/act_runner:0.6.1` → `gitea/runner:4.0.0`, four majors in one hop. +The `.runner` registration survived, so no re-registration; rollback is changing the tag back. +Probe, CI and CD all green afterwards. + +### Now configured, and impossible before + +| Setting | Value | What it does | +| --- | --- | --- | +| `health_check.enabled` / `min_free_disk_space_mb` | `true` / `10240` | Pauses **task fetching** (running jobs continue) below the floor. Closes the §7 disk gap that 0.6.1 could not. Also bounds cache eviction. | +| `runner.tool_cache_mode` | `shared` | One `RUNNER_TOOL_CACHE` across jobs, so `setup-dotnet` / `setup-node` stop re-installing the same SDK. Documented safe **only at capacity 1** — which is us. | +| `cache.offline_mode` | `true` | Reuse a cached action instead of re-fetching from github.com every job. | +| `runner.default_image` | the mirrored `ci-ubuntu` | A job whose `runs-on` matches no label would otherwise pull from an external registry. | +| `metrics` | `/readyz` added | Task-admission readiness, alongside `/metrics` and `/healthz`. | + +### Available, deliberately not configured + +- **`post_task_script`** — the 4.0 docs are explicit that the runner **stops task heartbeats and + appears offline to Gitea while it runs**. A `docker buildx prune` there is not fast enough. Not + needed anyway: `workdir_cleanup_age: 24h` + `idle_cleanup_interval: 10m` are **on by default** + and remove orphaned per-job networks and volumes — the 137 unused volumes in §7, fixed without + configuration. +- **`hooks.job_started` / `job_completed`** — run inside the job; either failing fails the job. +- **`log.job`** (dir / retention / max_size) — keeps a copy of each task log on disk. Costs disk; + left off. +- **`cache.s3`**, **`cache.external_server`** — for a second runner. Caches are per-runner today. + +### What v4.x adds that changes the standardization plan + +| v4.x feature | Replaces in the plan | +| --- | --- | +| `builtin:checkout` — native checkout, no Node runtime in the job image | The github.com dependency for `actions/checkout@v4`, and the need for Node in every golden CI image | +| `uses: self:{owner}/{repo}@{ref}` | Absolute-URL references to a shared actions repo, and flipping `DEFAULT_ACTIONS_URL=self` | +| `cache.s3` (S3 / MinIO) | `act_runner cache-server` + `external_secret` as the shared-cache mechanism for runner #2 | +| OpenTelemetry job traces (`OTEL_*`) | Hand-read timestamps as the source for build-time measurement | + +### Breaking changes crossed (audit list — all resolved at the 2026-09-29 upgrade) + +| Major | Change | Applies here? | +| --- | --- | --- | +| 2.0 | **Env-var overrides for config disabled** | ⚠️ **Yes** — `GITEA_RUNNER_LABELS` would stop configuring labels. Moving labels into `config.yaml` is a prerequisite. | +| 2.0 | `container.force_pull` defaults to **`false`** | ⚠️ Yes — a moving label tag would silently go stale. Digest-pinning becomes mandatory, not optional. | +| 2.0 | Docker credentials no longer implicit for all pulls | ⚠️ Yes, once the label image is mirrored into the private Gitea registry — it will need configured creds. | +| 3.0 | Container-escaping `options` stripped (`--pid`, `--ipc`, `--uts`, …) | Probably not — `--shm-size` is not an escape option, so the Postgres service flag should survive. Verify. | +| 3.0 | Cache service **v2** on by default | Re-test which `actions/cache` major works after upgrading. | +| 3.0 | One process per registration file | No — single runner. | +| 4.0 | Jobs send cache requests **to the runner**, which forwards them | Verify reachability; set `cache.host`/`cache.port` if the per-job network cannot reach the runner. | +| 4.0 | `valid_volumes` matches with doublestar (`/data/**`, not `/data/*`) | No — `valid_volumes: []`. | +| all | **The `.runner` registration file stays valid across versions** | No re-registration needed; rollback is changing the image tag back. | + +--- + +## 5. Probe results + +### Run 2026-09-29 — Gitea Runner **4.0.0** (post-upgrade). Everything survived four majors. + +| Probe | Expected | Observed | Note | +| --- | --- | --- | --- | +| `always()` fires | ran | ✅ ran | | +| `failure()` fires | ran | ✅ ran | `cd.yml` rollback still valid after 3.0 | +| `success()` skipped after failure | skipped | ✅ skipped | | +| `cancelled()` skipped | skipped | ✅ skipped | | +| `--shm-size=256mb` on a service container | `268435456` | ✅ **`268435456`**, `/dev/shm` 256M, `Privileged=false` | 3.0's option stripping does **not** touch `--shm-size` | +| `postgres` / `redis` resolve | yes | ✅ both | per-job `…-services-network` unchanged | +| TCP to `postgres:5432` / `redis:6379` by name | connects | ✅ both | | +| `ACTIONS_CACHE_URL` | set | `http://10.140.0.2:43447/` | | +| **`ACTIONS_RESULTS_URL`** | — | **`http://10.140.0.2:43447`** | **Changed.** On 0.6.1 this was the Gitea instance; on 4.0 it is the runner's own cache server — this is `cache.v2`, under which artifact uploads also go through the cache server. | +| Cache endpoint reachable | HTTP, not 000 | ✅ HTTP 404 | 4.0 routes job cache through the runner; no `cache.host`/`port` needed with `network_mode: host` | +| `actions/cache@v3` round-trip | HIT on 2nd run | ✅ **HIT** — restored a stamp from **2026-09-27** | the entry outlived the `cache.dir` move **and** the v4 upgrade | +| Cache step duration | — | **1s** (was 24s on 0.6.1) | | +| `Set up job` | — | **5s / 13s** (was ~2m37s cold on ghcr.io) | mirrored + digest-pinned toolchain | + +Nothing regressed, so no rule in `CICD/` changes as a result of the upgrade. The one new fact is +`ACTIONS_RESULTS_URL` pointing at the cache server — which is why `upload-artifact@v4` is now +worth retesting (see §2). + +### Run 1: 2026-09-28 — act_runner v0.6.1 (superseded, kept for comparison) + +Run 1: 2026-09-28, Gitea 1.27.1 / act_runner v0.6.1, **after** applying the new `config.yaml` +(`container.network: ""`, `cache.dir: /data/cache`). + +| Probe | Expected if healthy | Observed | Note | +| --- | --- | --- | --- | +| `always()` fires | ran | ✅ **ran** | | +| `failure()` fires | ran | ✅ **ran** | | +| `success()` skipped after failure | not ran | ✅ **skipped** | | +| `cancelled()` skipped | not ran | ✅ **skipped** | | +| job-level `if: always()` with a failed `needs` | job runs | ✅ **ran** | `needs-context` executed | +| `needs..result` populated | `failure` | ✅ **`'failure'`** | | +| `ACTIONS_CACHE_URL` set | non-empty | ✅ `http://10.140.0.2:34585/` | `ACTIONS_RESULTS_URL` = the Gitea instance | +| cache endpoint reachable from job container | HTTP, not `000` | ✅ **HTTP 404** | 404 on `/` is the cache server answering — it is reachable | +| `actions/cache@v3` round-trip, run 1 | miss | ✅ `Cache not found for input keys` | | +| `actions/cache@v3` round-trip, run 2 | restored from key | ✅ **HIT** (operator-confirmed) | run 2 total 1m36s vs 3m16s for the cache job alone on run 1 | +| service `--shm-size=256mb` honoured | `ShmSize=268435456` | ✅ **`268435456`**, `/dev/shm` 256M | not stripped; `Privileged=false` | +| `getent hosts postgres` / `redis` | resolves | ✅ **both resolve** | | +| TCP to `postgres:5432` / `redis:6379` by name | connects | ✅ **both reachable** | | +| Job network | per-job, not the default bridge | `GITEA-ACTIONS-TASK-…-JOB-services-…-services-network` | what `container.network: ""` produces | + +### Conclusion: the network change works — the `ci.yml` workaround is gone + +With `container.network: ""` the runner builds a network per job, attaches the job container to +it, and registers each service under its name. Measured: `postgres` and `redis` both resolved and +both accepted TCP connections by name. + +Consequences (applied 2026-09-28): + +- The invariant in [`ci-cd-build-cache.md` §8](../ci-cd-build-cache.md) is **service DNS, no + published host ports**, gated on `container.network: ""`. The old high-port + host-discovery + rule described `container.network: bridge` and is retired. The [hybrid playbook + anti-pattern row](../hybrid-gcp-tailscale-cicd.md) names `container.network` as the variable. +- `.gitea/workflows/ci.yml` uses `Host=postgres` and `redis:6379`. Do not reintroduce + `ports: 54329:5432` / host-discovery. +- Copy the same shape into [`CICD/templates/workflows/ci.yml`](../templates/workflows/ci.yml). + +`pg_isready` is not “Postgres is ready for tests.” Crash recovery (`57P03`) accepts TCP while +queries still fail. Service `--shm-size=256mb` + `--health-start-period` plus an application-level +wait-for-queries (and a testhost cap so the container does not crash mid-run) are the trio that +kept integration green. See [Host budget](#host-budget). + +### Conclusion: RabbitMQ must not be a workflow `services:` entry (2026-09-30) + +"Service containers are reached by name" holds for **Postgres and Redis and not for RabbitMQ**. +Measured on Runner 4.0.0 / e2-standard-2 while onboarding a Node service: declaring `rabbitmq` +under `jobs.*.services` fails the service health check **before any step runs**: + +```text +the service 'rabbitmq' is unhealthy: +Failed to connect and authenticate to rabbit@… in 60000 ms +``` + +A fixed hostname, `RABBITMQ_NODENAME`, plain alpine (no management UI), a longer +`--health-start-period` and `--shm-size` all failed to clear it. The job never starts, so no +step-level workaround is reachable. + +**Working pattern:** start brokers with `docker run` on the job container's own Docker network — +[`scripts/start-job-sidecars.sh`](../scripts/start-job-sidecars.sh) — with unique container +names, a fixed RabbitMQ hostname/nodename, connecting by **container IP** where the network is +the default `bridge` (no embedded DNS), an AMQP probe from the job before tests, and cleanup +under `if: always()`. Requires the Docker socket on the runner, which this runner has. + +Wrapped for reuse as +[`infra/ci-workflows/.../node-service-ci.yml`](../infra/ci-workflows/.gitea/workflows/node-service-ci.yml). + +Also seen: Gitea logs `'runs-on' key not defined in CI/` for reusable callers that omit a +local `runs-on`. Expected noise, not a service failure. + +### Conclusion: the expression set behaves like GitHub Actions + +`docs.gitea.com/usage/actions/comparison` states *"For expressions, only `always()` is supported."* +**That is not true of Gitea 1.27.1 with act_runner v0.6.1.** Measured: `always()` and `failure()` +both fired after a failed step, `success()` and `cancelled()` were both correctly skipped, and a +job with `if: always()` ran despite a failed `needs`. + +Consequences: + +- The `Roll back on failure` step in `.gitea/workflows/cd.yml` (`if: failure()`) **works as + written**. No redesign needed — this removes a planned work item. +- `if: failure()` is *not* on the enforced-invariants list after all. Keep the ban on + `jobs..environment`; the `upload-artifact@v4` ban retired on 2026-09-29 (Runner 4.0), and + the expression ban never applied here. +- Re-measure this after the v4 runner upgrade; it is runner behaviour, not a documented guarantee, + and the docs disclaim it. + +--- + +## 6. Platform compose stack + +Single GCP **e2-standard-2** (2 vCPU / 8 GB). Gitea publishes `8181:3000` and `2222:22`; TLS for +`git.vectur45.com` terminates in something outside this stack. The runner is `network_mode: host` +and reaches Gitea via the public URL, so runner→Gitea job fetching hairpins out through DNS and +the reverse proxy. A job that uses both vCPUs makes Gitea stall. + +Gaps against [arch-040](../../docs/Reference/architecture/walkthroughs.json) (running a real +product on one Docker host): + +| Gap | Effect | Reference | +| --- | --- | --- | +| No `logging:` options on either service | Default `json-file` has **no rotation**; a full `/var/lib/docker` takes down Gitea, the runner and every job at once | [dock-mid-014](../../docs/Reference/mid/docker/docker.json), arch-040 step 6 | +| No `healthcheck:` on either service | `depends_on` orders starts only; nothing detects a wedged Gitea | [dock-junior-018](../../docs/Reference/junior/docker/docker.json), [dock-junior-023](../../docs/Reference/junior/docker/docker.json) | +| No resource limits | A runaway build or uncapped testhost takes both vCPUs; Gitea stalls on the same VM | | +| No scheduled `docker image prune` / `builder prune` | Build cache and per-job images grow without bound; v0.6.1 has no `health_check` to pause fetching on low disk | arch-040 step 6 | +| No documented backup or **restore test** for `gitea-data` + DB | Gitea cannot be downgraded; the repo host is the one thing with no rebuild path | [dock-mid-016](../../docs/Reference/mid/docker/docker.json), [dock-senior-015](../../docs/Reference/senior/docker/docker.json) | +| Both images on `:latest` | See §1 | [dock-junior-012](../../docs/Reference/junior/docker/docker.json) | + +--- + +## 7. Host — raw measurements + +The **rules** derived from this host live in [Host budget](#host-budget) at the top of this file; +the documents in `CICD/` link there. This section holds the readings those rules are built on, so +they can be re-taken and compared rather than re-argued. + +Measured 2026-09-29. **One VM runs everything**: Gitea, the runner, every job container, every +build — and, on the evidence of 73 running containers, the live demo stacks as well. + +| Fact | Value | Note | +| --- | --- | --- | +| Machine type | **e2-standard-2** | 2 vCPU, 8 GB. Full-core, *not* shared-core — no burstable throttling to chase. | +| vCPU | **2** | | +| RAM | 7.8 Gi total · 4.6 Gi used · **1.9 Gi available** · **swap 0** | The binding constraint. | +| Disk | 291 G, 53 G used, **239 G free (19 %)** | `/var/lib/docker` is on `/`. Not a risk today. | +| Images | 73 (68 active) · 14.45 GB · 3.54 GB reclaimable | | +| Containers | **73, all running** | Gitea + runner is 2 of them. The rest is other workload on the same box. | +| Local volumes | 161 (**24 active**) · 17.39 GB · 5.09 GB reclaimable | 137 unused. **Do not blanket-prune** — see below. | +| Build cache | 0 B | Misleading: CD builds on a `docker-container` buildx builder, whose cache lives in a *volume*, not the daemon's build cache. It is inside the 17.39 GB above. | + +### How the capacity number was derived + +`floor(vCPU / 2)` = **1** and `floor((RAM_GB − 2) / 4)` = **1**. Both agree, neither is close, so +`runner.capacity: 1` is not a judgement call. The rule and its consequences are in +[Host budget](#host-budget); a second concurrent .NET job is an OOM risk against the workload +already on the box ([dock-mid-009](../../docs/Reference/mid/docker/docker.json), exit 137). + +### Memory, not disk, is the constraint — measured under load + +Disk was the assumed risk and the numbers disprove it: 239 GB free. RAM is the ceiling. + +Measured during CI run #1276 (`backend` job, .NET restore/build/test with Postgres + Redis +service containers): + +| | | +| --- | --- | +| Job container peak RSS | **832 MiB** (not the 3–4 GB assumed) | +| Job container CPU | 20–30 % of 200 % — **not** CPU-saturated | +| Host available memory, minimum | **919 MB** | +| OOM kills | none | +| Co-tenants | ~15 app containers, 138–250 MiB each, most already capped at 1–2 GB | + +**Verdict: the VM holds CI today, with roughly 900 MB of headroom and no swap.** + +It also confirms the capacity number quantitatively: one job costs ~1 GB of availability +(1.9 GB → 919 MB). A second concurrent job would land near zero and the OOM killer would pick a +victim — and CI job containers have **no memory limit**, while the demo containers do, so the +kernel's choice is not guaranteed to be the build. See the `--memory` finding in §3: capping the +job container is **not available** on v0.6.1. + +Measured during CD run #1280 (`build-and-push`, `buildx bake` of three images + the EF bundle): + +| | | +| --- | --- | +| CD job container | 160 MiB — the job only orchestrates | +| `buildx_buildkit_growth-os-builder0` | peak **656 MiB**, already capped at **3 GiB**, CPU up to 47 % | +| Host available, minimum | **942 MB** transient (single sample, between readings of 1799 and 1779 MB); otherwise > 1250 MB | +| OOM kills | none | + +**CD is lighter on memory than CI.** The heaviest single thing this box runs is the `backend` CI +job at 832 MiB, not the bake — because the build happens inside the BuildKit container, which is +already limited to 3 GiB. Both pipelines fit with ~900 MB–1.2 GB of headroom. + +⬜ Still unmeasured: the `frontend` job (npm + vite). + +### Structural note: this box both builds and serves + +`growth_os_api`, `growth_os_worker` and ~13 other application containers run on the same VM as the +runner and BuildKit. [arch-040](../../docs/Reference/architecture/walkthroughs.json) step 1 is +explicit that *"the server never builds"* — building on the serving box couples deploys to build +failures, competes for CPU with users, and puts source and build credentials on a host that should +hold neither. Measured impact today is tolerable (BuildKit peaked at 47 % of 200 %, nothing was +OOM-killed), so this is a **ceiling, not an incident**: it is what will bind first when a second +project's CI arrives, or when `capacity` needs to rise. A dedicated runner VM resolves it together +with the blast-radius problem above. + +### Pruning, specifically + +| Command | Verdict | +| --- | --- | +| `docker image prune -f` | ✅ safe, ~3.5 GB | +| `docker buildx prune --builder growth-os-builder --filter until=168h` | ✅ this is the one that reaches the CD build cache. `docker builder prune` alone touches the default builder and does nothing here. | +| `docker volume prune` | ❌ **do not run.** 137 unused volumes, and this box holds application data. This is exactly [dock-junior-025](../../docs/Reference/junior/docker/docker.json) — "`--volumes` deletes your databases". Inspect and remove individually if space is ever needed. | + +### Blast radius + +The runner holds the **host Docker socket** (root on this VM) and `network_mode: host`, and at job +time it holds `DEPLOY_SSH_KEY` and the registry PAT — on the same machine as Gitea and ~71 other +running containers. Any CI job, and any compromise of a co-tenant, reaches all of it. Acceptable +only while every repo served is private and trusted +([dock-mid-020](../../docs/Reference/mid/docker/docker.json)). A dedicated runner VM fixes the +contention and the blast radius in one move. + +### Host hygiene + +| Gap | Status | +| --- | --- | +| Scheduled `docker image prune` + `docker buildx prune --builder …` | ⬜ none — low urgency at 19 % disk | +| Log rotation on the Gitea + runner containers | ⬜ see §6 | +| Memory alerting | ⬜ none — **this is the one that matters here** | +| Swapfile (absorbs a build spike instead of OOM-killing a container) | ⬜ none — 0 B swap | +| Memory cap on CI job containers | ❌ **not possible on v0.6.1** — `--memory` is silently ignored by act's option parser (see §3). Retest after the v4 upgrade. Swap is the mitigation that does not depend on a parser. | +| Backup + **restore test** for `gitea-data` and the DB | ⬜ none | + +--- + +## How to re-measure + +1. Host — GCP machine type (`e2-standard-2` today). Re-check if the VM is resized; every + capacity / testhost-cap rule depends on it. +2. Versions — `curl -s https://git.vectur45.com/api/v1/version`; Admin → Actions → Runners. +3. Digests — `docker inspect` the container for `.Image`, then `docker image inspect` that id for + `.RepoDigests` (containers carry no digest field). +4. Config — `cat` the mounted `config.yaml`, and diff against + `act_runner generate-config` run from the **running image** to see which defaults apply. +5. Labels — `runner.labels` in `platform/config/runner.yaml` (not `GITEA_RUNNER_LABELS`). + Confirm in the admin UI. +6. Probes — re-run `probe.yml`. +7. Green backend job — record step timestamps in [Host budget](#host-budget) (build, unit, + integration). A testhost or InMemory change that “fixes tests” can still move compile time. +8. Green CD tag — record bake / migrate / deploy timestamps in [Host budget](#host-budget). + Confirm Gitea stays responsive during bake and that `docker create` of the scratch + migrate-bundle succeeds. + +Re-measure on: any Gitea minor bump, any runner image change, any `config.yaml` or compose edit +(the runner does not hot-reload — it needs a restart), or a VM resize (machine type is the +host budget). + +--- + +**Reference behind these rows:** [dock-junior-012](../../docs/Reference/junior/docker/docker.json) +(`:latest`), [dock-junior-017](../../docs/Reference/junior/docker/docker.json) (service names vs +localhost), [dock-mid-005](../../docs/Reference/mid/docker/docker.json) (CI cache backends), +[dock-mid-010](../../docs/Reference/mid/docker/docker.json) (network drivers, publishing), +[dock-mid-014](../../docs/Reference/mid/docker/docker.json) (log rotation), +[dock-mid-020](../../docs/Reference/mid/docker/docker.json) (socket mount = root on host), +[dock-senior-001](../../docs/Reference/senior/docker/docker.json) (golden base images), +[dock-senior-006](../../docs/Reference/senior/docker/docker.json) (mirror third-party images), +[arch-039](../../docs/Reference/architecture/walkthroughs.json) (measure before caching), +[arch-040](../../docs/Reference/architecture/walkthroughs.json) (one Docker host). diff --git a/docs/CICD/scripts/cap-buildx-builder.sh b/docs/CICD/scripts/cap-buildx-builder.sh new file mode 100755 index 0000000..4ef5af7 --- /dev/null +++ b/docs/CICD/scripts/cap-buildx-builder.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# Cap a named docker-container buildx builder so it cannot take both vCPUs +# or swap-thrash Gitea on the e2-standard-2 (2 vCPU / 8 GB). +# +# ./CICD/scripts/cap-buildx-builder.sh growth-os-builder +# +# BUILDKIT_STEP_MAX_PARALLELISM=1 only serializes steps. A single +# `dotnet publish` / vite / gzip still uses every core unless the +# buildkitd container itself has a cgroup quota. This script: +# - reuses the builder when the driver is already docker-container +# (wiping it would drop the local BuildKit cache) +# - creates it with parallelism=1 and GOMAXPROCS=1 when missing +# - always `docker update --cpus=1 --memory=3g --memory-swap=3g` +# +# Override with BUILDX_HOST_CPUS / BUILDX_HOST_MEMORY. +# The CD job must still bake one target at a time. +set -euo pipefail + +builder="${1:?builder name}" +cpus="${BUILDX_HOST_CPUS:-1.0}" +memory="${BUILDX_HOST_MEMORY:-3g}" + +if docker buildx inspect "$builder" >/dev/null 2>&1; then + driver="$(docker buildx inspect "$builder" | awk '/^Driver:/{print $2; exit}')" + if [ "$driver" = "docker-container" ]; then + docker buildx use "$builder" + else + docker buildx rm -f "$builder" + docker buildx create --name "$builder" --driver docker-container \ + --driver-opt env.BUILDKIT_STEP_MAX_PARALLELISM=1 \ + --driver-opt env.GOMAXPROCS=1 \ + --use + fi +else + docker buildx create --name "$builder" --driver docker-container \ + --driver-opt env.BUILDKIT_STEP_MAX_PARALLELISM=1 \ + --driver-opt env.GOMAXPROCS=1 \ + --use +fi + +docker buildx inspect --bootstrap + +ids="$(docker ps --filter "name=buildx_buildkit_${builder}" --format '{{.ID}}')" +cid="$(printf '%s\n' "$ids" | awk 'NR==1')" +if [ -z "$cid" ]; then + echo "cap-buildx-builder: no running container matching buildx_buildkit_${builder}" >&2 + docker ps --filter "name=buildx_buildkit" >&2 || true + exit 1 +fi + +docker update \ + --cpus="$cpus" \ + --memory="$memory" \ + --memory-swap="$memory" \ + --cpu-shares=512 \ + "$cid" +echo "cap-buildx-builder: ${builder} -> ${cid} cpus=${cpus} memory=${memory} (swap capped)" diff --git a/docs/CICD/scripts/runner-host.sh b/docs/CICD/scripts/runner-host.sh new file mode 100755 index 0000000..47654ca --- /dev/null +++ b/docs/CICD/scripts/runner-host.sh @@ -0,0 +1,207 @@ +#!/usr/bin/env bash +# Manage the remote Gitea act_runner host. +# +# RUNNER_HOST=ci.example.com ./CICD/scripts/runner-host.sh reclaim +# ./CICD/scripts/runner-host.sh reclaim ci.example.com +# ./CICD/scripts/runner-host.sh restart-docker ci.example.com +# +# reclaim (preferred): stop the runner, remove leftover job/BuildKit +# containers, prune unused build cache and dangling images. Docker and +# other stacks (Postgres, compose) stay up. Next bake is colder. +# If Gitea is already 504 / the VM is frozen, Reset from the GCP +# console first — this script needs SSH. +# +# restart-docker: systemctl restart docker. That stops every container +# on the host. Use only if reclaim is not enough and this box is not +# also serving prod. +# +# Optional: RUNNER_USER, RUNNER_SSH_KEY, RUNNER_UNIT, RUNNER_CONTAINER. +set -euo pipefail + +usage() { + sed -n '2,20p' "$0" | sed 's/^# \{0,1\}//' + echo "commands: status | stop | start | reclaim | restart-docker" + exit 2 +} + +CMD="${1:-}" +HOST="${RUNNER_HOST:-${2:-}}" +REMOTE_USER="${RUNNER_USER:-${USER:-}}" +KEY="${RUNNER_SSH_KEY:-}" +UNIT="${RUNNER_UNIT:-}" +CONTAINER="${RUNNER_CONTAINER:-}" + +if [ -z "$CMD" ] || [ "$CMD" = "-h" ] || [ "$CMD" = "--help" ]; then + usage +fi +if [ -z "$HOST" ]; then + echo "set RUNNER_HOST or pass the host as the second argument" >&2 + usage +fi + +ssh_opts=(-o BatchMode=yes -o StrictHostKeyChecking=accept-new) +if [ -n "$KEY" ]; then + ssh_opts+=(-i "$KEY") +fi + +# shellcheck disable=SC2029 +ssh "${ssh_opts[@]}" "${REMOTE_USER}@${HOST}" \ + CMD="$CMD" UNIT="$UNIT" CONTAINER="$CONTAINER" \ + bash -euo pipefail <<'EOF' +sys() { + if systemctl "$@"; then + return 0 + fi + sudo -n systemctl "$@" +} + +runner_names() { + if [ -n "${UNIT:-}" ]; then + printf '%s\n' "$UNIT" + return + fi + printf '%s\n' act_runner act-runner gitea-runner gitea_runner +} + +container_names() { + if [ -n "${CONTAINER:-}" ]; then + printf '%s\n' "$CONTAINER" + return + fi + printf '%s\n' act_runner act-runner gitea-runner gitea_act_runner +} + +find_unit() { + local unit + for unit in $(runner_names); do + if systemctl cat "$unit" >/dev/null 2>&1 || sudo -n systemctl cat "$unit" >/dev/null 2>&1; then + printf '%s\n' "$unit" + return 0 + fi + done + return 1 +} + +find_container() { + local name + for name in $(container_names); do + if docker ps -a --format '{{.Names}}' | grep -qx "$name"; then + printf '%s\n' "$name" + return 0 + fi + done + return 1 +} + +stop_runner() { + local unit container + if unit="$(find_unit)"; then + sys stop "$unit" + echo "stopped systemd unit ${unit}" + return 0 + fi + if container="$(find_container)"; then + docker stop "$container" + echo "stopped docker container ${container}" + return 0 + fi + echo "no act_runner systemd unit or docker container found." >&2 + return 1 +} + +start_runner() { + local unit container + if unit="$(find_unit)"; then + sys start "$unit" + echo "started systemd unit ${unit}" + return 0 + fi + if container="$(find_container)"; then + docker start "$container" + echo "started docker container ${container}" + return 0 + fi + echo "no act_runner systemd unit or docker container found." >&2 + return 1 +} + +show_status() { + echo "=== memory ===" + free -h || true + echo "=== docker disk ===" + docker system df || true + echo "=== running containers ===" + docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Size}}' || true + echo "=== buildx ===" + docker buildx ls || true +} + +reclaim() { + echo "=== before ===" + show_status + + stop_runner || true + + leftovers="$( + { + docker ps -aq --filter name=GITEA-ACTIONS + docker ps -aq --filter name=buildx_buildkit + docker ps -aq --filter name=buildkit + } 2>/dev/null | awk 'NF && !seen[$0]++' + )" + if [ -n "$leftovers" ]; then + # shellcheck disable=SC2086 + docker stop $leftovers >/dev/null 2>&1 || true + # shellcheck disable=SC2086 + docker rm -f $leftovers >/dev/null + echo "removed leftover job/BuildKit containers" + else + echo "no leftover job/BuildKit containers" + fi + + # Drop named docker-container builders left by CD (cap-buildx-builder.sh). + # Enumerated, not hardcoded — a per-project name list goes stale on every onboarding. + docker buildx ls 2>/dev/null | awk '/docker-container/ {print $1}' | while read -r b; do + [ -n "$b" ] || continue + docker buildx rm -f "$b" >/dev/null 2>&1 || true + done + docker container prune -f >/dev/null + docker builder prune -f + docker image prune -f + echo "pruned unused build cache and dangling images (volumes left alone)" + + start_runner || true + + echo "=== after ===" + show_status +} + +restart_docker() { + echo "restarting docker — every container on this host will stop." + stop_runner || true + sys restart docker + for i in $(seq 1 30); do + if docker info >/dev/null 2>&1; then + break + fi + sleep 1 + done + docker info >/dev/null + echo "docker is up" + start_runner || true + show_status +} + +case "$CMD" in + status) show_status ;; + stop) stop_runner ;; + start) start_runner ;; + reclaim) reclaim ;; + restart-docker) restart_docker ;; + *) + echo "unknown command: $CMD" >&2 + echo "commands: status | stop | start | reclaim | restart-docker" >&2 + exit 2 + ;; +esac +EOF diff --git a/docs/CICD/scripts/start-job-sidecars.sh b/docs/CICD/scripts/start-job-sidecars.sh new file mode 100755 index 0000000..cf24db9 --- /dev/null +++ b/docs/CICD/scripts/start-job-sidecars.sh @@ -0,0 +1,205 @@ +#!/usr/bin/env bash +# Start Postgres, RabbitMQ, and Redis on the current Gitea Actions job network. +# Use this instead of workflow services: for RabbitMQ — on this runner, RabbitMQ +# as a service fails health before any step runs (see platform/observed-state.md). +# +# Requires: Docker socket on the job, docker CLI, bash. Optional: node for AMQP TCP probe. +# Exports into $GITHUB_ENV (when set): +# CI_PG_NAME, CI_RMQ_NAME, CI_REDIS_NAME +# DATABASE_URL, AMQP_URL, REDIS_URL (override names via env below) +# +# Optional env: +# CI_PG_IMAGE, CI_RMQ_IMAGE, CI_REDIS_IMAGE +# CI_PG_DB, CI_PG_USER, CI_PG_PASSWORD +# CI_RMQ_USER, CI_RMQ_PASS +# CI_DATABASE_URL_VAR, CI_AMQP_URL_VAR, CI_REDIS_URL_VAR (names written to GITHUB_ENV) +# CI_MIGRATOR_URL_VAR (optional second name for the same Postgres URL) +set -euo pipefail + +PG_IMAGE="${CI_PG_IMAGE:-postgres:16-alpine}" +RMQ_IMAGE="${CI_RMQ_IMAGE:-rabbitmq:3.13-alpine}" +REDIS_IMAGE="${CI_REDIS_IMAGE:-redis:7.2-alpine}" +PG_DB="${CI_PG_DB:-app_test}" +PG_USER="${CI_PG_USER:-postgres}" +PG_PASSWORD="${CI_PG_PASSWORD:-postgres}" +RMQ_USER="${CI_RMQ_USER:-ciuser}" +RMQ_PASS="${CI_RMQ_PASS:-cipass}" +DATABASE_URL_VAR="${CI_DATABASE_URL_VAR:-DATABASE_URL}" +AMQP_URL_VAR="${CI_AMQP_URL_VAR:-AMQP_URL}" +REDIS_URL_VAR="${CI_REDIS_URL_VAR:-REDIS_URL}" +MIGRATOR_URL_VAR="${CI_MIGRATOR_URL_VAR:-}" + +find_job_cid() { + local cid + cid="$(grep -oE '[0-9a-f]{64}' /proc/self/cgroup 2>/dev/null | head -1 || true)" + if [ -n "${cid}" ] && docker inspect "${cid}" >/dev/null 2>&1; then + printf '%s\n' "${cid}" + return 0 + fi + if docker inspect "$(hostname)" >/dev/null 2>&1; then + hostname + return 0 + fi + cid="$(grep -oE 'containers/[0-9a-f]{64}' /proc/self/mountinfo 2>/dev/null | head -1 | cut -d/ -f2 || true)" + if [ -n "${cid}" ] && docker inspect "${cid}" >/dev/null 2>&1; then + printf '%s\n' "${cid}" + return 0 + fi + return 1 +} + +CID="$(find_job_cid)" || { + echo "start-job-sidecars: cannot resolve job container id (is /var/run/docker.sock mounted?)" >&2 + exit 1 +} +NETWORK="$(docker inspect -f '{{range $k, $_ := .NetworkSettings.Networks}}{{println $k}}{{end}}' "${CID}" | awk 'NF { print; exit }')" +if [ -z "${NETWORK}" ]; then + echo "start-job-sidecars: job container ${CID} has no Docker network" >&2 + exit 1 +fi +echo "start-job-sidecars: job=${CID} network=${NETWORK}" + +SUFFIX="${GITHUB_RUN_ID:-local}-${GITHUB_RUN_ATTEMPT:-1}" +PG_NAME="ci-pg-${SUFFIX}" +RMQ_NAME="ci-rmq-${SUFFIX}" +REDIS_NAME="ci-redis-${SUFFIX}" + +if [ -n "${GITHUB_ENV:-}" ]; then + { + echo "CI_PG_NAME=${PG_NAME}" + echo "CI_RMQ_NAME=${RMQ_NAME}" + echo "CI_REDIS_NAME=${REDIS_NAME}" + } >> "${GITHUB_ENV}" +fi + +docker rm -f "${PG_NAME}" "${RMQ_NAME}" "${REDIS_NAME}" 2>/dev/null || true + +if [ "${NETWORK}" = "host" ]; then + docker run -d --name "${PG_NAME}" \ + -e POSTGRES_DB="${PG_DB}" \ + -e POSTGRES_USER="${PG_USER}" \ + -e POSTGRES_PASSWORD="${PG_PASSWORD}" \ + -p 127.0.0.1:45432:5432 \ + "${PG_IMAGE}" + docker run -d --name "${RMQ_NAME}" \ + --hostname "${RMQ_NAME}" \ + -e RABBITMQ_NODENAME="rabbit@${RMQ_NAME}" \ + -e RABBITMQ_DEFAULT_USER="${RMQ_USER}" \ + -e RABBITMQ_DEFAULT_PASS="${RMQ_PASS}" \ + -p 127.0.0.1:45672:5672 \ + "${RMQ_IMAGE}" + docker run -d --name "${REDIS_NAME}" \ + -p 127.0.0.1:46379:6379 \ + "${REDIS_IMAGE}" + PG_HOST=127.0.0.1; PG_PORT=45432 + RMQ_HOST=127.0.0.1; RMQ_PORT=45672 + REDIS_HOST=127.0.0.1; REDIS_PORT=46379 +else + docker run -d --name "${PG_NAME}" \ + --network "${NETWORK}" \ + -e POSTGRES_DB="${PG_DB}" \ + -e POSTGRES_USER="${PG_USER}" \ + -e POSTGRES_PASSWORD="${PG_PASSWORD}" \ + "${PG_IMAGE}" + docker run -d --name "${RMQ_NAME}" \ + --network "${NETWORK}" \ + --hostname "${RMQ_NAME}" \ + -e RABBITMQ_NODENAME="rabbit@${RMQ_NAME}" \ + -e RABBITMQ_DEFAULT_USER="${RMQ_USER}" \ + -e RABBITMQ_DEFAULT_PASS="${RMQ_PASS}" \ + "${RMQ_IMAGE}" + docker run -d --name "${REDIS_NAME}" \ + --network "${NETWORK}" \ + "${REDIS_IMAGE}" + PG_PORT=5432; RMQ_PORT=5672; REDIS_PORT=6379 + PG_HOST="$(docker inspect -f "{{(index .NetworkSettings.Networks \"${NETWORK}\").IPAddress}}" "${PG_NAME}")" + RMQ_HOST="$(docker inspect -f "{{(index .NetworkSettings.Networks \"${NETWORK}\").IPAddress}}" "${RMQ_NAME}")" + REDIS_HOST="$(docker inspect -f "{{(index .NetworkSettings.Networks \"${NETWORK}\").IPAddress}}" "${REDIS_NAME}")" + if [ -z "${PG_HOST}" ] || [ -z "${RMQ_HOST}" ] || [ -z "${REDIS_HOST}" ] \ + || [ "${PG_HOST}" = "" ] || [ "${RMQ_HOST}" = "" ] || [ "${REDIS_HOST}" = "" ]; then + echo "start-job-sidecars: failed to resolve dependency IPs on ${NETWORK}" >&2 + exit 1 + fi + echo "start-job-sidecars: ips pg=${PG_HOST} rmq=${RMQ_HOST} redis=${REDIS_HOST}" +fi + +echo "Waiting for Postgres…" +for i in $(seq 1 60); do + if docker exec "${PG_NAME}" pg_isready -U "${PG_USER}" -d "${PG_DB}" >/dev/null 2>&1; then + echo "Postgres ready" + break + fi + if [ "${i}" -eq 60 ]; then + docker logs "${PG_NAME}" || true + exit 1 + fi + sleep 1 +done + +echo "Waiting for RabbitMQ…" +for i in $(seq 1 90); do + if docker exec "${RMQ_NAME}" rabbitmq-diagnostics -q ping >/dev/null 2>&1 \ + && docker exec "${RMQ_NAME}" rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; then + echo "RabbitMQ ready (ping + listeners)" + break + fi + if [ "${i}" -eq 90 ]; then + docker logs "${RMQ_NAME}" || true + exit 1 + fi + sleep 1 +done + +echo "Probing AMQP ${RMQ_HOST}:${RMQ_PORT} from job…" +for i in $(seq 1 30); do + if command -v node >/dev/null 2>&1; then + if node -e " + const net = require('net'); + const s = net.connect(${RMQ_PORT}, '${RMQ_HOST}', () => { s.end(); process.exit(0); }); + s.on('error', () => process.exit(1)); + setTimeout(() => process.exit(1), 2000); + "; then + echo "AMQP port reachable from job" + break + fi + else + echo "AMQP TCP probe skipped (node not on PATH)" + break + fi + if [ "${i}" -eq 30 ]; then + echo "start-job-sidecars: AMQP probe failed — job cannot reach ${RMQ_HOST}:${RMQ_PORT}" >&2 + docker logs "${RMQ_NAME}" || true + exit 1 + fi + sleep 1 +done + +echo "Waiting for Redis…" +for i in $(seq 1 30); do + if docker exec "${REDIS_NAME}" redis-cli ping 2>/dev/null | grep -q PONG; then + echo "Redis ready" + break + fi + if [ "${i}" -eq 30 ]; then + docker logs "${REDIS_NAME}" || true + exit 1 + fi + sleep 1 +done + +DATABASE_URL="postgresql://${PG_USER}:${PG_PASSWORD}@${PG_HOST}:${PG_PORT}/${PG_DB}" +AMQP_URL="amqp://${RMQ_USER}:${RMQ_PASS}@${RMQ_HOST}:${RMQ_PORT}" +REDIS_URL="redis://${REDIS_HOST}:${REDIS_PORT}" + +if [ -n "${GITHUB_ENV:-}" ]; then + { + echo "${DATABASE_URL_VAR}=${DATABASE_URL}" + echo "${AMQP_URL_VAR}=${AMQP_URL}" + echo "${REDIS_URL_VAR}=${REDIS_URL}" + if [ -n "${MIGRATOR_URL_VAR}" ]; then + echo "${MIGRATOR_URL_VAR}=${DATABASE_URL}" + fi + } >> "${GITHUB_ENV}" +fi + +echo "start-job-sidecars: ready ${DATABASE_URL_VAR} / ${AMQP_URL_VAR} / ${REDIS_URL_VAR}" diff --git a/docs/CICD/scripts/stop-runner.sh b/docs/CICD/scripts/stop-runner.sh new file mode 100755 index 0000000..8fa336d --- /dev/null +++ b/docs/CICD/scripts/stop-runner.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# Compatibility wrapper. Prefer: +# ./CICD/scripts/runner-host.sh reclaim "$HOST" +# to free job/BuildKit cache without restarting Docker. +set -euo pipefail +dir="$(cd "$(dirname "$0")" && pwd)" +if [ "${1:-}" = "-h" ] || [ "${1:-}" = "--help" ]; then + exec "$dir/runner-host.sh" --help +fi +if [ -n "${1:-}" ]; then + exec "$dir/runner-host.sh" stop "$1" +fi +exec "$dir/runner-host.sh" stop diff --git a/docs/CICD/templates/.env.example b/docs/CICD/templates/.env.example new file mode 100644 index 0000000..c371753 --- /dev/null +++ b/docs/CICD/templates/.env.example @@ -0,0 +1,25 @@ +# Kit template — host-owned at /opt//.env (chmod 600). +# CD never uploads this file — only the IMAGE_TAG line is patched each release. +# Never commit a filled .env. +# +# PG_* must be Npgsql key=value form, not a URI. No wrapping quotes. +# Every segment must be Key=Value. A common mistake that breaks readiness: +# Username=app;mysecret!;SSL Mode=Disable ← missing Password= +# Correct: +# Username=app;Password=mysecret!;SSL Mode=Disable + +# ---- image coordinates ---- +REGISTRY=git.vectur45.com// +IMAGE_TAG=latest + +# ---- exposed ports on the production host ---- +API_PORT=8100 +UI_PORT=8101 + +# ---- PostgreSQL (shared-services network; Host=postgres is Docker DNS) ---- +PG_CONNECTION=Host=postgres;Port=5432;Database=myapp;Username=myapp;Password=CHANGE_ME;SSL Mode=Disable +# DDL-only for the CD migrate job (Gitea secret PG_CONNECTION_DDL). Never inject into the API container. +# PG_CONNECTION_DDL=Host=postgres;Port=5432;Database=myapp;Username=myapp_migrator;Password=CHANGE_ME;SSL Mode=Disable + +# ---- application secrets (openssl rand -base64 48) ---- +API_KEY=CHANGE_ME_AT_LEAST_32_BYTES diff --git a/docs/CICD/templates/README.md b/docs/CICD/templates/README.md new file mode 100644 index 0000000..311ca50 --- /dev/null +++ b/docs/CICD/templates/README.md @@ -0,0 +1,17 @@ +# Templates — copy and rename + +Copy these into a project repo. **No product names** — only placeholders. + +| File | Copy to | +| --- | --- | +| `workflows/ci.yml` | `.gitea/workflows/ci.yml` | +| `workflows/cd.yml` | `.gitea/workflows/cd.yml` | +| `docker-bake.hcl` | repo root | +| `docker-compose.prod.yml` | repo root (and/or deploy host) | +| `.env.example` | document host `.env` shape (never commit secrets) | + +Also copy [`../scripts/cap-buildx-builder.sh`](../scripts/cap-buildx-builder.sh) to the +project’s `scripts/` until `infra/ci-actions` owns capped bake. + +Fill the substitute table in [`../onboarding-a-project.md`](../onboarding-a-project.md) before +the first CI run. diff --git a/docs/CICD/templates/docker-bake.hcl b/docs/CICD/templates/docker-bake.hcl new file mode 100644 index 0000000..8aaa377 --- /dev/null +++ b/docs/CICD/templates/docker-bake.hcl @@ -0,0 +1,46 @@ +# Kit template — copy to the repo root (or pass -f). +# Invoked from the repo root. cwd:// keeps contexts relative to that +# working directory, not this file. +# +# CD must cap the builder cgroup (scripts/cap-buildx-builder.sh) +# and bake one target at a time. The runner host also runs Gitea. +# +# The API Dockerfile must end with `final` and expose a slim +# `migrate-bundle` stage (scratch + /out/migrate-api + CMD). Do not bake the +# SDK `migrate` stage into the daemon. +# +# Substitute: , , api/, web/ (drop ui target if no SPA image). + +variable "REGISTRY" {} +variable "TAG" {} + +group "default" { + targets = ["api", "ui", "migrate"] +} + +target "api" { + context = "cwd://api" + dockerfile = "Dockerfile" + target = "final" + tags = ["${REGISTRY}/-api:${TAG}", "${REGISTRY}/-api:latest"] + cache-from = ["type=registry,ref=${REGISTRY}/-api:buildcache"] + cache-to = ["type=registry,ref=${REGISTRY}/-api:buildcache,mode=max"] +} + +target "ui" { + context = "cwd://web" + dockerfile = "Dockerfile" + target = "final" + tags = ["${REGISTRY}/-ui:${TAG}", "${REGISTRY}/-ui:latest"] + cache-from = ["type=registry,ref=${REGISTRY}/-ui:buildcache"] + cache-to = ["type=registry,ref=${REGISTRY}/-ui:buildcache,mode=max"] +} + +target "migrate" { + context = "cwd://api" + dockerfile = "Dockerfile" + target = "migrate-bundle" + tags = ["-migrate-bundle:local"] + cache-from = ["type=registry,ref=${REGISTRY}/-api:buildcache"] + # no cache-to — api already exports this Dockerfile at mode=max +} diff --git a/docs/CICD/templates/docker-compose.prod.yml b/docs/CICD/templates/docker-compose.prod.yml new file mode 100644 index 0000000..1faf330 --- /dev/null +++ b/docs/CICD/templates/docker-compose.prod.yml @@ -0,0 +1,54 @@ +# Kit template — copy to the deploy host as /opt//docker-compose.prod.yml +# (or ship from the repo and scp in CD). +# +# Runs app containers only. Shared Postgres/RabbitMQ/Redis/Seq live on the +# external "shared-services" network and must already exist. +# +# docker compose -f docker-compose.prod.yml --env-file .env up -d +# +# Substitute: , image names, env keys your app needs. + +name: myapp + +services: + api: + image: ${REGISTRY}/-api:${IMAGE_TAG} + container_name: myapp_api + restart: unless-stopped + ports: + - "${API_PORT:-8100}:8080" + environment: + ASPNETCORE_ENVIRONMENT: Production + ConnectionStrings__Default: "${PG_CONNECTION}" + Auth__ApiKey: "${API_KEY}" + networks: + - myapp_prod + - shared-services + logging: + driver: json-file + options: { max-size: "50m", max-file: "5" } + deploy: + resources: + limits: { memory: 1G } + + # Optional SPA / static UI image — delete if CD only ships the API. + ui: + image: ${REGISTRY}/-ui:${IMAGE_TAG} + container_name: myapp_ui + restart: unless-stopped + ports: + - "${UI_PORT:-8101}:80" + networks: + - myapp_prod + logging: + driver: json-file + options: { max-size: "20m", max-file: "3" } + deploy: + resources: + limits: { memory: 256M } + +networks: + myapp_prod: + driver: bridge + shared-services: + external: true diff --git a/docs/CICD/templates/workflows/cd.yml b/docs/CICD/templates/workflows/cd.yml new file mode 100644 index 0000000..d92e3e5 --- /dev/null +++ b/docs/CICD/templates/workflows/cd.yml @@ -0,0 +1,281 @@ +# Kit template — copy to .gitea/workflows/cd.yml and fill placeholders. +# Copy templates/docker-bake.hcl to the repo root; copy scripts/cap-buildx-builder.sh +# next to CD (until infra/ci-actions owns capped bake). +# +# ubuntu-latest is a registered runner label, not a GitHub-hosted VM. +# Requires Docker-mode runner (host docker socket), curl, ssh, scp, bash. +# GITEA_TOKEN cannot push images — REGISTRY_TOKEN must be a PAT. +# +# Secrets: REGISTRY_USERNAME, REGISTRY_TOKEN, PG_CONNECTION_DDL, +# DEPLOY_HOST, DEPLOY_USER, DEPLOY_SSH_KEY +# Variables: REGISTRY (optional), UI_* bake vars if you ship a SPA image, +# MIGRATE_DOCKER_NETWORK (default shared-services) +# +# Substitute every , , /opt/, image names. +name: CD + +on: + push: + tags: ["v*"] + workflow_dispatch: + inputs: + image_tag: + description: "Image tag to deploy (defaults to the pushed tag)" + required: false + +env: + REGISTRY: git.vectur45.com// + +jobs: + build-and-push: + runs-on: ubuntu-latest + outputs: + tag: ${{ steps.meta.outputs.tag }} + steps: + - uses: actions/checkout@v4 + + - name: Resolve tag and registry + id: meta + run: | + if [ -n "${{ vars.REGISTRY }}" ]; then + echo "REGISTRY=${{ vars.REGISTRY }}" >> "$GITHUB_ENV" + fi + if [ -n "${{ inputs.image_tag }}" ]; then + echo "tag=${{ inputs.image_tag }}" >> "$GITHUB_OUTPUT" + elif [[ "${GITHUB_REF}" == refs/tags/* ]]; then + echo "tag=${GITHUB_REF_NAME}" >> "$GITHUB_OUTPUT" + else + echo "image_tag input is required for workflow_dispatch without a tag" >&2 + exit 1 + fi + + - name: Log in to the Gitea registry + run: | + echo "${{ secrets.REGISTRY_TOKEN }}" \ + | docker login "${REGISTRY%%/*}" \ + -u "${{ secrets.REGISTRY_USERNAME }}" --password-stdin + + - name: Bake and push images + env: + TAG: ${{ steps.meta.outputs.tag }} + VITE_API_BASE_URL: ${{ vars.UI_API_BASE_URL }} + VITE_RELEASE: ${{ steps.meta.outputs.tag }} + VITE_ENVIRONMENT: production + run: | + # Cap buildkitd cgroup, then bake one target at a time — + # BUILDKIT_STEP_MAX_PARALLELISM=1 alone does not leave Gitea a core. + bash scripts/cap-buildx-builder.sh -builder + bake_one() { + local target="$1" + shift + echo "=== bake ${target} ===" + BUILDX_NO_DEFAULT_ATTESTATIONS=1 docker buildx bake \ + --progress=plain \ + "$target" \ + "$@" \ + -f docker-bake.hcl + } + bake_one api --push --set api.output=type=image,push=true + sleep 8 + # Omit ui bake if the project has no SPA image. + if [ -n "${VITE_API_BASE_URL}" ]; then + bake_one ui --push --set ui.output=type=image,push=true + sleep 8 + fi + bake_one migrate --set migrate.output=type=docker + # scratch migrate-bundle needs an explicit command (or image CMD). + cid=$(docker create -migrate-bundle:local /out/migrate-api) + docker cp "$cid:/out/migrate-api" ./migrate-api + docker rm "$cid" + chmod +x ./migrate-api + + - name: Upload migration bundle + uses: actions/upload-artifact@v4 + with: + name: migrate-api + path: migrate-api + if-no-files-found: error + + migrate: + needs: build-and-push + runs-on: ubuntu-latest + # Bundle is an artefact from build-and-push — never docker build here. + # Bind mounts resolve on the Docker host, not the job workspace. + # Postgres is on the deploy host; copy the binary there. + steps: + - name: Download migration bundle + uses: actions/download-artifact@v4 + with: + name: migrate-api + path: . + + - name: Configure SSH + run: | + mkdir -p ~/.ssh + echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519 + chmod 600 ~/.ssh/id_ed25519 + ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts + chmod +x ./migrate-api + + # Expand-then-contract: migrate while the previous release still serves. + # PG_CONNECTION_DDL must be Npgsql key=value form, not a URI. No wrapping quotes. + - name: Apply migrations + env: + PG_CONNECTION_DDL: ${{ secrets.PG_CONNECTION_DDL }} + MIGRATE_DOCKER_NETWORK: ${{ vars.MIGRATE_DOCKER_NETWORK }} + run: | + REMOTE="${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" + NETWORK="${MIGRATE_DOCKER_NETWORK:-shared-services}" + scp -i ~/.ssh/id_ed25519 ./migrate-api \ + "$REMOTE:/tmp/myapp-migrate-api" + umask 077 + printf '%s' "$PG_CONNECTION_DDL" > /tmp/myapp-pg-ddl + scp -i ~/.ssh/id_ed25519 /tmp/myapp-pg-ddl \ + "$REMOTE:/tmp/myapp-pg-ddl" + rm -f /tmp/myapp-pg-ddl + ssh -i ~/.ssh/id_ed25519 "$REMOTE" \ + NETWORK="$NETWORK" \ + bash -euo pipefail <<'EOF' + chmod +x /tmp/myapp-migrate-api + chmod 600 /tmp/myapp-pg-ddl + + PG_CONNECTION_DDL="$(tr -d '\r\n' < /tmp/myapp-pg-ddl)" + PG_CONNECTION_DDL="${PG_CONNECTION_DDL#\"}" + PG_CONNECTION_DDL="${PG_CONNECTION_DDL%\"}" + PG_CONNECTION_DDL="${PG_CONNECTION_DDL#\'}" + PG_CONNECTION_DDL="${PG_CONNECTION_DDL%\'}" + + if [[ "$PG_CONNECTION_DDL" == postgresql://* || "$PG_CONNECTION_DDL" == postgres://* ]]; then + echo "PG_CONNECTION_DDL must be Npgsql key=value form, not a URI." >&2 + exit 1 + fi + if [[ "$PG_CONNECTION_DDL" != Host=* && "$PG_CONNECTION_DDL" != host=* ]]; then + PG_CONNECTION_DDL="Host=${PG_CONNECTION_DDL}" + fi + printf '%s' "$PG_CONNECTION_DDL" > /tmp/myapp-pg-ddl + + docker run --rm \ + --network "${NETWORK}" \ + -v /tmp/myapp-migrate-api:/migrate-api:ro \ + -v /tmp/myapp-pg-ddl:/run/pg-ddl:ro \ + --entrypoint sh \ + mcr.microsoft.com/dotnet/runtime-deps:8.0 \ + -c 'exec /migrate-api --connection "$(tr -d "\r\n" < /run/pg-ddl)"' + rm -f /tmp/myapp-migrate-api /tmp/myapp-pg-ddl + EOF + + deploy: + needs: [build-and-push, migrate] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Configure SSH + run: | + mkdir -p ~/.ssh + echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519 + chmod 600 ~/.ssh/id_ed25519 + ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts + + - name: Copy compose file + run: | + scp -i ~/.ssh/id_ed25519 docker-compose.prod.yml \ + "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}:/opt//docker-compose.prod.yml" + + - name: Deploy + env: + IMAGE_TAG: ${{ needs.build-and-push.outputs.tag }} + REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }} + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + run: | + if [ -n "${{ vars.REGISTRY }}" ]; then + REGISTRY="${{ vars.REGISTRY }}" + else + REGISTRY="git.vectur45.com//" + fi + REGISTRY_HOST="${REGISTRY%%/*}" + ssh -i ~/.ssh/id_ed25519 \ + "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" \ + IMAGE_TAG="$IMAGE_TAG" \ + REGISTRY_HOST="$REGISTRY_HOST" \ + REGISTRY_USERNAME="$REGISTRY_USERNAME" \ + REGISTRY_TOKEN="$REGISTRY_TOKEN" \ + bash -euo pipefail <<'EOF' + cd /opt/ + + echo "${REGISTRY_TOKEN}" | docker login "${REGISTRY_HOST}" \ + -u "${REGISTRY_USERNAME}" --password-stdin + + env_val() { sed -n "s/^${1}=//p" .env | tail -n1 | tr -d '\r'; } + strip_quotes() { + local v="$1" + v="${v#\"}"; v="${v%\"}"; v="${v#\'}"; v="${v%\'}" + printf '%s' "$v" + } + PG_CONNECTION="$(strip_quotes "$(env_val PG_CONNECTION)")" + if [[ -z "$PG_CONNECTION" ]]; then + echo "PG_CONNECTION is empty in /opt//.env" >&2 + exit 1 + fi + if [[ "$PG_CONNECTION" != Host=* && "$PG_CONNECTION" != host=* ]]; then + echo "PG_CONNECTION must start with Host= (Npgsql key=value form)." >&2 + exit 1 + fi + + grep '^IMAGE_TAG=' .env > .env.previous || true + if grep -q '^IMAGE_TAG=' .env; then + sed -i "s|^IMAGE_TAG=.*|IMAGE_TAG=${IMAGE_TAG}|" .env + else + echo "IMAGE_TAG=${IMAGE_TAG}" >> .env + fi + + docker compose -f docker-compose.prod.yml --env-file .env pull + docker compose -f docker-compose.prod.yml --env-file .env up -d --remove-orphans + docker image prune -f + docker compose -f docker-compose.prod.yml --env-file .env ps -a + EOF + + - name: Smoke test + run: | + ssh -i ~/.ssh/id_ed25519 \ + "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" bash -euo pipefail <<'EOF' + cd /opt/ + env_val() { sed -n "s/^${1}=//p" .env | tail -n1 | tr -d '\r'; } + API_PORT="$(env_val API_PORT)"; API_PORT="${API_PORT:-8100}" + + for i in $(seq 1 30); do + set +e + http_code=$(curl -s -o /dev/null -w '%{http_code}' --connect-timeout 2 \ + "http://localhost:${API_PORT}/health/ready" 2>/dev/null) + curl_exit=$? + set -e + if [ "$curl_exit" -ne 0 ] || [ -z "$http_code" ]; then + http_code="000" + fi + if [ "$http_code" = "200" ]; then + echo "Ready check passed (attempt ${i})." + exit 0 + fi + echo "Attempt ${i}/30: HTTP ${http_code}" + sleep 5 + done + echo "Ready check never passed" + docker compose -f docker-compose.prod.yml --env-file .env logs --tail 150 api || true + exit 1 + EOF + + - name: Roll back on failure + if: failure() + run: | + ssh -i ~/.ssh/id_ed25519 \ + "${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}" bash -euo pipefail <<'EOF' + cd /opt/ + # Restores the previous image tag only. Schema is NOT reverted — + # migrations must be backwards-compatible (expand-then-contract). + if [ -f .env.previous ]; then + PREV=$(cut -d= -f2 .env.previous) + sed -i "s|^IMAGE_TAG=.*|IMAGE_TAG=${PREV}|" .env + docker compose -f docker-compose.prod.yml --env-file .env up -d + echo "Rolled back to ${PREV}" + fi + EOF diff --git a/docs/CICD/templates/workflows/ci.yml b/docs/CICD/templates/workflows/ci.yml new file mode 100644 index 0000000..4b50b20 --- /dev/null +++ b/docs/CICD/templates/workflows/ci.yml @@ -0,0 +1,115 @@ +# Kit template — copy to .gitea/workflows/ci.yml and fill placeholders. +# Pin @v1 (or @v1.1 once post_build_command is tagged on infra/ci-workflows). +# Never a branch. Path filter + changes job stay local (repo-specific). +# +# node-ci phases: lint → extra_check (NO dist) → build → post_build (MAY use dist). +# Do not put check:bundle / Playwright / anything that needs dist/ in extra_check. +# +# If tests still use Testcontainers, the workflow's Postgres/Redis services may sit +# idle — prefer extending infra/ci-workflows over forking steps. +name: CI + +on: + push: + branches: [main, master] + paths: + - "api/**" + - "web/**" + - "tests/**" + - "MyApp.sln" + - ".gitea/workflows/**" + pull_request: + branches: [main, master] + paths: + - "api/**" + - "web/**" + - "tests/**" + - "MyApp.sln" + - ".gitea/workflows/**" + workflow_dispatch: + +jobs: + # Stays local: repo-specific path map; needs fetch-depth: 0. + # Keep actions/checkout@v4 here until builtin:checkout is proven with fetch-depth: 0. + changes: + runs-on: ubuntu-latest + outputs: + backend: ${{ steps.filter.outputs.backend }} + frontend: ${{ steps.filter.outputs.frontend }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - id: filter + name: Detect stack changes + run: | + set -euo pipefail + backend=false + frontend=false + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + backend=true + frontend=true + else + if [ "${{ github.event_name }}" = "pull_request" ]; then + base="${{ github.event.pull_request.base.sha }}" + else + base="${{ github.event.before }}" + fi + if [ -z "${base:-}" ] || [ "$base" = "0000000000000000000000000000000000000000" ]; then + backend=true + frontend=true + else + files="$(git diff --name-only "$base" "${{ github.sha }}")" + printf '%s\n' "$files" + if printf '%s\n' "$files" | grep -qE '^(api/|tests/|MyApp\.sln|\.gitea/workflows/)'; then + backend=true + fi + if printf '%s\n' "$files" | grep -qE '^(web/|\.gitea/workflows/)'; then + frontend=true + fi + fi + fi + echo "backend=${backend}" >> "$GITHUB_OUTPUT" + echo "frontend=${frontend}" >> "$GITHUB_OUTPUT" + + backend: + needs: changes + if: needs.changes.outputs.backend == 'true' + uses: infra/ci-workflows/.gitea/workflows/dotnet8-ci.yml@v1 + with: + working_directory: . + solution: MyApp.sln + postgres_db: myapp_test + # Prefer split projects: isolated (InMemory) first, then service-backed. + # If unit + integration share one .csproj, omit isolated_test_projects and + # list that project only under test_projects. + isolated_test_projects: | + tests/MyApp.UnitTests/MyApp.UnitTests.csproj + test_projects: | + tests/MyApp.IntegrationTests/MyApp.IntegrationTests.csproj + test_env: | + Auth__ApiKey=ci-test-api-key-at-least-32-bytes-long!! + + frontend: + needs: changes + if: needs.changes.outputs.frontend == 'true' + # Use @v1.1 once infra/ci-workflows tags post_build_command; until then keep + # post-dist steps inside build_command after `npx vite build`. + uses: infra/ci-workflows/.gitea/workflows/node-ci.yml@v1 + with: + working_directory: web + node_version: "22" + # Typecheck once here; build must not re-run tsc / vue-tsc. + lint_command: npm run lint && npm run typecheck + # Pre-dist only (audit, unit tests, source checks). + extra_check_command: npm audit --audit-level=high && npm run test -- --run --coverage + build_command: npx vite build + # Needs dist/ — bundle budget, Playwright, etc. (requires node-ci @v1.1+) + post_build_command: npm run check:bundle && npx playwright install --with-deps chromium && npx playwright test + build_env: | + VITE_API_BASE_URL=http://localhost:5067 + VITE_RELEASE=ci + VITE_ENVIRONMENT=ci + CI=true + artifact_path: dist diff --git a/docs/CICD/updateCICD.md b/docs/CICD/updateCICD.md new file mode 100644 index 0000000..024a860 --- /dev/null +++ b/docs/CICD/updateCICD.md @@ -0,0 +1 @@ +Use docs/CICD/* especially onboarding-a-project.md to update the ci/cd of this project and remove any unnecessary/overengineered parts. List what needs to change below \ No newline at end of file diff --git a/scripts/ci-start-sidecars.sh b/scripts/ci-start-sidecars.sh index af1b3e7..679f613 100755 --- a/scripts/ci-start-sidecars.sh +++ b/scripts/ci-start-sidecars.sh @@ -12,8 +12,8 @@ RMQ_IMAGE="${CI_RMQ_IMAGE:-rabbitmq:3.13-management-alpine}" REDIS_IMAGE="${CI_REDIS_IMAGE:-redis:7-alpine}" KAFKA_IMAGE="${CI_KAFKA_IMAGE:-apache/kafka:3.7.0}" ES_IMAGE="${CI_ES_IMAGE:-docker.elastic.co/elasticsearch/elasticsearch:8.13.0}" -# Official images are on quay.io; Docker Hub returns "access denied" for minio/minio. -MINIO_IMAGE="${CI_MINIO_IMAGE:-quay.io/minio/minio:RELEASE.2024-07-04T14-25-45Z}" +# Upstream minio/minio was removed from Docker Hub/Quay; mirror of pgsty/minio. +MINIO_IMAGE="${CI_MINIO_IMAGE:-git.vectur45.com/trent/ci-minio:latest}" PG_USER="${CI_PG_USER:-postgres}" PG_PASSWORD="${CI_PG_PASSWORD:-postgres}"