From 49c6cd4142ca139c9440c7bbba8b16b07a0f1e34 Mon Sep 17 00:00:00 2001 From: Carlos Jorge Date: Mon, 30 Nov 2026 17:57:51 +0000 Subject: [PATCH] feat(deploy): one image for every environment, configured at runtime The image takes no environment's values at build time. Its entrypoint checks ENVIRONMENT (staging or production) and nginx writes it into every HTML page as window.__DOCS_ENV__; the browser picks the Mixpanel project from it. Links to (www.|staging.)thegraph.com follow the page's own origin after mount. image.yml builds ghcr.io/graphprotocol/graph-docs ( on every run, latest from the default branch), checks the runtime environment, and pushes. release.yml gives a v* tag of a default-branch commit that commit's image digest under the tag's name, without rebuilding. ci-cd-production.yml is unchanged; .k8s/production sets ENVIRONMENT=production. Co-Authored-By: Claude Opus 5.5 --- .github/scripts/check-runtime-env.sh | 58 ++++++++++ .github/workflows/ci-cd-pull-request.yml | 12 ++- .github/workflows/ci-cd-staging.yml | 53 ---------- .github/workflows/image.yml | 67 ++++++++++++ .github/workflows/release.yml | 129 +++++++++++++++++++++++ .k8s/production/deployment.yaml | 7 ++ .k8s/staging/deployment.yaml | 12 +++ .k8s/staging/kustomization.yaml | 2 + Dockerfile | 10 +- docker-entrypoint.sh | 22 ++++ nginx.conf | 3 + package.json | 4 +- website/.env | 2 - website/next.config.js | 10 +- website/src/pages/_app.tsx | 18 +++- website/src/runtimeEnv.ts | 30 ++++++ 16 files changed, 360 insertions(+), 79 deletions(-) create mode 100755 .github/scripts/check-runtime-env.sh delete mode 100644 .github/workflows/ci-cd-staging.yml create mode 100644 .github/workflows/image.yml create mode 100644 .github/workflows/release.yml create mode 100644 .k8s/staging/deployment.yaml create mode 100755 docker-entrypoint.sh create mode 100644 website/src/runtimeEnv.ts diff --git a/.github/scripts/check-runtime-env.sh b/.github/scripts/check-runtime-env.sh new file mode 100755 index 000000000000..894fe8939db9 --- /dev/null +++ b/.github/scripts/check-runtime-env.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# Checks that the docs image takes its environment at runtime (docker-entrypoint.sh): +# - the image's configuration names no environment; +# - for staging and production, the container serves pages that carry that environment right +# after (window.__DOCS_ENV__); +# - without ENVIRONMENT, or with a value other than those two, the container exits instead. +# Usage: check-runtime-env.sh IMAGE (DOCKER selects the client; docker by default). +set -eu + +image="$1" +docker="${DOCKER:-docker}" +container="" + +fail() { + echo "check-runtime-env: $*" >&2 + exit 1 +} + +cleanup() { + if [ -n "$container" ]; then "$docker" rm -f "$container" >/dev/null; fi +} +trap cleanup EXIT + +config_env=$("$docker" image inspect --format '{{range .Config.Env}}{{println .}}{{end}}' "$image") +if printf '%s\n' "$config_env" | grep -E '^(ENVIRONMENT|ORIGIN)='; then + fail "the image sets an environment's value" +fi + +for environment in staging production; do + container=$("$docker" run -d -e ENVIRONMENT="$environment" -p 127.0.0.1::80 "$image") + port=$("$docker" port "$container" 80/tcp | head -n 1 | sed 's/.*://') + expected="" + for path in /docs/en/ /docs/en/about/; do + page="" + attempt=0 + until page=$(curl -fsS "http://127.0.0.1:$port$path"); do + attempt=$((attempt + 1)) + [ "$attempt" -lt 30 ] || fail "$environment: no answer on $path" + sleep 1 + done + case "$page" in + *"$expected"*) echo "check-runtime-env: $environment: $path carries its environment" ;; + *) fail "$environment: $path does not start its with $expected" ;; + esac + done + "$docker" rm -f "$container" >/dev/null + container="" +done + +if "$docker" run --rm "$image" true; then + fail "the container started without ENVIRONMENT" +fi +for value in "" local prod; do + if "$docker" run --rm -e ENVIRONMENT="$value" "$image" true; then + fail "the container started with ENVIRONMENT='$value'" + fi +done +echo "check-runtime-env: without a valid ENVIRONMENT the container exits" diff --git a/.github/workflows/ci-cd-pull-request.yml b/.github/workflows/ci-cd-pull-request.yml index cc6efa51a0d9..0805547df75b 100644 --- a/.github/workflows/ci-cd-pull-request.yml +++ b/.github/workflows/ci-cd-pull-request.yml @@ -3,7 +3,7 @@ name: Pull Request CI/CD on: pull_request env: - BASE_IMAGE: ghcr.io/graphprotocol/graph-docs-staging + IMAGE: ghcr.io/graphprotocol/graph-docs jobs: lint: @@ -100,8 +100,10 @@ jobs: uses: docker/build-push-action@v5 with: context: . # required to respect .dockerignore - cache-from: type=registry,ref=${{ env.BASE_IMAGE }}:latest - build-args: | - ENVIRONMENT=staging - ORIGIN=https://staging.thegraph.com + cache-from: type=registry,ref=${{ env.IMAGE }}:latest + tags: ${{ env.IMAGE }}:${{ github.sha }} + load: true push: false + + - name: Check the runtime environment + run: .github/scripts/check-runtime-env.sh "$IMAGE:$GITHUB_SHA" diff --git a/.github/workflows/ci-cd-staging.yml b/.github/workflows/ci-cd-staging.yml deleted file mode 100644 index 991689716364..000000000000 --- a/.github/workflows/ci-cd-staging.yml +++ /dev/null @@ -1,53 +0,0 @@ -name: Staging CI/CD - -on: - workflow_dispatch: - push: - branches: - - main - -# Builds the staging image and pushes it to ghcr.io; it deploys nothing. -# Staging runs on stg-apps-us-central1, delivered by Argo CD and Kargo from -# graphprotocol/graph-infra: Kargo follows this image's `latest` tag, which only -# builds of the default branch move. - -permissions: - actions: write # cancel-workflow-action - contents: read - packages: write - -env: - BASE_IMAGE: ghcr.io/graphprotocol/graph-docs-staging - -jobs: - build: - runs-on: ubuntu-latest - steps: - - name: Cancel Previous Runs - uses: styfle/cancel-workflow-action@0.12.1 - with: - access_token: ${{ github.token }} - - - name: Check out the repo - uses: actions/checkout@v4 - - - name: Log in to GitHub Container Registry - uses: docker/login-action@v3 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - - name: Build and push Docker image - uses: docker/build-push-action@v5 - with: - context: . # required to respect .dockerignore - cache-from: type=registry,ref=${{ env.BASE_IMAGE }}:latest - cache-to: type=inline - build-args: | - ENVIRONMENT=staging - ORIGIN=https://staging.thegraph.com - tags: | - ${{ env.BASE_IMAGE }}:${{ github.sha }} - ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && format('{0}:latest', env.BASE_IMAGE) || '' }} - push: true diff --git a/.github/workflows/image.yml b/.github/workflows/image.yml new file mode 100644 index 000000000000..cd33f4f9dae6 --- /dev/null +++ b/.github/workflows/image.yml @@ -0,0 +1,67 @@ +name: Image + +on: + workflow_dispatch: + push: + branches: + - main + +# Builds the docs image, ghcr.io/graphprotocol/graph-docs, and pushes it to ghcr.io; it deploys +# nothing. The image is the same for every environment: the build takes no environment's values, +# and each deployment sets the container's ENVIRONMENT (docker-entrypoint.sh). Every run pushes +# ; only builds of the default branch move latest. +# Staging runs on stg-apps-us-central1, delivered by Argo CD and Kargo from +# graphprotocol/graph-infra: Kargo follows latest. A v* tag releases a commit's image under the +# tag's name (release.yml). + +# Runs of one branch build one at a time and in order, so latest only moves forward. A run is not +# cancelled: every commit it builds keeps its image, which a release tags. +concurrency: + group: image-${{ github.ref }} + cancel-in-progress: false + +permissions: + contents: read + packages: write + +env: + IMAGE: ghcr.io/graphprotocol/graph-docs + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Check out the repo + uses: actions/checkout@v4 + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build Docker image + uses: docker/build-push-action@v5 + with: + context: . # required to respect .dockerignore + cache-from: type=registry,ref=${{ env.IMAGE }}:latest + cache-to: type=inline + labels: | + org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }} + org.opencontainers.image.revision=${{ github.sha }} + tags: ${{ env.IMAGE }}:${{ github.sha }} + load: true + + - name: Check the runtime environment + run: .github/scripts/check-runtime-env.sh "$IMAGE:$GITHUB_SHA" + + - name: Push Docker image + env: + LATEST: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + run: | + docker push "$IMAGE:$GITHUB_SHA" + if [ "$LATEST" = true ]; then + docker tag "$IMAGE:$GITHUB_SHA" "$IMAGE:latest" + docker push "$IMAGE:latest" + fi diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000000..4ea4029343a6 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,129 @@ +name: Release + +on: + push: + tags: + - v* + +# A v* tag of a commit on the default branch, once the checks pass, gets an image tag of the same +# name: ghcr.io/graphprotocol/graph-docs: is the digest the default branch's build pushed as +# (image.yml), nothing rebuilt. A version tag never moves to another image, and tags never +# move latest. Production Kargo follows these version tags (graphprotocol/graph-infra). +# ci-cd-production.yml still builds and deploys production from the same tags, separately. + +# Releases run one at a time, and none is cancelled. +concurrency: + group: release + cancel-in-progress: false + +permissions: + contents: read + +env: + IMAGE: ghcr.io/graphprotocol/graph-docs + +jobs: + checks: + runs-on: ubuntu-latest + steps: + - name: Check out the repo + uses: actions/checkout@v4 + + - name: Set up env + uses: the-guild-org/shared-config/setup@v1 + with: + node-version: 22 + + - name: Install dependencies + run: pnpm install + + - name: Lint + run: pnpm lint + + - name: Check formatting + run: pnpm prettier:check + + - name: Typecheck + run: pnpm typecheck + + release: + runs-on: ubuntu-latest + timeout-minutes: 60 + needs: [checks] + permissions: + contents: read + packages: write + steps: + - name: Check the tag + run: | + if ! [[ "$GITHUB_REF_NAME" =~ ^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$ ]]; then + echo "$GITHUB_REF_NAME is not a valid image tag." >&2 + exit 1 + fi + + - name: Check out the repo + uses: actions/checkout@v4 + with: + # The default branch's history, to check the release is on it. + fetch-depth: 0 + filter: blob:none + + - name: Check the release is on the default branch + env: + DEFAULT_BRANCH: ${{ github.event.repository.default_branch }} + run: | + git fetch --no-tags origin "+refs/heads/$DEFAULT_BRANCH:refs/remotes/origin/$DEFAULT_BRANCH" + if ! git merge-base --is-ancestor "$GITHUB_SHA" "origin/$DEFAULT_BRANCH"; then + echo "$GITHUB_REF_NAME ($GITHUB_SHA) is not on $DEFAULT_BRANCH; only its commits are released." >&2 + exit 1 + fi + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Tag the image + run: | + set -o pipefail + tag=$GITHUB_REF_NAME + error=$(mktemp) + # Prints the digest of $1; fails on any registry error, "not found" included. + digest() { + docker buildx imagetools inspect --format '{{.Manifest.Digest}}' "$1" 2> "$error" + } + not_found() { + grep -qiE 'not found|manifest unknown' "$error" + } + # The default branch's build of the commit may still be running when the tag arrives: + # wait for its image, up to 40 minutes. + attempt=0 + until source=$(digest "$IMAGE:$GITHUB_SHA"); do + if ! not_found; then + cat "$error" >&2 + exit 1 + fi + attempt=$((attempt + 1)) + if [ "$attempt" -ge 80 ]; then + echo "$IMAGE:$GITHUB_SHA does not exist: the default branch's build of $GITHUB_SHA pushes it (image.yml)." >&2 + exit 1 + fi + sleep 30 + done + if current=$(digest "$IMAGE:$tag"); then + if [ "$current" != "$source" ]; then + echo "$IMAGE:$tag is already $current, not $source ($GITHUB_SHA); a version tag never moves." >&2 + exit 1 + fi + echo "$IMAGE:$tag is already $source ($GITHUB_SHA)." + exit 0 + elif ! not_found; then + cat "$error" >&2 + exit 1 + fi + # A carbon copy of the manifest: the version tag gets the commit image's digest. + docker buildx imagetools create --prefer-index=false --tag "$IMAGE:$tag" "$IMAGE@$source" + [ "$(digest "$IMAGE:$tag")" = "$source" ] || { echo "$IMAGE:$tag is not $source" >&2; exit 1; } + echo "$IMAGE:$tag: $source ($GITHUB_SHA)" diff --git a/.k8s/production/deployment.yaml b/.k8s/production/deployment.yaml index 3c767e6a87be..38872cbfb5b5 100644 --- a/.k8s/production/deployment.yaml +++ b/.k8s/production/deployment.yaml @@ -4,3 +4,10 @@ metadata: name: graph-docs spec: replicas: 5 + template: + spec: + containers: + - name: app + env: + - name: ENVIRONMENT + value: production diff --git a/.k8s/staging/deployment.yaml b/.k8s/staging/deployment.yaml new file mode 100644 index 000000000000..e11e8ce64cb3 --- /dev/null +++ b/.k8s/staging/deployment.yaml @@ -0,0 +1,12 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: graph-docs +spec: + template: + spec: + containers: + - name: app + env: + - name: ENVIRONMENT + value: staging diff --git a/.k8s/staging/kustomization.yaml b/.k8s/staging/kustomization.yaml index 49c93f07b88d..f3834146d109 100644 --- a/.k8s/staging/kustomization.yaml +++ b/.k8s/staging/kustomization.yaml @@ -4,3 +4,5 @@ bases: - ../base resources: - ingress.yaml +patchesStrategicMerge: + - deployment.yaml diff --git a/Dockerfile b/Dockerfile index 80e857c82e94..79f504a6466c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,7 @@ +# One image for every environment: the build takes no environment's values. The container reads +# ENVIRONMENT when it starts (docker-entrypoint.sh). FROM node:22-alpine AS builder -ARG ENVIRONMENT -ARG ORIGIN - -ENV ENVIRONMENT=$ENVIRONMENT -ENV ORIGIN=$ORIGIN - ENV PNPM_HOME="/usr/bin" ENV NODE_OPTIONS="--max-old-space-size=8192" @@ -24,8 +20,10 @@ RUN pnpm build FROM nginx:1.16.0-alpine COPY --from=builder ./app/nginx.conf /etc/nginx/ +COPY --from=builder /app/docker-entrypoint.sh /docker-entrypoint.sh COPY --from=builder /app/out /usr/share/nginx/html EXPOSE 80/tcp +ENTRYPOINT ["/docker-entrypoint.sh"] CMD ["nginx", "-g", "daemon off;"] diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100755 index 000000000000..87212d5cfdf0 --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# The image's entrypoint, and the only place a deployment's environment enters the docs: the build +# reads none, so every environment runs the same image. It checks ENVIRONMENT, has nginx write it +# into every HTML page it serves (window.__DOCS_ENV__, read by website/src/runtimeEnv.ts), then +# runs the command. Without a valid ENVIRONMENT the container exits and never becomes ready. +set -eu + +case "${ENVIRONMENT:-}" in +staging | production) ;; +*) + echo "docs: ENVIRONMENT must be staging or production, not '${ENVIRONMENT:-}'" >&2 + exit 1 + ;; +esac + +# Included by nginx.conf's server: the script goes right after , ahead of Next's scripts. +cat >/etc/nginx/runtime-env.conf <' ''; +sub_filter_once on; +CONF + +exec "$@" diff --git a/nginx.conf b/nginx.conf index d39b3bacd089..b7ca257952e9 100644 --- a/nginx.conf +++ b/nginx.conf @@ -32,6 +32,9 @@ http { listen 80; root /usr/share/nginx/html; index index.html index.htm; + + # The deployment's environment in every HTML page, written by docker-entrypoint.sh + include /etc/nginx/runtime-env.conf; # Short cache with revalidation add_header Cache-Control "no-cache, must-revalidate"; diff --git a/package.json b/package.json index d9692c0ad8a2..591b6f1a6419 100644 --- a/package.json +++ b/package.json @@ -15,9 +15,9 @@ "prettier:check": "prettier . --check", "typecheck": "turbo run typecheck", "test": "turbo run test", - "docker:build": "source ./website/.env.local && DOCKER_BUILDKIT=1 docker build . -t docs --no-cache --build-arg ENVIRONMENT=$ENVIRONMENT --build-arg ORIGIN=$ORIGIN", + "docker:build": "DOCKER_BUILDKIT=1 docker build . -t docs --no-cache", "docker:clean": "docker builder prune", - "docker:up": "docker run --rm -it -p 3000:80 -v \"$(pwd)/nginx.conf:/etc/nginx/nginx.conf\" docs" + "docker:up": "docker run --rm -it -p 3000:80 -e ENVIRONMENT=staging -v \"$(pwd)/nginx.conf:/etc/nginx/nginx.conf\" docs" }, "devDependencies": { "@edgeandnode/eslint-config": "^2.0.3", diff --git a/website/.env b/website/.env index a2ffa8e76e27..587077ac99d7 100644 --- a/website/.env +++ b/website/.env @@ -1,5 +1,3 @@ -ENVIRONMENT=local -ORIGIN=http://localhost:3000 BASE_PATH=/docs ALGOLIA_API_KEY=9a358df50b02a5b66efeecbc0a2cab3d ALGOLIA_APP_ID=WQ5FYJCL00 diff --git a/website/next.config.js b/website/next.config.js index a9f34a795874..b6a3697427f7 100644 --- a/website/next.config.js +++ b/website/next.config.js @@ -10,18 +10,12 @@ import rehypeUnwrapImages from './dist/mdxPlugins/rehypeUnwrapImages.js' import remarkCallouts from './dist/mdxPlugins/remarkCallouts.js' import remarkTransformRemoteDocs from './dist/mdxPlugins/remarkTransformRemoteDocs.js' +// Inlined at build time, so the same in every environment. What differs by environment is read in +// the browser at runtime (src/runtimeEnv.ts). const env = { - ENVIRONMENT: process.env.ENVIRONMENT, - ORIGIN: process.env.ORIGIN, BASE_PATH: process.env.BASE_PATH, ALGOLIA_API_KEY: process.env.ALGOLIA_API_KEY, ALGOLIA_APP_ID: process.env.ALGOLIA_APP_ID, - MIXPANEL_TOKEN: - process.env.NODE_ENV === 'production' - ? process.env.ENVIRONMENT === 'production' - ? 'cfeac8baf33c9b4d255f28d57f3c9148' // production - : 'e57a9892339b2acfd02943c86b746d32' // staging - : '', // local dev (no tracking) GOOGLE_ANALYTICS_MEASUREMENT_ID: process.env.NODE_ENV === 'production' ? 'G-5MK48LFNKY' : '', } diff --git a/website/src/pages/_app.tsx b/website/src/pages/_app.tsx index c60df1ea74f1..298549b00b60 100644 --- a/website/src/pages/_app.tsx +++ b/website/src/pages/_app.tsx @@ -2,6 +2,7 @@ import mixpanel from 'mixpanel-browser' import type { AppProps } from 'next/app' import NextLink from 'next/link' import { DefaultSeo } from 'next-seo' +import { useEffect, useState } from 'react' import googleAnalytics from 'react-ga4' import { @@ -16,6 +17,7 @@ import { import { CookieBanner } from '@edgeandnode/go' import { supportedLocales, translations } from '@/i18n' +import { mixpanelToken } from '@/runtimeEnv' import '@edgeandnode/gds/style.css' import '@docsearch/css' @@ -33,6 +35,16 @@ const absoluteUrlRegex = /^(?:[a-zA-Z][a-zA-Z\d+.-]*:|\/\/)/ export default function MyApp({ Component, router, pageProps }: AppProps) { const { locale } = extractLocaleFromRouter(router, supportedLocales) + // The origin the page is served from, once mounted, when it is (www.|staging.)thegraph.com: absolute + // links to thegraph.com are rewritten to it, so staging's pages link to staging. Until then, as in the + // pages rendered at build time, links stay as written, so hydration matches. + const [siteOrigin, setSiteOrigin] = useState(null) + useEffect(() => { + if (rootRelativeOrTheGraphUrlRegex.test(window.location.origin)) { + setSiteOrigin(window.location.origin) + } + }, []) + return ( <> { + if (typeof window === 'undefined') return null + const environment = window.__DOCS_ENV__?.ENVIRONMENT + return environment === 'staging' || environment === 'production' ? environment : null +} + +const mixpanelTokens: Record = { + production: 'cfeac8baf33c9b4d255f28d57f3c9148', + staging: 'e57a9892339b2acfd02943c86b746d32', +} + +/** The environment's Mixpanel project; none (no tracking) without an environment. */ +export const mixpanelToken = (): string | null => { + const environment = runtimeEnvironment() + return environment ? mixpanelTokens[environment] : null +}