diff --git a/.github/scripts/smoke-test.sh b/.github/scripts/smoke-test.sh new file mode 100755 index 0000000..5854891 --- /dev/null +++ b/.github/scripts/smoke-test.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Boots the Laravel for Rust dev image the way Ingot runs it and checks it +# does what the README promises, so a broken image never gets a tag. Run by +# build.yml on each architecture's own runner; also runnable by hand: +# +# .github/scripts/smoke-test.sh +# .github/scripts/smoke-test.sh laravel-rust:test +# +# It makes a new app with `laravel new --rust` inside the image, then: +# - runs `laravel migrate` on its own (no npm install for that); +# - runs the image's default `laravel dev` and waits for /up to answer 200 +# (node_modules is installed first, by the entrypoint); +# - checks the files it wrote belong to the calling user; +# - edits src/ and waits for the server to restart; +# - checks `docker stop` is prompt. +# Needs network access (crates.io, npm, the starter app) and Docker. Leaves +# nothing behind: containers, network, volumes and the app folder are +# removed on exit. +set -euo pipefail + +if [ "$#" -ne 1 ]; then + echo "usage: $0 " >&2 + exit 2 +fi +image=$1 + +# Seconds to wait for each step. The first compile of a new app is cold in +# CI; the defaults leave plenty of room on a GitHub-hosted runner. +up_timeout=${SMOKE_UP_TIMEOUT:-900} +restart_timeout=${SMOKE_RESTART_TIMEOUT:-300} + +# Logs are read into a variable before searching: with pipefail, +# `docker logs | grep -q` fails whenever grep exits at its first match +# before docker logs has finished writing. +logs() { docker logs "$@" "$prefix-app" 2>&1 || true; } + +fail() { echo "SMOKE TEST FAILED ($image): $*" >&2; exit 1; } +step() { echo "--- $*"; } + +prefix="laravel-rust-smoke-$$" +work=$(mktemp -d) +uid=$(id -u) + +cleanup() { + docker rm -f "$prefix-app" "$prefix-db" >/dev/null 2>&1 || true + docker network rm "$prefix" >/dev/null 2>&1 || true + for v in registry git build; do + docker volume rm "$prefix-cargo-$v" >/dev/null 2>&1 || true + done + # The app's files belong to $uid, but a failed run can leave some that + # don't; remove them as root from inside a container to be sure. + docker run --rm --user 0 -v "$work:/w" --entrypoint sh "$image" -c 'rm -rf /w/* /w/.[!.]*' >/dev/null 2>&1 || true + rm -rf "$work" || true +} +trap cleanup EXIT + +step "toolchain" +docker run --rm --entrypoint sh "$image" -c ' + set -e + cargo --version; rustc --version; cargo fmt --version; cargo clippy --version + node --version; npm --version + laravel --version + command -v tini +' || fail "a tool is missing or doesn't run" +image_uid=$(docker run --rm --entrypoint id "$image" -u) || fail "id did not run" +[ "$image_uid" != 0 ] || fail "runs as root by default" + +step "services" +docker network create "$prefix" >/dev/null +docker run -d --name "$prefix-db" --network "$prefix" \ + -e POSTGRES_USER=app -e POSTGRES_PASSWORD=app -e POSTGRES_DB=app \ + postgres:17-alpine >/dev/null +for v in registry git build; do + docker volume create "$prefix-cargo-$v" >/dev/null +done +volumes=( + -v "$prefix-cargo-registry:/usr/local/cargo/registry" + -v "$prefix-cargo-git:/usr/local/cargo/git" + -v "$prefix-cargo-build:/usr/local/cargo/build" +) +env=( + -e APP_URL=https://example-app.test + -e DATABASE_URL="postgres://app:app@$prefix-db/app" +) + +# The calling user's UID in group 0, as Ingot runs it. On a GitHub runner +# that UID is 1001, not the image's default 1000, which is the point: the +# cache folders and HOME must work for any UID in group 0. +step "laravel new (as $uid:0)" +docker run --rm --user "$uid:0" -v "$work:/work" -w /work "${volumes[@]}" \ + "$image" laravel new example-app --rust /dev/null && break + sleep 1 +done +docker exec "$prefix-db" pg_isready -h 127.0.0.1 -q -U app -d app || fail "Postgres didn't start" + +step "laravel migrate without laravel dev" +docker run --rm --user "$uid:0" --network "$prefix" -v "$app:/app" \ + "${volumes[@]}" "${env[@]}" "$image" laravel migrate --force \ + || fail "laravel migrate failed" +[ ! -e "$app/node_modules" ] || fail "laravel migrate installed node_modules" + +step "laravel dev" +docker run -d --name "$prefix-app" --user "$uid:0" --network "$prefix" \ + -p 127.0.0.1::80 -v "$app:/app" "${volumes[@]}" "${env[@]}" "$image" >/dev/null +port=$(docker port "$prefix-app" 80/tcp | head -n1 | sed 's/.*://') +url="http://127.0.0.1:$port/up" + +wait_up() { + local timeout=$1 start code + start=$(date +%s) + while :; do + code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$url" || true) + [ "$code" = 200 ] && return 0 + [ -n "$(docker ps -q -f "name=^$prefix-app\$")" ] || return 1 + [ $(( $(date +%s) - start )) -lt "$timeout" ] || return 1 + sleep 5 + done +} + +start=$(date +%s) +if ! wait_up "$up_timeout"; then + docker logs --tail 60 "$prefix-app" >&2 || true + fail "/up did not answer 200 within ${up_timeout}s" +fi +echo "/up answered 200 after $(( $(date +%s) - start ))s" + +[[ "$(logs)" == *"docker-entrypoint: node_modules isn't installed"* ]] \ + || fail "the entrypoint didn't install node_modules" +for path in target node_modules; do + owner=$(stat -c %u "$app/$path") || fail "$path is missing" + [ "$owner" = "$uid" ] || fail "$path belongs to UID $owner, not $uid" +done + +step "restart on an edit to src/" +main=$(grep -rl 'fn main' "$app/src" | head -n1) +[ -n "$main" ] || fail "no fn main in src/" +since=$(date +%s) +echo "// smoke test edit" >>"$main" +start=$(date +%s) +restarted= +while [ $(( $(date +%s) - start )) -lt "$restart_timeout" ]; do + # The old server keeps answering /up until nodemon has killed it, so + # wait for cargo to finish the new build after the restart too. + recent=$(logs --since "$since") + if [[ "$recent" == *'restarting due to changes'* && "${recent#*restarting due to changes}" == *Finished* ]]; then + restarted=1 + break + fi + sleep 2 +done +if [ -z "$restarted" ]; then + docker logs --tail 40 "$prefix-app" >&2 || true + fail "the server didn't restart within ${restart_timeout}s of an edit" +fi +if ! wait_up "$restart_timeout"; then + docker logs --tail 40 "$prefix-app" >&2 || true + fail "/up did not answer 200 again after the restart" +fi +echo "restarted after $(( $(date +%s) - start ))s" + +step "docker stop" +start=$(date +%s) +docker stop "$prefix-app" >/dev/null +took=$(( $(date +%s) - start )) +# docker stop's own timeout is 10s; reaching it means the signal didn't get +# through and the processes were killed. +[ "$took" -lt 5 ] || fail "docker stop took ${took}s" +echo "stopped in about ${took}s" + +echo "smoke test passed: $image" diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..9314527 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,170 @@ +name: Build + +# Builds the Laravel for Rust dev image on a native runner for each +# architecture and boots it with a new app (.github/scripts/smoke-test.sh). +# +# Publishing is off until the repository variable PUBLISH_IMAGES is "true" +# (Settings > Secrets and variables > Actions > Variables). With it on, a +# push to main, the weekly rebuild or a manual run on main also pushes each +# architecture's image by digest before its smoke test, and tags the +# multi-arch image only once both have passed. Pull requests never publish. +on: + pull_request: + paths-ignore: ["**.md"] + push: + branches: [main] + paths-ignore: ["**.md"] + # Weekly rebuild, so fixes in the rust and node base images and Debian's + # packages reach the tag without a Dockerfile change. Scheduled runs skip + # the layer cache. + schedule: + - cron: "0 11 * * 1" # Mondays 11:00 UTC + workflow_dispatch: + +# A newer push supersedes whatever this workflow is still building for an +# older commit of the same branch or pull request. On main a running run +# is never cancelled, because it could stop its publish job between the +# `dev` and `dev-` tags; a newer run waits for it (and a run still +# waiting is replaced by a newer one, so that commit gets no `dev-`). +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} + +env: + REGISTRY: ghcr.io + IMAGE_NAME: ${{ github.repository_owner }}/laravel-rust + # Only from main: a manual run on another branch must not move `dev`. + PUBLISH: ${{ vars.PUBLISH_IMAGES == 'true' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + +jobs: + build: + name: build (${{ matrix.arch }}) + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }} + # A hung laravel new or npm install would otherwise hold the runner + # for GitHub's 6-hour default. + timeout-minutes: 45 + permissions: + contents: read + packages: write + strategy: + fail-fast: false + matrix: + arch: [amd64, arm64] + steps: + - name: Checkout code + uses: actions/checkout@v7 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + + - name: Build + id: build_local + if: ${{ env.PUBLISH != 'true' }} + uses: docker/build-push-action@v7 + with: + context: laravel-rust + file: laravel-rust/Dockerfile.dev + platforms: linux/${{ matrix.arch }} + load: true + tags: laravel-rust:test + no-cache: ${{ github.event_name == 'schedule' }} + cache-from: type=gha,scope=laravel-rust-dev-${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=laravel-rust-dev-${{ matrix.arch }} + + - name: Log in to GHCR + if: ${{ env.PUBLISH == 'true' }} + uses: docker/login-action@v4 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + # By digest only, with no tag: the smoke test below runs this exact + # image, and the merge job tags it only if both architectures pass. + - name: Build and push by digest + id: build_push + if: ${{ env.PUBLISH == 'true' }} + uses: docker/build-push-action@v7 + with: + context: laravel-rust + file: laravel-rust/Dockerfile.dev + platforms: linux/${{ matrix.arch }} + outputs: type=image,name=${{ env.REGISTRY }}/${{ env.IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true + no-cache: ${{ github.event_name == 'schedule' }} + cache-from: type=gha,scope=laravel-rust-dev-${{ matrix.arch }} + cache-to: type=gha,mode=max,scope=laravel-rust-dev-${{ matrix.arch }} + + - name: Smoke test + env: + IMAGE: ${{ env.PUBLISH == 'true' && format('{0}/{1}@{2}', env.REGISTRY, env.IMAGE_NAME, steps.build_push.outputs.digest) || 'laravel-rust:test' }} + run: .github/scripts/smoke-test.sh "$IMAGE" + + - name: Export digest + if: ${{ env.PUBLISH == 'true' }} + env: + DIGEST: ${{ steps.build_push.outputs.digest }} + run: | + mkdir -p /tmp/digests + touch "/tmp/digests/${DIGEST#sha256:}" + + - name: Upload digest + if: ${{ env.PUBLISH == 'true' }} + uses: actions/upload-artifact@v4 + with: + name: digest-laravel-rust-dev-${{ matrix.arch }} + path: /tmp/digests/* + if-no-files-found: error + retention-days: 1 + + # Puts the two tested digests under one multi-arch tag. + publish: + needs: build + if: ${{ vars.PUBLISH_IMAGES == 'true' && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }} + runs-on: ubuntu-latest + timeout-minutes: 10 + # One publish at a time, across all runs. + concurrency: + group: publish-laravel-rust-dev + cancel-in-progress: false + permissions: + contents: read + packages: write + steps: + # Exact artifact names: a missing architecture fails here instead of + # publishing a single-arch tag. + - name: Download digest (amd64) + uses: actions/download-artifact@v4 + with: + path: /tmp/digests/amd64 + name: digest-laravel-rust-dev-amd64 + + - name: Download digest (arm64) + uses: actions/download-artifact@v4 + with: + path: /tmp/digests/arm64 + name: digest-laravel-rust-dev-arm64 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + + - name: Log in to GHCR + uses: docker/login-action@v4 + with: + registry: ${{ env.REGISTRY }} + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + # `dev` is the tag Ingot runs (project.LaravelRustImage); `dev-` + # pins this exact build. + - name: Create manifest list and push + working-directory: /tmp/digests + run: | + test "$(find amd64 -type f | wc -l)" -eq 1 + test "$(find arm64 -type f | wc -l)" -eq 1 + amd64=$(find amd64 -type f -printf '%f') + arm64=$(find arm64 -type f -printf '%f') + docker buildx imagetools create \ + -t "$REGISTRY/$IMAGE_NAME:dev" \ + -t "$REGISTRY/$IMAGE_NAME:dev-$GITHUB_SHA" \ + "$REGISTRY/$IMAGE_NAME@sha256:${amd64}" \ + "$REGISTRY/$IMAGE_NAME@sha256:${arm64}" diff --git a/README.md b/README.md index bafbd3a..f048fbc 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,37 @@ # docker-rust Docker images for Rust apps, made for local development with [Ingot](https://github.com/aliasproject/ingot). The PHP images live in [docker-php](https://github.com/aliasproject/docker-php). + +| Image | Folder | Tag | +|---|---|---| +| Laravel for Rust dev image | `laravel-rust/` | `ghcr.io/aliasproject/laravel-rust:dev` (not published yet) | + +## Laravel for Rust dev image + +`laravel-rust/Dockerfile.dev` is a development image for [Laravel for Rust](https://laravel.com/rust/docs) apps (the `laravel-rust` crate), as Ingot runs them. Build it from its folder: + +```sh +docker build -f laravel-rust/Dockerfile.dev -t laravel-rust:dev laravel-rust +``` + +It has Rust 1.99 with `rustfmt` and `clippy`, Node 24, and the Laravel CLI 0.3.0. The CLI is a pinned release archive, checked against the release's `sha256.sum`. The image is Debian-based because the CLI has no Alpine build for arm64. + +The project is mounted at `/app`, and the container runs `laravel dev`, which runs the app's `npm run dev`. In an app made with `laravel new`, that script runs three processes: the server, which `nodemon` restarts with `cargo run` when `src/`, `Cargo.toml`, `Cargo.lock` or `.env` changes; a queue worker; and Vite. If `node_modules` isn't installed, the container's own `laravel dev` command installs it first. Other commands, such as `laravel migrate`, don't, and neither does `laravel dev` wrapped in a shell or with options before `dev`. After a lockfile change, run `npm ci` in the container yourself. Those packages are built for Linux. On macOS or Windows, where `/app` is your host folder, a host-side `npm run dev` then fails on them, so run npm in the container, or run `npm ci` again on the host before using it there. + +- **Address:** the app listens on `SERVER_HOST=0.0.0.0` and `SERVER_PORT=80`. Real environment variables take precedence over the app's `.env`. +- **User:** run the container as your own UID in group 0 (`--user "$(id -u):0"`), so the files it writes to `/app` (`target/`, `node_modules/`, `public/build/`) belong to you. `HOME` is `/home/app`, writable by group 0. +- **Caches:** `CARGO_HOME` is `/usr/local/cargo`. Mount volumes at its `registry`, `git` and `build` folders to keep downloaded crates and compiled dependencies across containers. New apps compile into `build/`, through Cargo's `build-dir`. The folders exist in the image, writable by group 0, so a new volume mounted there is writable too. Don't mount a volume over `CARGO_HOME` itself: it also holds `cargo` and `rustc`, which the volume would pin to an old version. +- **Stopping:** `tini` is PID 1 and passes `docker stop`'s signal to the whole process group, so `laravel dev` and the processes it runs stop promptly. +- **Console commands:** use `laravel migrate`, `laravel route:list` and so on. + +A Laravel for Rust app ships to production as one release binary, built by the app's own Dockerfile; this image is only for development. + +## Checks and publishing + +`.github/workflows/build.yml` builds the image on a native amd64 runner and a native arm64 runner, on pull requests and pushes to `main` (except changes to Markdown files only), every Monday and on demand. On each, `.github/scripts/smoke-test.sh` makes a new app with `laravel new --rust`, runs it with `laravel dev` as a UID other than the image's default, and checks that `/up` answers, that an edit restarts the server, that the files belong to the calling user and that `docker stop` is prompt. Run it by hand against any local tag: + +```sh +.github/scripts/smoke-test.sh laravel-rust:dev +``` + +Publishing is off. To turn it on, set the repository variable `PUBLISH_IMAGES` to `true`. Then pushes to `main`, the weekly rebuild and manual runs on `main` push each architecture's image by digest, smoke-test that exact image, and tag the pair as `dev` and `dev-` only once both pass. Pull requests never publish. After the first publish, make the `laravel-rust` package public in its GHCR settings, because Ingot pulls without logging in. diff --git a/laravel-rust/Dockerfile.dev b/laravel-rust/Dockerfile.dev new file mode 100644 index 0000000..5e87a4d --- /dev/null +++ b/laravel-rust/Dockerfile.dev @@ -0,0 +1,106 @@ +# syntax=docker/dockerfile:1 +# +# Development image for Laravel for Rust apps (the laravel-rust crate), as +# Ingot runs them: the project is bind-mounted at /app and `laravel dev` +# serves it. That command runs the app's `npm run dev`, which in a new +# Laravel for Rust app restarts `cargo run` on every change to src/, +# Cargo.toml, Cargo.lock or .env, runs a queue worker, and runs Vite. +# +# Build context: this folder. +# +# Not for production: a Laravel for Rust app ships as one release binary +# (see the app's own Dockerfile). +ARG RUST_VERSION=1.99 +ARG NODE_VERSION=24 +FROM node:${NODE_VERSION}-bookworm-slim AS node + +FROM rust:${RUST_VERSION}-bookworm + +LABEL maintainer="Michael Aguiar " + +# The Laravel CLI (`laravel dev`, `laravel migrate`, ...). Pinned to a +# release of laravel/cli-releases and checked against its published +# sha256.sum, instead of piping laravel.com/install.sh to a shell. There +# are only glibc builds for arm64, which is why this image is Debian, not +# Alpine. +ARG LARAVEL_CLI_VERSION=0.3.0 +ARG LARAVEL_CLI_SHA256_AMD64=b9271c4f929a24875c915681fe0d004139e004d4d4ade95c743569066b98ce69 +ARG LARAVEL_CLI_SHA256_ARM64=005faf367ee41acd30b39bf7e86654fa37474c67ad662ec86392e48932840525 +ARG TARGETARCH + +# Node and npm for Vite, copied from the official image (same Debian +# release, so the same glibc). +COPY --from=node /usr/local/bin/node /usr/local/bin/node +COPY --from=node /usr/local/lib/node_modules /usr/local/lib/node_modules + +RUN set -eux; \ + ln -s ../lib/node_modules/npm/bin/npm-cli.js /usr/local/bin/npm; \ + ln -s ../lib/node_modules/npm/bin/npx-cli.js /usr/local/bin/npx; \ + node --version; npm --version; \ + \ + # TARGETARCH is only set by BuildKit; the legacy builder leaves it empty. + arch="${TARGETARCH:-$(dpkg --print-architecture)}"; \ + case "$arch" in \ + amd64) target=x86_64-unknown-linux-gnu; sha256=$LARAVEL_CLI_SHA256_AMD64 ;; \ + arm64) target=aarch64-unknown-linux-gnu; sha256=$LARAVEL_CLI_SHA256_ARM64 ;; \ + *) echo "unsupported architecture: $arch" >&2; exit 1 ;; \ + esac; \ + archive="laravel-cli-$target.tar.xz"; \ + curl -fsSLo "/tmp/$archive" "https://github.com/laravel/cli-releases/releases/download/v$LARAVEL_CLI_VERSION/$archive"; \ + echo "$sha256 /tmp/$archive" | sha256sum -c -; \ + mkdir /tmp/laravel-cli; \ + tar -xJf "/tmp/$archive" -C /tmp/laravel-cli; \ + install -m 0755 "$(find /tmp/laravel-cli -type f -name laravel | head -n1)" /usr/local/bin/laravel; \ + rm -rf /tmp/laravel-cli "/tmp/$archive"; \ + laravel --version; \ + \ + rustup component add rustfmt clippy; \ + # The official image leaves RUSTUP_HOME world-writable so any user can + # install a toolchain or component (an app's rust-toolchain.toml can ask + # for one); keep that true for what was just added as root. Only the + # files that aren't yet: a chmod on the rest could copy the whole + # toolchain into this layer. + find "$RUSTUP_HOME" ! -perm -o+w -exec chmod a+w {} +; \ + \ + # tini runs as PID 1 and (with -g) passes signals to the whole process + # group, so `docker stop` (and Ingot's idle stop) reaches laravel dev + # and its nodemon and cargo children instead of waiting out the timeout + # and killing them mid-build. + apt-get update; \ + apt-get install -y --no-install-recommends tini; \ + rm -rf /var/lib/apt/lists/*; \ + \ + # Ingot mounts shared volumes at these folders so downloaded crates and + # compiled dependencies outlive the container (new Laravel for Rust apps + # set Cargo's build-dir to {cargo-cache-home}/build/laravel-rust). A new + # volume takes the ownership and mode of the folder it is mounted on, + # and the container runs as the host user's UID in group 0, so the + # folders must exist here, writable by group 0. (The rest of CARGO_HOME + # is already world-writable in the official image.) + mkdir -p "$CARGO_HOME/registry" "$CARGO_HOME/git" "$CARGO_HOME/build"; \ + chgrp 0 "$CARGO_HOME/registry" "$CARGO_HOME/git" "$CARGO_HOME/build"; \ + chmod 2775 "$CARGO_HOME/registry" "$CARGO_HOME/git" "$CARGO_HOME/build"; \ + \ + # A home for whatever UID the container runs as: npm's cache and the + # Laravel CLI's config live under $HOME. + mkdir -p /home/app; \ + chgrp 0 /home/app; \ + chmod 2775 /home/app + +ENV HOME=/home/app \ + SERVER_HOST=0.0.0.0 \ + SERVER_PORT=80 + +WORKDIR /app + +# Ingot runs the container as the host user's UID in group 0, so files the +# app writes to /app (target/, public/build/, storage/) belong to that +# user. Without Ingot, pass --user "$(id -u):0" for the same. +USER 1000:0 + +COPY docker-entrypoint /usr/local/bin/docker-entrypoint + +EXPOSE 80 + +ENTRYPOINT ["tini", "-g", "--", "docker-entrypoint"] +CMD ["laravel", "dev"] diff --git a/laravel-rust/docker-entrypoint b/laravel-rust/docker-entrypoint new file mode 100755 index 0000000..52ea2b1 --- /dev/null +++ b/laravel-rust/docker-entrypoint @@ -0,0 +1,20 @@ +#!/bin/sh +# `laravel dev` runs the app's `npm run dev` (server, queue worker and Vite +# under concurrently and nodemon), so it needs node_modules, and nothing +# else installs them in a project that was cloned rather than made with +# `laravel new`. Install them before `laravel dev` when npm hasn't (no +# node_modules/.package-lock.json, which npm writes once an install has +# finished). Other commands (`laravel migrate`, a shell) start as they are. +# After a lockfile change, run `npm ci` in the container yourself. +set -e + +if [ "$1" = laravel ] && [ "$2" = dev ] && [ -f package.json ] && [ ! -f node_modules/.package-lock.json ]; then + echo "docker-entrypoint: node_modules isn't installed, installing it" >&2 + if [ -f package-lock.json ]; then + npm ci --no-audit --no-fund + else + npm install --no-audit --no-fund + fi +fi + +exec "$@"