chore: GitHub workflow to auto-deploy PRs to Cloudflare (#880)

* feat: add Cloudflare Containers PR preview deployments

Add GitHub workflows to automatically deploy PRs to Cloudflare
Containers after tests pass, with automatic cleanup after 24 hours.

Components:
- workers/preview/: Cloudflare Worker entry point that routes
  traffic to the Rails container
- preview-deploy.yml: Deploys PRs after CI passes, comments
  preview URL on PR
- preview-cleanup.yml: Cleans up previews on PR close or after
  24 hours via scheduled job

The container sleeps after 30 minutes of inactivity and wakes
automatically on the next request.

Required secrets:
- CLOUDFLARE_API_TOKEN
- CLOUDFLARE_ACCOUNT_ID
- CLOUDFLARE_WORKERS_SUBDOMAIN

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: use development environment with embedded PostgreSQL for previews

- Add preview-specific Dockerfile with PostgreSQL server included
- Add docker-entrypoint.sh to start PostgreSQL and run migrations
- Change RAILS_ENV from production to development
- Auto-generate SECRET_KEY_BASE and DATABASE_URL for self-contained previews

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* feat: add Redis to preview container

- Install redis-server in the preview Dockerfile
- Start Redis in the entrypoint before PostgreSQL
- Auto-configure REDIS_URL for Sidekiq background jobs

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: mark GitHub deployment inactive on manual PR cleanup

When using workflow_dispatch with a specific pr_number, the workflow
now also marks the associated GitHub deployment as inactive, mirroring
the behavior of the batch cleanup path.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: remove npm cache config that requires missing lockfile

The setup-node action's cache feature requires a package-lock.json
which doesn't exist in workers/preview/. Remove the cache configuration
to fix the workflow.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: only update deployment status when deployment ID exists

Add condition to check steps.deployment.outputs.result exists before
attempting to update deployment status. This prevents a JavaScript
syntax error when the deployment step fails and no ID is available.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: quote shell variables to fix SC2086 shellcheck warning

Quote the --var argument and GITHUB_OUTPUT redirection to prevent
word splitting issues.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: add permissions for deployment status operations

Add deployments: write permission to the cleanup workflow so the
GITHUB_TOKEN can list and update deployment statuses.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: specify build context for Dockerfile in wrangler config

Use object syntax for image config to set build context to repository
root, allowing the Dockerfile to reference files from both the root
(Gemfile, .ruby-version) and workers/preview/ (docker-entrypoint.sh).

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: run wrangler from repo root for correct build context

- Update workflow to run wrangler with --config flag from repo root
- Update wrangler.toml paths (main, image) to be relative to repo root
- Embed entrypoint script directly in Dockerfile using heredoc
- Remove separate docker-entrypoint.sh file

This ensures the Docker build context includes Gemfile, .ruby-version,
and other files at the repo root.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: move preview Dockerfile to repo root for correct build context

Wrangler resolves paths relative to the config file, not the current
directory. Moving Dockerfile.preview to repo root ensures:
- Build context is the repo root (where Gemfile, .ruby-version are)
- Path in wrangler.toml is ../../Dockerfile.preview (relative to config)
- Worker runs from workers/preview/ directory again

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: use find to locate pg_hba.conf instead of glob in redirection

Shell glob patterns don't work with redirection operators. Use find
to locate the actual pg_hba.conf path before writing to it.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix: enable workers_dev for preview deployments

Add workers_dev = true to make the preview worker accessible via
the workers.dev subdomain.

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* feat: enable observability for container logs

https://claude.ai/code/session_013EZuzBxWPEEYp3TQptXWdP

* fix preview container boot path

* fix: set preview container startup command explicitly

* fix: update preview worker compatibility date

* chore: expose preview container diagnostics

* fix: recover from stale preview container state

* fix: harden preview container startup paths

* chore: report preview startup stages

* fix: bypass stale container helper state during recovery

* fix: allow longer preview container startup

* fix: upgrade preview container runtime

* fix: use supported node version for preview deploy

* fix: use public container startup flow

* fix: simplify preview container startup

* chore: retain preview container diagnostic history

* fix: bypass systemctl redirect for postgres startup

* chore: probe rails readiness from inside preview container

* chore: capture rails process and port diagnostics

* chore: capture rails startup logs on preview timeout

* fix: align preview bind behavior with ipv6 startup model

* chore: capture preview socket state on rails timeout

* chore: capture rails wait state and child processes

* fix: launch preview with puma directly

* fix: run preview in production mode

* chore: probe preview app boot before puma

* fix: disable lookbook routes in production preview

* chore: capture ruby backtrace from hung boot probe

* fix: disable bootsnap in preview runtime

* fix: disable sidekiq web routes in production preview

* chore: trace hung preview boot probe with strace

* fix: json-escape preview telemetry payloads

* fix: pass preview telemetry env vars correctly

* chore: signal ruby child for preview boot backtrace

* fix: allow longer preview cold-start budget

* fix: skip sidekiq web requires in production preview

* chore: deploy hello world preview container

* fix(preview): restore rails image without redundant warmup

* feat(preview): seed demo dataset on boot

* ci(preview): require preview-cf label

* ci(preview): reuse pr workflow checks

* fix(preview): avoid clearing demo data in production boot

* fix(preview): tolerate already-running postgres on boot

* fix(preview): check demo user via psql during boot

* fix(preview): defer heavy demo seed until after boot

* fix(preview): move demo-user creation after rails boot

* fix(preview): fail fast on container lifecycle errors

* fix(preview): validate manual cleanup pr input

* fix(preview): parameterize preview pr number

* ci(preview): use setup-node v6

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: KiloClaw <kiloclaw@openclaw.ai>
This commit is contained in:
Juan José Mata
2026-05-15 23:14:20 +02:00
committed by GitHub
parent 495d8a223d
commit 6a765a90c6
9 changed files with 2414 additions and 4 deletions

182
.github/workflows/preview-deploy.yml vendored Normal file
View File

@@ -0,0 +1,182 @@
name: Deploy PR Preview
on:
pull_request:
types: [opened, synchronize, reopened, labeled, unlabeled]
paths-ignore:
- 'charts/**'
- 'docs/**'
- '*.md'
jobs:
deploy-preview:
if: contains(github.event.pull_request.labels.*.name, 'preview-cf')
name: Deploy to Cloudflare Containers
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
actions: read
contents: read
pull-requests: write
deployments: write
steps:
- name: Wait for PR CI to pass
uses: actions/github-script@v7
with:
script: |
const headSha = context.payload.pull_request.head.sha;
const timeoutMs = 10 * 60 * 1000;
const pollMs = 15 * 1000;
const startedAt = Date.now();
let lastState = 'not found';
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
while (Date.now() - startedAt < timeoutMs) {
const { data } = await github.rest.actions.listWorkflowRunsForRepo({
owner: context.repo.owner,
repo: context.repo.repo,
event: 'pull_request',
head_sha: headSha,
per_page: 20,
});
const prRun = data.workflow_runs.find((run) => run.name === 'Pull Request' && run.head_sha === headSha);
if (prRun) {
lastState = `${prRun.status}/${prRun.conclusion ?? 'pending'}`;
core.info(`Pull Request workflow ${prRun.id}: ${lastState}`);
if (prRun.status === 'completed') {
if (prRun.conclusion === 'success') {
return;
}
core.setFailed(`Pull Request workflow concluded with ${prRun.conclusion}`);
return;
}
}
await sleep(pollMs);
}
core.setFailed(`Timed out waiting for Pull Request workflow for ${headSha}. Last state: ${lastState}`);
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v6
with:
node-version: "24"
- name: Install Wrangler dependencies
working-directory: workers/preview
run: npm install
- name: Configure preview files for this PR
working-directory: workers/preview
run: |
sed -i "s/\${PR_NUMBER}/${{ github.event.pull_request.number }}/g" wrangler.toml
sed -i "s/\${PR_NUMBER}/${{ github.event.pull_request.number }}/g" src/index.ts
cat wrangler.toml
- name: Create GitHub Deployment
id: deployment
uses: actions/github-script@v7
with:
script: |
const deployment = await github.rest.repos.createDeployment({
owner: context.repo.owner,
repo: context.repo.repo,
ref: context.payload.pull_request.head.sha,
environment: `preview-pr-${{ github.event.pull_request.number }}`,
auto_merge: false,
required_contexts: [],
description: 'PR Preview Deployment'
});
return deployment.data.id;
result-encoding: string
- name: Deploy to Cloudflare Containers
id: deploy
working-directory: workers/preview
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
run: |
npx wrangler deploy --var "PR_NUMBER:${{ github.event.pull_request.number }}"
# Get the deployment URL
PREVIEW_URL="https://sure-preview-${{ github.event.pull_request.number }}.${{ secrets.CLOUDFLARE_WORKERS_SUBDOMAIN }}.workers.dev"
echo "preview_url=${PREVIEW_URL}" >> "$GITHUB_OUTPUT"
- name: Update Deployment Status
if: always() && steps.deployment.outputs.result
uses: actions/github-script@v7
with:
script: |
const state = '${{ job.status }}' === 'success' ? 'success' : 'failure';
await github.rest.repos.createDeploymentStatus({
owner: context.repo.owner,
repo: context.repo.repo,
deployment_id: ${{ steps.deployment.outputs.result }},
state: state,
environment_url: state === 'success' ? '${{ steps.deploy.outputs.preview_url }}' : undefined,
description: state === 'success' ? 'Preview deployed successfully' : 'Preview deployment failed'
});
- name: Comment on PR
if: success()
uses: actions/github-script@v7
with:
script: |
const previewUrl = '${{ steps.deploy.outputs.preview_url }}';
const commentBody = `## 🚀 Preview Deployment Ready
Your preview environment has been deployed to Cloudflare Containers.
**Preview URL:** ${previewUrl}
> ⏰ This preview is intended to be cleaned up after **24 hours** of the last deployment once the cleanup workflow is live on the default branch.
> 💤 The container will sleep after 30 minutes of inactivity and wake on the next request.
---
<sub>Deployed from commit ${{ github.event.pull_request.head.sha }}</sub>`;
// Find existing comment
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: ${{ github.event.pull_request.number }}
});
const botComment = comments.find(comment =>
comment.user.type === 'Bot' &&
comment.body.includes('Preview Deployment Ready')
);
if (botComment) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: botComment.id,
body: commentBody
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: ${{ github.event.pull_request.number }},
body: commentBody
});
}
- name: Store cleanup metadata
if: success()
uses: actions/upload-artifact@v4
with:
name: preview-cleanup-pr-${{ github.event.pull_request.number }}
path: |
workers/preview/wrangler.toml
retention-days: 2