Pro-Grade Deployment Pipeline & Deployment Recipes
This repository implements a modular, enterprise-grade continuous integration and delivery architecture built around a shared runtime contract. Core CI, immutable release artifact publication, database schema migration, and provider-specific hosting deployment are separated into explicit responsibilities.
For the authoritative specification of container, database, environment variable, reverse proxy, health check, and lifecycle requirements, refer to the Application Runtime Contract. All hosting providers and deployment environments must satisfy this baseline contract.
Deployment State & Optional Vercel Target
- Current Deployment Architecture: The primary deployment architecture is provider-neutral, utilizing standard containerized builds (
Dockerfile) running on Node.js / Docker hosts such as Google Cloud Run or AWS. - Disconnected Vercel Connection: The historical direct Vercel connection is disconnected. Core application code, environment validation, database access, and routing logic do not depend on Vercel-specific runtime environment variables or proprietary APIs.
- Optional Vercel Support: Vercel remains fully supported as an optional deployment target. Couples or developers who wish to deploy on Vercel can import the repository directly into Vercel or use
vercel deploy, ensuring required production environment variables (DATABASE_URL,ADMIN_PASSWORD,ALLOWED_HOSTS,GUEST_PASSCODE,GUEST_SESSION_SECRET) are provided in Vercel's project settings. - Static Showcase & Documentation Targets: For database-free static HTML previews,
npm run build:export(scripts/build-export.mjswithSTATIC_EXPORT=trueandtrailingSlash: true, verified in parallel bystatic-export-buildinci.yml) builds a static showcase inside an isolated staged workspace usingSTATIC_MOCK_CONFIG, deterministic archetype datasets frombuildArchetypeSeedDatainsrc/lib/sampleData/builder.ts, and.next-exportbuild caching. At runtime in the browser,RootLayoutClient(src/components/layout/RootLayoutClient.tsx) mountsDemoProvider(src/components/demo/DemoContext.tsx) andDemoToolbar(src/components/demo/DemoToolbar.tsx), hydratingwedding_showcase_demo_v1localStoragestate viahydrateDemoStateFromStorageinsrc/lib/demo/demoStore.ts, intercepting/api/*and/api/admin/*mutations client-side viainstallDemoFetchInterceptorinsrc/lib/demo/demoApiHandler.ts, simulating non-charging registry card payments viaSimulatedCardCheckout(SIMULATED_TEST_CARDS) insrc/features/registry/components/SimulatedCardCheckout.tsx, and exposing the interactive<SetupWizard />preview on/admin/setupviaAdminSetupPageinsrc/app/admin/setup/page.tsx. Component showcases and architectural documentation portals are built vianpm run build-storybook(storybook-buildinci.ymlandstorybook.yml) andnpm run docs:build(verifyinci.ymluploadingdocs-portal-static, merged with/demo/and/storybook/and browser-verified vianpm run pages:verifyinpages-verifybeforedeploy-docspublishes the unified GitHub Pages bundle with subpath-safe return links resolved viaresolveShowcasePathinsrc/lib/basePath.ts).
Shared Runtime Contract
All hosting platforms consume the same unified application runtime contract, ensuring total portability and avoiding vendor lock-in:
- Node.js & Package Manager Specification: Node.js v22.x LTS (
>=22.22.1 <23.0.0acrossengines.nodeanddevEngines.runtime) andnpm^10.9.0(enforced viaenginesanddevEnginesinpackage.json), Next.js App Router standalone build (output: 'standalone'). - Database Engine & ORM: PostgreSQL 15+ accessed via Prisma ORM v7.x (
@prisma/client). - Migration Mechanism: Schema updates run prior to application start via offline
./node_modules/.bin/prisma migrate deployin the Docker Composemigrationservice anddocker-entrypoint.sh(whenRUN_MIGRATIONS=trueorRUN_MIGRATIONS=1), ornpx prisma migrate deployin CI/CD (.github/workflows/db-migrate.yml) and PaaS release hooks. - Environment Variables: Validated at startup by
src/env.tsusing Zod schema validation. - Asset Storage Abstraction: Local filesystem storage (
/app/public/uploads) or S3-compatible object storage (Cloudflare R2, AWS S3). - Liveness & Readiness Probes: Unauthenticated process liveness probe at
/api/live(HTTP 200{ "status": "alive", "timestamp": "..." }without database coupling), startup/rollout verification probe at/api/health(HTTP 200{ "success": true, "data": { "status": "ok", "database": "connected", ... } }), and unwrapped readiness probe at/api/ready. - Host Domain Security: Host header validation enforced via
ALLOWED_HOSTS.
Support Tier Matrix
To distinguish officially verified deployment targets from community-maintained examples, hosting options are classified into support tiers:
| Target Platform | Category | Support Tier | Detailed Guide |
|---|---|---|---|
| Generic Docker / VPS | Portable Baseline | Tier 1 — Officially Tested | Docker / VPS Guide |
| Google Cloud Run | Container / Serverless | Tier 1 — Officially Tested | Cloud Run Guide |
| Vercel | Serverless Node / Edge | Tier 1 — Officially Tested | Vercel Guide |
| Railway & Render | PaaS Target | Tier 2 — Community Supported | Railway & Render Guide |
Deployment Recipes Summary
1. Generic Docker / VPS Deployment
The canonical portable baseline using the multi-platform Dockerfile (tini PID 1, /opt/prisma-cli outside /app, root:root static /app ownership, setuid/setgid stripping) and hardened docker-compose.yml (read_only: true, cap_drop: [ALL], no-new-privileges:true, shm_size: "256mb" on db, bounded json-file 10m x 3 log rotation, pids_limit, mem_limit, stop_grace_period: 15s, and tmpfs mounts at /tmp and /app/.next/cache, with automated test overrides isolated in .env.ci and docker-compose.ci.yml). Consolidates image builds under app (pull_policy: never on migration and app-standby), orchestrates db bound to 127.0.0.1:${DB_PORT:-5432}:5432 with mandatory operator secrets, runs a dedicated one-shot migration service (./node_modules/.bin/prisma migrate deploy before app starts with RUN_MIGRATIONS="false", plus optional offline RUN_MIGRATIONS=true or RUN_MIGRATIONS=1 in docker-entrypoint.sh for standalone containers), pins NODE_ENV: production and scopes container DATABASE_URL via ${CONTAINER_DATABASE_URL:-...}, forwards all 21 runtime variables plus all 32 trimmed/blank-safe SITE_* overrides, preserves E2E_TEST=false default production onboarding, configures built-in Compose liveness healthchecks via /api/live (with rollout/readiness verification via /api/health and /api/ready) and graceful SIGTERM pg.Pool draining (5000ms timer inside the 15s grace period), and provides zero-downtime standby loopback rollouts (docker-compose.rollout.yml + ./scripts/rollout-vps.sh) behind dual-upstream Nginx/Caddy reverse proxies alongside networked port-mapped rollbacks (--stop-timeout 15).
2. Google Cloud Run Deployment
Managed serverless container target deploying attested ghcr.io immutable container digests to isolated Cloud Run services (wedding-website-staging for staging and wedding-website for production by default, or parameterized via vars.CLOUD_RUN_SERVICE and vars.CLOUD_RUN_REGION) using keyless Workload Identity Federation OIDC (vars.GCP_WORKLOAD_IDENTITY_PROVIDER and vars.GCP_SERVICE_ACCOUNT, with secrets.GCP_SA_KEY fallback), GCP Secret Manager, and Cloud SQL PostgreSQL. Automated via .github/workflows/deploy.yml with pre-deployment schema migrations, S3/R2 asset storage, and instant revision traffic splitting for rollbacks.
3. Vercel Deployment
Optional serverless Node.js deployment target using serverless PostgreSQL connection pooling (Neon, Supabase, RDS Proxy). Supports Vercel automatic custom domain TLS, pre-deploy build migrations (DATABASE_URL="${POSTGRES_URL_NON_POOLING:-$DATABASE_URL}" env -u POSTGRES_URL_NON_POOLING npx prisma migrate deploy && next build), and instant deployment rollbacks.
4. Railway & Render PaaS Deployment
Low-friction PaaS deployment path with managed PostgreSQL add-ons, pre-deploy release commands, persistent volume mounts or S3 asset storage, and automatic domain SSL provisioning.
Runtime Configuration & Production Secrets
Startup validation (src/env.ts) requires every production deployment (NODE_ENV=production) to configure non-default values for DATABASE_URL, ADMIN_PASSWORD (64-byte scrypt hash generated via scripts/generate-password-hash.mjs), ALLOWED_HOSTS, GUEST_PASSCODE, and GUEST_SESSION_SECRET (32+ characters, distinct from GUEST_PASSCODE).
For the canonical Environment Variable Matrix—including defaults, TRUST_PROXY hop counts (1 or 2 behind trusted reverse proxies), optional S3_* object storage credentials, STRIPE_* checkout keys, CRON_SECRET, RUN_MIGRATIONS (true or 1), POSTGRES_URL_NON_POOLING (prisma.config.ts shadow database / migration overrides), SITE_* overrides, E2E_TEST production blocklist warnings (never set E2E_TEST=true in production), and prisma/schema.prisma persisted entity and MULTISITE_ENABLED isolation rules—see the Application Runtime Contract and .env.example.
Webhooks & Scheduled Background Jobs
1. Stripe Registry Webhook (payment_intent.succeeded)
When online card checkout is enabled (STRIPE_SECRET_KEY + NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY), configure Stripe to deliver webhook events to your public deployment:
- In the Stripe Dashboard > Developers > Webhooks, click Add endpoint.
- Set the Endpoint URL to
https://<your-domain>/api/registry/webhook/stripeand ensure<your-domain>is listed inALLOWED_HOSTS. - Subscribe to the
payment_intent.succeededevent. - Copy the endpoint's Signing secret (
whsec_...) and setSTRIPE_WEBHOOK_SECRETin your hosting provider's runtime environment. src/middleware.tsvalidatesALLOWED_HOSTSand exempts/api/registry/webhook/stripefrom guest/admin session cookies so Stripe deliveries reachsrc/features/registry/api/webhook.ts, which verifies thestripe-signatureheader againstSTRIPE_WEBHOOK_SECRETbefore recording paid contributions.
2. Scheduled Broadcast Cron (/api/cron/broadcasts)
Scheduled guest broadcasts (ScheduledBroadcast entries) are processed by calling /api/cron/broadcasts:
- Generate a high-entropy secret (e.g.,
openssl rand -hex 32) and setCRON_SECRETin your hosting provider's runtime environment. - Configure your platform scheduler to issue periodic
GETorPOSTrequests (every 1–5 minutes, or daily on Vercel Hobby viavercel.json) tohttps://<your-domain>/api/cron/broadcastswith header:httpAuthorization: Bearer <CRON_SECRET> - On Vercel, the repository's root
vercel.jsonschedules/api/cron/broadcasts(0 14 * * *) and Vercel automatically injectsAuthorization: Bearer <CRON_SECRET>whenCRON_SECRETis configured in Vercel Environment Variables. On Docker/VPS, Google Cloud Run, Railway, and Render, configure hostcrontab, Cloud Scheduler, or a platform Cron service as documented in each provider recipe underdocs/deployment/.
🏗️ Architecture & Responsibilities
The automated release architecture decouples continuous delivery across isolated staging and production environments using mandatory human approval gates and automated rollback safeguards:
┌───────────────────────────────────────────────────────────┐
│ 1. Continuous Integration (ci.yml & storybook.yml) │
│ • Static gates, lint, typecheck, VitePress docs:build │
│ • Unit & integration tests, Storybook (storybook-build)│
│ • Static HTML showcase export (static-export-build) │
│ • Production build, container smoke & Playwright E2E │
│ • Unified Pages verification & deploy (pages-verify) │
└─────────────────────────────┬─────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────┐
│ 2. Artifact Publication (publish-artifact.yml) │
│ • Multi-arch OCI Docker build (FIFO queue: max) │
│ • Tagged by immutable commit SHA & version │
│ • Published to GHCR (default) & Docker Hub (optional) │
└─────────────────────────────┬─────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────┐
│ 3. Automated Staging Stage (deploy-stage.yml: staging) │
│ • Lock: deploy-env-staging (FIFO queue: max) │
│ • Staging Database Migration (db-migrate.yml) │
│ • Staging Provider Deployment (deploy-provider.yml) │
│ • Staging Verification (/api/health & /api/ready) │
└─────────────────────────────┬─────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────┐
│ 4. Mandatory Production Review Gate (environment: prod) │
│ • Reviewers inspect file-only DDL summary & staging │
│ • Pauses db-migrate.yml before accessing prod secrets │
│ • Mandatory human reviewer approval required │
└─────────────────────────────┬─────────────────────────────┘
│
▼
┌───────────────────────────────────────────────────────────┐
│ 5. Production Delivery Stage (deploy-stage.yml: prod) │
│ • Lock: deploy-env-production (FIFO queue: max) │
│ • Post-approval live prisma migrate status & deploy │
│ • Production Provider Deployment (deploy-provider.yml) │
│ • Production Verification (/api/health & /api/ready) │
└─────────────────────────────┬─────────────────────────────┘
│
┌─────────┴─────────┐
│ │
[Success] [Failure]
│ │
▼ ▼
┌───────────────────────┐ ┌──────────────────────────────┐
│ Release Complete │ │ 6. Automated Rollback │
│ High Availability │ │ • Calls rollback.yml │
│ Preserved │ │ • Restores previous tag │
│ Live Traffic Healthy │ │ • NO second approval gate │
└───────────────────────┘ └──────────────────────────────┘The top-level Release Pipeline (deploy.yml) executes ci-gate, schema-compatibility, and publish-artifact without acquiring environment locks, then delegates staging and production delivery to the reusable Deploy Stage (deploy-stage.yml) workflow so automated staging deployments never queue behind unapproved production reviewer gates. Each environment stage acquires a unified deploy-env-${{ inputs.environment }} concurrency group (cancel-in-progress: false, queue: max) across database migration, provider rollout, /api/health and /api/ready verification, and automated rollback, queuing up to 100 runs in FIFO order without canceling superseded runs mid-flight.
🛡️ GitHub Environment Setup & Reviewer Configuration
To protect production database integrity and application availability, the deployment architecture requires two distinct GitHub repository environments with isolated credentials:
1. Staging Environment (staging)
- Purpose: Automated pre-production integration testing, database schema migration verification, and container deployment validation on every merge to
main. - Environment Setup:
- Navigate to Settings > Environments in your GitHub repository.
- Click New environment and name it
staging. - Protection Rules: Leave "Required reviewers" unconfigured to permit unblocked, automated continuous delivery on every merge.
- Environment Variables (non-secret targets & Workload Identity Federation identifiers):
SERVICE_URL: Public base URL of the staging web service for/api/healthand/api/readyprobes (e.g.,https://staging.wedding.example.com). ConfigureSERVICE_URLas a GitHub Environment variable (vars.SERVICE_URL) so cross-jobservice_urloutputs and$GITHUB_STEP_SUMMARYdiagnostics remain unmasked (secrets.SERVICE_URLis supported as a legacy fallback during migration).CLOUD_RUN_SERVICE: Optional Cloud Run service name override for staging (defaults towedding-website-stagingso staging promotions never overwrite productionwedding-website).CLOUD_RUN_REGION: Optional Cloud Run region override for staging (defaults tous-central1).GCP_WORKLOAD_IDENTITY_PROVIDER: Primary keyless OIDC Workload Identity Provider resource name (projects/<project-number>/locations/global/workloadIdentityPools/<pool>/providers/<provider>).GCP_SERVICE_ACCOUNT: Service account email impersonated via Workload Identity Federation (<sa-name>@<project-id>.iam.gserviceaccount.com).
- Environment Secrets:
DATABASE_URL: Connection string for the isolated staging PostgreSQL instance (e.g.,postgresql://wedding:staging_pass@staging-db.internal:5432/wedding_staging), plus optionalPOSTGRES_URL_NON_POOLINGwhenDATABASE_URLconnects through a PgBouncer pooler.- Provider secrets (
GCP_SA_KEYfallback when Workload Identity Federation variables are unset, optionalGCP_PROJECT_ID, orDEPLOY_WEBHOOK_URL+DEPLOY_WEBHOOK_SECRETfor webhook/Docker host adapters). Becausestaginghas no required reviewers, automated staging rollbacks can resolve variables and secrets directly fromstaging(or an optionalSTAGING_ROLLBACK_ENVIRONMENT).
2. Production Environment (production)
- Purpose: Live environment hosting attendee traffic, requiring explicit human reviewer approval before executing schema migrations or container updates.
- Environment Setup:
- Navigate to Settings > Environments in your GitHub repository.
- Click New environment and name it
production. - Required Reviewers (Mandatory Gate):
- Check the Required reviewers checkbox.
- Specify designated maintainers, release managers, or team leads authorized to approve production releases.
- Select Prevent self-review if team policy mandates dual-control sign-off.
- Deployment Branches: Restrict deployment to
mainbranch (and optionally release tagsv*if promoting tagged releases viadeploy-provider.ymlwithimage_tagordeploy.ymlwithrelease_ref/image_digest; automateddeploy.ymlruns trigger onmainafterCIsucceeds). - Environment Variables (non-secret targets & Workload Identity Federation identifiers):
SERVICE_URL: Public base URL of the live production web service for/api/healthand/api/readyprobes (e.g.,https://wedding.example.com). ConfigureSERVICE_URLas a GitHub Environment variable (vars.SERVICE_URL) so cross-jobservice_urloutputs and$GITHUB_STEP_SUMMARYdiagnostics remain unmasked (secrets.SERVICE_URLis supported as a legacy fallback during migration).CLOUD_RUN_SERVICE: Optional Cloud Run service name override for production (defaults towedding-website).CLOUD_RUN_REGION: Optional Cloud Run region override for production (defaults tous-central1).GCP_WORKLOAD_IDENTITY_PROVIDER: Primary keyless OIDC Workload Identity Provider resource name for production deployments.GCP_SERVICE_ACCOUNT: Production service account email impersonated via Workload Identity Federation.
- Environment Secrets (workflow-consumed credentials only):
DATABASE_URL: Connection string for the isolated production PostgreSQL instance used bydb-migrate.yml(e.g.,postgresql://wedding:prod_pass@prod-db.internal:5432/wedding_prod), plus optionalPOSTGRES_URL_NON_POOLINGdirect connection secret whenDATABASE_URLuses a PgBouncer pooler.- Provider secrets (
GCP_SA_KEYfallback when OIDC variables are unset, optionalGCP_PROJECT_ID, orDEPLOY_WEBHOOK_URL+DEPLOY_WEBHOOK_SECRETfor signed webhook/Docker host deployments). - Note: Application runtime secrets (
ADMIN_PASSWORD,GUEST_PASSCODE,GUEST_SESSION_SECRET,S3_*,STRIPE_*) are not read by GitHub Actions workflows and must be configured in your target hosting platform's secret store (such as GCP Secret Manager, Vercel Environment Variables, or VPS.env).
3. Unguarded Production Rollback Environment (production-rollback)
- Purpose: Enables unattended container restoration when
/api/healthor/api/readyfails after a reviewer-approved production rollout, resolving environment-scoped provider credentials without pausing behindproduction's human reviewer gate. - Environment Setup:
- Navigate to Settings > Environments and click New environment named
production-rollback. - Protection Rules: Leave Required reviewers unchecked so emergency rollbacks execute immediately within the 60-second recovery target. Restrict Deployment branches to
mainand release tags (v*). - Environment Variables & Secrets: Set
SERVICE_URL(vars.SERVICE_URL, withsecrets.SERVICE_URLsupported as a legacy fallback), optional Cloud Run target/OIDC variables (CLOUD_RUN_SERVICE,CLOUD_RUN_REGION,GCP_WORKLOAD_IDENTITY_PROVIDER,GCP_SERVICE_ACCOUNT), and copy only the container deployment secrets required by.github/workflows/rollback.ymland.github/workflows/deploy-provider.yml(GCP_SA_KEY,GCP_PROJECT_ID,DEPLOY_WEBHOOK_URL, andDEPLOY_WEBHOOK_SECRET—DATABASE_URLis not needed because rollbacks preserve forward-only N-1 compatible schemas). - Pipeline Binding: Set repository variable
PRODUCTION_ROLLBACK_ENVIRONMENT=production-rollbackunder Settings > Secrets and variables > Actions > Variables (or passrollback_environment: production-rollbackwhen manually invokingrollback.ymlviaworkflow_dispatch;deploy.ymlanddeploy-provider.ymlacceptrollback_environmentstrictly onworkflow_callso manual forward promotions always honorproductionprotection rules). Whenrollback_environmentis omitted,rollback.ymlfalls back totarget_environment.
- Navigate to Settings > Environments and click New environment named
4. Strict Separation of Secrets, Database Credentials & Environment Locks
- Staging and production MUST NOT share database credentials or database instances.
- Reusable workflows declare explicit
workflow_call.secretsand pass minimal per-callee secret maps across.github/workflows/deploy.yml,.github/workflows/deploy-stage.yml,.github/workflows/publish-artifact.yml,.github/workflows/db-migrate.yml,.github/workflows/deploy-provider.yml, and.github/workflows/rollback.yml(omitting blanket secret inheritance so only.github/workflows/db-migrate.ymlreceivesDATABASE_URLandPOSTGRES_URL_NON_POOLING, while.github/workflows/deploy-provider.ymland.github/workflows/rollback.ymlreceive only provider/service secrets and resolve environment-scoped secrets fromenvironment/rollback_environment). Registry logins bind temporaryDOCKER_CONFIGdirectories (mktemp -d) and delete them before subsequent steps run. - Staging migrations execute strictly against the staging database (
deploy-env-staging); production migrations execute strictly against the production database (deploy-env-production) following reviewer sign-off. - Concurrency groups in
.github/workflows/deploy-stage.yml,.github/workflows/db-migrate.yml,.github/workflows/deploy-provider.yml, and.github/workflows/rollback.ymlare keyed strictly on targetenvironment(deploy-env-stagingordeploy-env-production) rather thanrollback_environment, ensuring manual dispatches and unguardedproduction-rollbackruns serialize against activeproductiondeployments while passingcaller_holds_lock: trueto nested workflows to avoid nested lock contention.
🔄 Staging Promotion & Approval Workflow
- Automated Staging Delivery on Merge & Tag Promotion SHA Resolution:
- When a pull request is merged into
main,.github/workflows/ci.yml(CI) executes static checks, unit tests, container smoke tests, and Playwright E2E tests first. OnceCIcompletes withsuccesson themainpush, GitHub Actions triggers.github/workflows/deploy.ymlviaworkflow_runforgithub.event.workflow_run.head_sha. On manualworkflow_dispatchor reusableworkflow_callruns,ci-gatechecks out the repository (fetch-depth: 0,persist-credentials: false), resolvestarget_shafromimage_digestOIDC build provenance attestation (gh attestation verify --format jsonsigned by.github/workflows/publish-artifact.ymland OCIorg.opencontainers.image.revisionmetadata viascripts/resolve-oci-provenance.sh),image_tag(v*release tags or 40-character SHAs),release_ref(restricted to immutablev*tags or 40-character SHAs and dereferenced via the GitHub Commits API / git tags), orcommit_shabefore defaulting togithub.sha(failing closed if multiple promotion inputs resolve to different commits), and verifies viascripts/verify-release-target.sh(including--ci-only) thattarget_shadescends fromrefs/remotes/origin/main(or matches an OIDC-attestedrefs/tags/v*maintenance release signed by.github/workflows/publish-artifact.yml) and that its latest completed trustedci.ymlrun (eventinpushorworkflow_dispatchwith non-nullhead_repositorymatchinggithub.repositoryacross paginatedexclude_pull_requests=true&per_page=100results, sorted byupdated_atdescending) succeeded. Becausedeploy.ymlomits root-levelconcurrency,ci-gate,schema-compatibility, andpublish-artifactexecute immediately on every merge without waiting on pendingproductionapprovals. schema-compatibility(contents: read,packages: read,attestations: read,deployments: read, omittingactions: readanddeployments: write) re-verifiestarget_shaviascripts/verify-release-target.sh --skip-ci-checkand detaches its git checkout (git checkout --detach) on everyworkflow_run,workflow_dispatch, andworkflow_callexecution (npm run lint:migrationsandnode --experimental-strip-types scripts/preflight-migration-summary.ts --offlineon Node.js 22 withoutnpm ci, resolving--base-reffrom the latest activesuccessnon-dry_runGitHub Deployment forstagingorproduction, falling back to/repos/<owner>/<repo>/activity?ref=refs/heads/main&activity_type=pushmatchingafter == RESOLVED_TARGET_SHAorHEAD^1), and both thestagingandproductionstage jobs forwardcommit_sha: target_shaplusimage_tag: inputs.image_tag || inputs.release_ref || needs.publish-artifact.outputs.image_tag || needs.ci-gate.outputs.target_shathrough.github/workflows/deploy-stage.ymlto.github/workflows/db-migrate.ymland.github/workflows/deploy-provider.ymlsov*tag,release_ref, or digest promotions executenpm run lint:migrations,npx prisma migrate deploy, and--source-ref refs/tags/<v*>provenance verification at the exact release commit rather thanmainHEAD. Whenimage_digest,image_tag, andrelease_refare omitted,.github/workflows/publish-artifact.ymlruns once viaworkflow_call(concurrency: publish-artifact-release,cancel-in-progress: false,queue: max) attarget_shato confirm passingCI, natively build (ubuntu-latestforlinux/amd64andubuntu-24.04-armforlinux/arm64without QEMU emulation,provenance: false,sbom: false), stamporg.opencontainers.image.revisionlabels and manifest annotations, loadwedding-website:latestviaskopeo, Trivy-scan (CRITICAL/HIGH/MEDIUM) and generate SPDX JSON SBOMs (aquasecurity/trivy-action), smoke-test (scripts/test-container.mjs), and exportzstd-compressed OCI archives without registry credentials inbuild, then re-verifies archive digests (skopeo inspect) and SPDX SBOMs, pushes architecture manifests (skopeo copy --preserve-digests), merges the multi-platform OCI index (docker buildx imagetools createwithindex:org.opencontainers.image.revision), synthesizes the multi-platform index SPDX SBOM, signs OIDC build provenance (actions/attest-build-provenance) and SPDX SBOM (actions/attest) attestations across both per-architecture (amd64,arm64) and merged index digests onghcr.io(and conditionaldocker.io/), and exportsimage_digest(sha256:<64-hex>).- The
stagingjob indeploy.ymlinvokes.github/workflows/deploy-stage.yml(environment: 'staging'), acquiringdeploy-env-staging(cancel-in-progress: false,queue: max). Insidedeploy-stage.yml,deploy-provider(caller_holds_lock: true) receivescommit_sha(needs.ci-gate.outputs.target_sha), the attestedimage_digest, and optionalcloud_run_service/cloud_run_regionoverrides with job-scopedactions: readanddeployments: write: its read-onlypreflightjob checks outcommit_sha(fetch-depth: 0), verifies OIDC provenance viagh attestation verifyagainst theoci://ghcr.io/<owner>/<repo>@sha256:<hex>URI viascripts/resolve-oci-provenance.sh, confirms a passingci.ymlrun for the signed source revision, and runsnpm run lint:migrationsprior to rollout, while the checkout-freedeployjob captures the prior staging release (previous_image_digestandprevious_image_tag: from the active Cloud Run@sha256:revision OIDC provenance attestation /commit-shaand OCI revision labels, environment-filteredstagingGitHub Deployments withsuccessstatus, completed non-dry_runstagingdeploy.yml/deploy-provider.ymlworkflow runs, or GHCR-verifiedHEAD^1/ commit parents ofcommit_shaviadocker buildx imagetools inspect) before deploying the digest-pinned container tostaging, records environment deployment state in GitHub Deployments, andverify-deploymentvalidates/api/health.
- When a pull request is merged into
- Pre-Flight Schema Compatibility & Offline Git Diff DDL Summary (Pre-Approval):
- Prior to the
productiongate,schema-compatibilityin.github/workflows/deploy.yml(deployments: read) runsnpm run lint:migrations, resolvesBASE_SHAfrom the latest activesuccessnon-dry_runGitHub Deployment forstaging(wheninputs.environment == 'staging') orproduction(falling back to/repos/<owner>/<repo>/activity?ref=refs/heads/main&activity_type=pushmatchingafter == RESOLVED_TARGET_SHA, orHEAD^1when empty), and invokesnode --experimental-strip-types scripts/preflight-migration-summary.ts --offline(passing--base-ref "$BASE_SHA"when resolved) on Node.js 22 withoutnpm ciorDATABASE_URL, diffingprisma/migrations/across multi-commit releases (NOT QUERIEDdatabase status) and emitting every changed SQL DDL file to$GITHUB_STEP_SUMMARYwithout claiming live pending migrations. - Simultaneously, the
stagingstage (deploy-stage.ymlrunningdatabase-migrationviadb-migrate.ymlagainststagingDATABASE_URLandverify-deployment) validates live migration execution and/api/healthin staging without waiting on anyproductionlock.
- Prior to the
- Maintainer Review & Sign-Off (
productionGate):- Once
stagingsucceeds, theproductionjob indeploy.ymlinvokes.github/workflows/deploy-stage.yml(environment: 'production'), acquiringdeploy-env-production(cancel-in-progress: false,queue: max) and calling.github/workflows/db-migrate.yml(caller_holds_lock: true) withenvironment: productiondeclared on themigratejob, so GitHub Actions pauses the job before exposing productionDATABASE_URLor querying the live production database while subsequentproductionpromotions queue safely in FIFO order (up to 100 runs). - Maintainers inspect the offline
git diffSQL DDL summary fromschema-compatibility, the attestedimage_digest, and the live staging migration/health results, then click Review deployments >production> Approve and deploy.
- Once
- Post-Approval Live Production DDL Check, Deployment & Automated Rollback Guard:
- Once approved,
.github/workflows/db-migrate.ymlunlocksproductionsecrets, verifiesnpm run lint:migrations, queries live productionDATABASE_URLvianpx prisma migrate status(npx tsx scripts/preflight-migration-summary.ts --require-db) to audit pending/failed migrations, schema drift, and connectivity (redacting database URLs on failure) and emit the live DDL summary, and runsnpx prisma migrate deploywith lock and statement timeouts. - Inside
deploy-stage.yml,deploy-provider(caller_holds_lock: true) passescommit_sha(needs.ci-gate.outputs.target_sha), minimal provider secrets (omittingDATABASE_URLandPOSTGRES_URL_NON_POOLING), job-scopedactions: readanddeployments: write, and the exactimage_digestattested inpublish-artifact.yml(or an explicitimage_digest/release_ref/image_tagsupplied on manual dispatches, withtarget_sharesolved from provenance or tag commit so newerHEADmigrations are never applied prematurely), runs read-onlypreflight(fetch-depth: 0,gh attestation verifyagainst.github/workflows/publish-artifact.yml, passingci.ymlverification, andnpm run lint:migrations), and then in checkout-freedeploycaptures the currently servingproductioncontainer image (previous_image_digestandprevious_image_tag: from Cloud Run@sha256:revision attestations/labels, environment-isolatedproductionGitHub Deployments withsuccessstatus so concurrentstagingrollouts never polluteproductionrollback tags, completed non-dry_runproductionworkflow runs, or GHCR-published releases verified viadocker buildx imagetools inspectandHEAD^1/ commit parents relative tocommit_shawhile skippingstaging,dry_run, and unpublishedHEAD^1commits) before rollout, deploys the immutable@sha256:URI via.github/workflows/deploy-provider.yml, and records the deployment in GitHub Deployments. - Post-deployment health and readiness probes (
Verify Provider Service Healthindeploy-provider.yml,timeout-minutes: 4inside atimeout-minutes: 20provider job budget alongside bounded rollout step timeouts oftimeout-minutes: 5for Cloud Run andtimeout-minutes: 2for webhook adapters, with stage summary consumption inverify-deploymentofdeploy-stage.yml,timeout-minutes: 5) verify/api/healthand/api/readywith bounded socket timeouts (curl --connect-timeout 5 --max-time 10) and exponential backoff while still holdingdeploy-env-<environment>. GitHub Deployments are created inin_progressstate (auto_inactive: false) before probing/api/healthand/api/readyand transition tosuccess(auto_inactive: true) only after/api/healthreturnsHTTP 200with.data.status == "ok"and.data.database == "connected"and/api/readyreturnsHTTP 200withstatus == "ready"anddatabase == "connected"(orfailureviaif: always()when/api/healthor/api/readyfails or cancels). - Rollback Guarantee: When
PRODUCTION_ROLLBACK_ENVIRONMENT/STAGING_ROLLBACK_ENVIRONMENTis unset (rollback_environment == ''),.github/workflows/deploy-provider.yml(auto_rollback_on_failure: true, reserving headroom inside its 20-minute job budget after bounded forward rollout and probe step timeouts) marks the failed deploymentfailureand executes automatic checkout-free in-job fallback recovery inside the already-approveddeployjob (afterpreflightalready verifiednpm run lint:migrationsviaactions/setup-node.nvmrc: priorsuccessGitHub Deployment verification,gh attestation verifyOIDC provenance check resolving attested OCIorg.opencontainers.image.revisionand SLSAinputs.commit_shaahead of OIDCGITHUB_SHAdigests and failing closed on conflicts, digest-pinned container restoration stamped with the attestedsource_revision,/api/healthand/api/readyverification, restored GitHub Deployment recording,inline_rollback_completed=true, andexit 1), skippingrollback.ymlso recovery finishes without a second human reviewer prompt. When an unguardedrollback_environment(e.g.,production-rollback) is configured, when a stage run is cancelled afterrollout_executed == 'true'(inline_rollback_completed != 'true'), or on standalonerollback.ymldispatches,.github/workflows/deploy-stage.ymlinvokes.github/workflows/rollback.yml(caller_holds_lock: true) withcommit_sha(needs.ci-gate.outputs.target_shascoped topreflight),previous_image_digest,previous_image_tag,provider,cloud_run_service,cloud_run_region, androllback_environment.rollback.ymlevaluatesif: always()with upstream job and step outcome guards acrosspreflight,redeploy,verify, andreportso cancelled runs never skip recovery, validates 40-character hexadecimalcommit_sha(defaulting togithub.shaon manual dispatch), accepts digest-pinned rollbacks (previous_digestwith emptyprevious_tag), rejectslatest, verifies inpreflight(checking attested OCIorg.opencontainers.image.revisionand SLSAinputs.commit_shaahead of OIDCGITHUB_SHAdigests only aftergh attestation verifysucceeds) thatprevious_digest/previous_tagdoes not matchCURRENT_SHA(commit_sha || github.sha) and succeeded earlier intarget_environmentGitHub Deployments beforeredeploystarts, checks outcommit_sha(persist-credentials: false) to verifynpm run lint:migrationswithoutmaindrift, delegates redeployment (caller_holds_lock: true,is_rollback: true, omitting the failingcommit_shasodeploy-provider.ymlstamps the restored artifact's attestedsource_revisiononto Cloud Run and GitHub Deployments) to.github/workflows/deploy-provider.ymlwithout requiring a second human approval step, and consumeshealth_statusandhttp_statusfromdeploy-provider.yml(with fallback${SERVICE_URL}/api/healthpolling forHTTP 200,.data.status == "ok",.data.database == "connected"and${SERVICE_URL}/api/readypolling forHTTP 200,status == "ready",database == "connected") without gatingverifyonproductionor leaking environmentsecrets.SERVICE_URLbefore releasingdeploy-env-<environment>and reportingSUCCESS.
- Once approved,
📄 Workflows Overview
1. Continuous Integration (ci.yml) & Storybook Showcase (storybook.yml)
- Triggers & Concurrency:
ci.yml: Pull requests,merge_groupmerge queue checks, manualworkflow_dispatch, and pushes tomainandrelease/**maintenance branches (omittingv*version tag pushes somainandrelease/**tag pushes never duplicate CI runs;ci-completeruns acrossrelease/**andworkflow_dispatchwhileattest-bundles,prepare-docs, anddeploy-docsremain restricted tomainpushes), configured withconcurrency: { group: ${{ (github.event_name == 'pull_request' || github.event_name == 'merge_group') && format('CI-{0}', github.ref) || format('CI-{0}-{1}-{2}', github.ref, github.run_id, github.run_attempt) }}, cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'merge_group' }} }(omitting top-levelqueue: max, which GitHub Actions forbids alongsidecancel-in-progress: trueor conditional cancelling expressions) so open pull requests and supersededmerge_groupruns onCI-<ref>cancel in-progress runs immediately while concurrentmain,release/**, andworkflow_dispatchruns execute in isolatedCI-<ref>-<run_id>-<run_attempt>concurrency groups without evicting commits (anddeploy-docsserializes GitHub Pages publishing viagroup: github-pages,cancel-in-progress: false, andqueue: max).storybook.yml(Storybook Static Showcase): Reusableworkflow_callinvoked bystorybook-buildinci.yml(passingcaller_holds_lock: trueand exportingoutputs.storybook_base_path) and manualworkflow_dispatch(including checkout-freeSHA256SUMSprovenance attestation on manual dispatches), declaring boolean inputcaller_holds_lock(default: false) and serialized viaconcurrency: { group: ${{ inputs.caller_holds_lock && format('caller-storybook-{0}-{1}-{2}', github.ref, github.run_id, github.run_attempt) || format('storybook-{0}', github.ref) }}, cancel-in-progress: false, queue: max }withtimeout-minutes: 20onbuildandtimeout-minutes: 5onattest-storybook(isolatingci.ymlcaller runs undercaller-storybook-<ref>-<run_id>-<run_attempt>so activemainandrelease/**CI runs never stall behind standalonestorybook-<ref>workflow_dispatchruns queued in FIFO order viaqueue: max, while cancelled parent PR/merge_groupruns propagate cancellation automatically).
- Execution Bounds & AST Policy: Every
runs-onrunner job across.github/workflows/declares an explicit integertimeout-minutes(1–60) enforced statically bynpm run check:action-pins(while exempting reusableuses:caller jobs withoutruns-on, such asstorybook-buildinci.yml) and pairs external API, registry, attestation, browser install, and GitHub Pages steps with step-leveltimeout-minutesstrictly below the enclosing job budget so hung steps never holdqueue: maxFIFO locks for 6 hours (ci.ymlbudgets:verify: 15,doc-drift-comment: 5,unit-test: 30,build: 30,container-arm64: 30,static-export-build: 25,e2e-test: 25,a11y-report: 5,a11y-report-comment: 5,pages-verify: 15,ci-complete: 5,attest-bundles: 5,prepare-docs: 30,deploy-docs: 10;storybook.ymlbudgets:build: 20,attest-storybook: 5). - Secrets required: None (runs entirely on isolated local containers and GitHub OIDC Pages tokens).
- Jobs & Actions:
verify(ci.yml): Read-only (contents: read,persist-credentials: falseacross all workflow checkouts) unified static guardrail bundle (npm run check:static -- --skip-doc-sync --skip-action-pins, runningcheck:env-docs,check:runbooks,check:setup-guides,check:identifiers,check:links,check:spec-contracts,check:prisma,lint:migrations, andcheck:standalone), root and isolated Prisma CLImoderate-severity dependency audit (npm run check:audit), single-pass YAML 1.2 AST policy, SHA &# v...version comment pinning, and upstream commit verification (npm run check:action-pins -- --verify-upstream), verifiedservices.dbdigest export (outputs.db_image), normalized GitHub Pages base-path resolution (outputs.portal_base_path,outputs.demo_base_path, andoutputs.storybook_base_pathvianode scripts/build-pages-bundle.mjs --resolve-base-pathsacross/custom domains/CNAME,/<owner>.github.iosites, and/<repo>project subpaths),actions/cachepersistence of content-hashed.eslintcache(--cache-strategy content) and all five incremental*.tsbuildinfofiles (touching exact hits to current time and backdating partialrestore-keyshits to2000-01-01T00:00:00Z), TypeScript type checking (npm run typecheck, reusingnext typegenoutput frompostinstall), ESLint (npm run lint), Knip (npm run lint:unused), OpenAPI/architecture sync (uploadingdoc-drift-statusartifact), and VitePress portal compilation (VITEPRESS_BASEbound tosteps.resolve-pages-base-paths.outputs.portal_base_pathwithSKIP_DOC_SYNC=true npm run docs:build, uploadingdocs-portal/.vitepress/dist/asdocs-portal-static).doc-drift-comment(ci.yml): Isolated downstream PR comment job (needs: verify,pull-requests: write,issues: write, zeroactions/checkoutand zeronpm ci) that downloadsdoc-drift-statuson pull requests and creates or updates the<!-- doc-drift-comment -->PR comment without exposing write-scoped tokens topackage.jsonscripts.unit-test(ci.yml): Installs dependencies withSKIP_NEXT_TYPEGEN=true npm ci, restores and persistsnode_modules/.cache/jest(cacheDirectoryinjest.config.mjs) viaactions/cache, and runs Prisma migration parity verification (Verify Prisma Migration Sync) and Jest unit and integration tests (npm run test:cov) against the verifiedpostgres:15-alpinedigest exported byverify, uploading coverage andjest-a11y-violationsartifacts.build(ci.yml): Installs dependencies withSKIP_NEXT_TYPEGEN=true npm ci, hydrates and persists non-emptyamd64BuildKit cache mounts (/var/cache/apt,/var/lib/apt,/root/.npm,/app/.next/cachevalidated viavalidate_cache_archive, extracted with--no-same-owner --no-same-permissions, and exported viascripts/persist-buildkit-mounts.sh) viaactions/cache, guardscrazy-max/ghaction-github-runtimewithif: github.event_name != 'pull_request', builds Next.js once insidewedding-website:latest(linux/amd64) usingapp-amd64BuildKit layer cache (exportingmode=maxcache layers only on non-pull_requestruns), scanswedding-website:latestwithaquasecurity/trivy-action(CRITICAL,HIGH, andMEDIUMseverities matchingpublish-artifact.yml,ignore-unfixed: true,exit-code: 1, zero secrets), extracts standalone output fromwedding-website:latestinto.next/standalonefor post-build standalone portability and execution checks (npm run check:standalone -- --standalone-only,npm run test:standalone), runs OCI container & clean database smoke tests (npm run test:container -- --container-migrationwithSKIP_IMAGE_BUILD=trueandGHA_CACHE_SCOPE=app-amd64), and uploadsnext-build-artifact(.next/,public/,prisma/,node_modules/.prisma, andnode_modules/@prisma).container-arm64(ci.yml): Parallel nativelinux/arm64OCI container build (hydrating and persisting non-emptyarm64BuildKit cache mounts viaactions/cachewithvalidate_cache_archive,--no-same-owner --no-same-permissions, andscripts/persist-buildkit-mounts.sh, guardingcrazy-max/ghaction-github-runtimewithif: github.event_name != 'pull_request', readingapp-arm64BuildKit layer cache, and skippingmode=maxwrites onpull_requestevents),aquasecurity/trivy-actionCRITICAL/HIGH/MEDIUMcontainer vulnerability scan (ignore-unfixed: true,exit-code: 1, zero secrets), clean-database Prisma migration check, and HTTP probe smoke test (scripts/test-container.mjswithSKIP_IMAGE_BUILD=true) onubuntu-24.04-arm(GitHub-hostedubuntu-24.04-armrunners run free on public repositories, whereas private forks may require paid runner quotas).storybook-build(ci.yml),build(storybook.yml), &attest-storybook(storybook.yml):storybook-buildinci.yml(on pull requests,merge_groupruns, andmainpushes, retaining the union of callee-required scopes) delegates to reusable./.github/workflows/storybook.yml(with: { storybook_base_path: needs.verify.outputs.storybook_base_path, caller_holds_lock: true }, also runnable via manualworkflow_dispatch), where read-onlybuild(contents: read) installs dependencies vianpm ci --ignore-scripts, consumesinputs.storybook_base_pathfromverify(or resolves the GitHub Pages Storybook subpath viascripts/build-pages-bundle.mjs --resolve-base-pathson manual dispatches across/<repo>/storybook,<owner>.github.io, and root custom domains/storybook), keysactions/cachefornode_modules/.cache/webpackandnode_modules/.cache/storybookonsteps.base-path.outputs.storybook_base, compiles the static Storybook showcase (npm run build-storybookwithNEXT_PUBLIC_BASE_PATH), runs the parallel Playwright light/dark runtime and WCAG 2.2 AA story audit (npm run test:e2e:storybookviaplaywright.storybook.config.tsacross all43stories /86renders), uploadsstorybook-a11y-violations(test-results/storybook-a11y-violations.json) onif: always() && !cancelled()andplaywright-storybook-traces(test-results/playwright-storybook/,retention-days: 7) onif: failure(), generates and verifies deterministicstorybook-static/SHA256SUMSmanifests viascripts/release-integrity.sh(generate-tree-sumsandverify-tree-sums), and uploadsstorybook-static(retention-days: 7) while exportingoutputs.storybook_base_pathtoci.yml; on manualworkflow_dispatch, the downstream checkout-freeattest-storybookjob (if: github.event_name == 'workflow_dispatch',contents: read,id-token: write,attestations: write) verifiessha256sum --check --strict SHA256SUMSand attestsstorybook-static/SHA256SUMSviaactions/attest-build-provenance.static-export-build(ci.yml): Runs in parallel afterverify(contents: read) without PostgreSQL services or secrets, installs dependencies withSKIP_NEXT_TYPEGEN=true npm ci, consumesneeds.verify.outputs.demo_base_pathasNEXT_PUBLIC_BASE_PATHfor repository subpaths (/<repo>/demo) or root custom-domain/<owner>.github.iosites (/demo), stages sources withoutsrc/app/api, caches.next-export/cachekeyed byneeds.verify.outputs.demo_base_path, compiles the database-free static HTML showcase vianpm run build:export(scripts/build-export.mjswithNEXT_PUBLIC_BASE_PATHandtrailingSlash: true, skipping rootnext typegenduringSTATIC_EXPORT=true) with zero[PageQueryError]logs, verifiesout/index.htmland route HTML files, executes the standalone Playwright static showcase runtime & light/dark WCAG 2.2 AA audit (npm run test:e2e:staticviaplaywright.static.config.tswithoutputDir: 'test-results/playwright-static'andtrace: 'retain-on-failure'plusscripts/serve-static-export.mjs), uploadsstatic-a11y-violations(test-results/static-a11y-violations.json) withif: always(), uploadsplaywright-static-traces(test-results/playwright-static/,retention-days: 7) onif: failure(), and uploads thedemo-staticartifact (retention-days: 7).e2e-test(ci.yml): Depends onverifyandbuild(contents: read), installs dependencies vianpm ci --ignore-scripts, restores.next/,public/,prisma/,node_modules/.prisma, andnode_modules/@prismafromnext-build-artifact, runs the standalone Playwright E2E and WCAG accessibility suite (npx playwright test, ignoringe2e/pages-showcase.spec.tsunless invoked explicitly vianpm run pages:verifyand retaining failure traces undertest-results/playwright/viatrace: 'retain-on-failure') against the verifiedpostgres:15-alpinedigest, uploadsplaywright-a11y-violations(test-results/playwright-a11y-violations.json) withif: always(), and uploadsplaywright-traces(test-results/playwright/,retention-days: 7) onif: failure().a11y-report(ci.yml): Read-only (contents: read) job that runs afterunit-test,e2e-test,static-export-build, andstorybook-buildwithif: always() && !cancelled(), downloadsjest-a11y-violations,playwright-a11y-violations,static-a11y-violations, andstorybook-a11y-violationsartifacts, generates sanitizedtest-results/a11y-summary.mdvianode scripts/a11y-report.mjs --include-static --include-storybook --require-complete(escaping HTML, Markdown links, backticks, and newlines in violation fields and exiting1after writingtest-results/a11y-summary.mdwhenever violations exist, expected suite artifacts are missing, or JSON parsing fails), uploadsa11y-summaryon pull requests, writes$GITHUB_STEP_SUMMARYonif: always() && !cancelled(), and fails whenever any upstream job (unit-test,e2e-test,static-export-build, orstorybook-build) does not succeed.a11y-report-comment(ci.yml): Isolated downstream PR comment job (needs: [a11y-report],pull-requests: write,issues: write, zeroactions/checkoutand zeronpm ci) that downloadsa11y-summaryon same-repository pull requests, validates lines against a strict allowlist, and creates or updates the<!-- a11y-report -->PR comment without exposing write-scoped tokens to branch code.pages-verify(ci.yml): Depends onverify,static-export-build, andstorybook-build(contents: read), installs dependencies vianpm ci --ignore-scripts, mergesdocs-portal-static(docs-portal/.vitepress/dist),demo-static(docs-portal/.vitepress/dist/demo), andstorybook-static(docs-portal/.vitepress/dist/storybook, verifyingdocs-portal/.vitepress/dist/storybook/SHA256SUMSimmediately viascripts/release-integrity.sh verify-tree-sums) with.nojekyll, passesPAGES_BASE_PATH(needs.verify.outputs.portal_base_path) to execute all 4 unified bundle Playwright smoke and cross-app navigation tests ine2e/pages-showcase.spec.tsvianpm run pages:verifywith zero skips, generates and verifiesdocs-portal/.vitepress/dist/SHA256SUMSacross the unified bundle viascripts/release-integrity.sh, and uploads the verifiedpages-bundleartifact (include-hidden-files: true,retention-days: 7).ci-complete(ci.yml): Terminal read-only (contents: read,timeout-minutes: 5, zeroactions/checkoutand zeronpm ci) branch-protection, merge queue, and release gate (if: always() && !cancelled()) that skips cleanly when a workflow run is cancelled and otherwise depends on and verifiesresult == 'success'across all 9 verification jobs (verify,unit-test,build,container-arm64,storybook-build,static-export-build,e2e-test,a11y-report, andpages-verify).attest-bundles(ci.yml): Checkout-free OIDC provenance job (needs: [ci-complete, storybook-build, pages-verify],timeout-minutes: 5,contents: read,id-token: write,attestations: write, zeroactions/checkoutand zeronpm ci) restricted strictly tomainpushes (if: github.ref == 'refs/heads/main' && github.event_name == 'push') that downloadsstorybook-staticandpages-bundle, verifies bothSHA256SUMSmanifests (sha256sum --check --strictplus symlink and file-set parity checks), and signs OIDC build provenance attestations (actions/attest-build-provenance# v4.2.2) over/tmp/storybook-static/SHA256SUMSand/tmp/pages-bundle/SHA256SUMS.prepare-docs(ci.yml): Read-only (contents: read,timeout-minutes: 30) preparation job afterverify,ci-complete,static-export-build,storybook-build, andpages-verifystrictly on pushes tomainthat consumesneeds.verify.outputs.portal_base_path,needs.verify.outputs.demo_base_path,needs.verify.outputs.storybook_base_path, andneeds.storybook-build.outputs.storybook_base_path, fetchesorigin/mainto verifygithub.shamatchesorigin/mainHEAD(outputs.is_latest, skipping stale burst commits or reruns cleanly), configures GitHub Pages (actions/configure-pages), reuses the pre-verifiedpages-bundleartifact directly withoutactions/setup-nodeornpm ciwheneveractions/configure-pagesmatchesverifyandstorybook-buildoutputs across/,<owner>.github.io, custom domains, and/<repo>/forks (verifyingdocs-portal/.vitepress/dist/SHA256SUMSviascripts/release-integrity.sh verify-tree-sumsandsha256sum --check --strictbeforeactions/upload-pages-artifact), or falls back to rebuilding all three surfaces (SKIP_DOC_SYNC=true npm run docs:build,npm run build:export+npm run test:e2e:static, andnpm run build-storybook+npm run test:e2e:storybookaligned to the configured Pages base paths, verifying downloaded/rebuiltstorybook-staticSHA256SUMSand generating/verifying unifiedSHA256SUMSviascripts/release-integrity.sh) if Pages settings changed mid-run, verifiesindex.html,demo/index.html,storybook/index.html, and.nojekyllexist, and uploads thegithub-pagesartifact (actions/upload-pages-artifact).deploy-docs(ci.yml): Isolated checkout-free Pages deployment job (needs: [ci-complete, prepare-docs],pages: write,id-token: write,timeout-minutes: 10,concurrency: { group: github-pages, cancel-in-progress: false, queue: max }, zeroactions/checkoutand zeronpm) that publishes the verified artifact to thegithub-pagesenvironment viaactions/deploy-pageswhenneeds.prepare-docs.outputs.is_latest == 'true'.
2. Artifact Publication (publish-artifact.yml)
- Triggers & Concurrency: Reusable
workflow_callfromdeploy.yml(afterCIsucceeds onmain), pushes tov*tags, and manualworkflow_dispatch, serialized inside a single sharedpublish-artifact-releaseconcurrency group (cancel-in-progress: false,queue: max) so parallelv*tag andmainruns queue in FIFO order (up to 100 runs) and never race on:latestor BuildKit caches. Pushing av*tag triggerspublish-artifact.ymldirectly (without re-runningci.yml):publish-artifact.ymlfetchesorigin/main,origin/release/*, andrefs/tags/v*, verifiesorigin/mainancestry (orN-1v*maintenance tag lineage onorigin/release/*descending from a matchingvMAJOR.MINOR.*tag on an advancedorigin/main), delegates active CI polling (--poll-ci) and completed trusted CI verification (--ci-only) toscripts/verify-release-target.sh, promotes the already-publishedghcr.io/<owner>/<repo>:<sha>multi-platform artifact directly viascripts/ghcr-release-promotion.shwhen bothlinux/amd64andlinux/arm64manifests plus OIDC SLSA provenance and SPDX SBOM attestations verify cleanly (falling back automatically to native matrix builds if:<sha>is absent or incomplete), publishes bothghcr.io/<owner>/<repo>:<GITHUB_REF_NAME>(such as:v0.1.0) andghcr.io/<owner>/<repo>:<sha>, and updates:latestidentically across GHCR and optional Docker Hub only when a pushedorigin/mainstable SemVer tag (vMAJOR.MINOR.PATCH) equals or exceeds every stable repository version tag (ignoring pre-release tags such asv2.2.0-rc.1, while manualworkflow_dispatch/commit_sha/ customtag_nameruns, default-branch non-tag builds, and non-mainN-1maintenance patch tags onorigin/release/*such asv1.0.1forcePUBLISH_LATEST=falseand never overwrite:latest) without automatically invokingdeploy.yml; operators can promote a tagged release viadeploy.yml(workflow_dispatchwithimage_tag: v0.1.0,release_ref: v0.1.0, orimage_digest, resolvingtarget_shato the tag's source commit before executingschema-compatibilityanddb-migrate.yml) ordeploy-provider.yml(image_tag: v0.1.0afterdb-migrate.yml). - Runner Quotas & Timeouts: When
buildis not skipped via attested GHCR promotion, nativelinux/amd64andlinux/arm64matrix builds run on GitHub-hostedubuntu-latestandubuntu-24.04-armrunners, which run free on public repositories (private forks may require paid runner quotas or runner overrides). Jobs enforce explicittimeout-minutesbudgets (preflight: 45covering the 2400-second /42m-boundedverify-cipolling loop and5mGHCR attestation inspection,build: 35with20mBuildKit and5mcache-persist/Trivy/SBOM step bounds,upload-sarif: 10for isolated checkout-free Code Scanning SARIF submission, andpublish: 20with2mscopedDOCKER_CONFIGregistry login,5mSBOM verification/archive push/index merge, and3mper-step OIDC provenance and SPDX SBOM attestation bounds) sopublish-artifact-releaseFIFO locks cannot stall for 6 hours. - Permissions: Top-level
contents: read;preflightscopescontents: read,actions: read,packages: read, andattestations: read(fororigin/mainancestry, SemVer tag resolution,ci.ymlstatus verification, and read-only GHCR manifest + OIDC attestation inspection and SBOM extraction),buildretains strictlycontents: read(with zero write permissions or registry credentials), checkout-freeupload-sarifholds strictlycontents: readandsecurity-events: write(uploadingtrivy-sarif-amd64andtrivy-sarif-arm64artifacts viagithub/codeql-action/upload-sarif), and checkout-freepublishscopescontents: read,packages: write(for GitHub Container Registry),id-token: write, andattestations: write(for OIDC cryptographic build provenance attestations; callerdeploy.ymlretains the union of callee-required scopes and passes explicitDOCKERHUB_USERNAME/DOCKERHUB_TOKENsecrets). - Actions:
- Runs a
preflightgate before building that fetchesorigin/main,origin/release/*, and full repositoryrefs/tags/v*history (fetch-depth: 0,persist-credentials: false), computes target OCI tags and SemVer 2.0.0:latesteligibility (forcingPUBLISH_LATEST=falseoutsideorigin/main), verifies the 40-character target commit (inputs.commit_shaorgithub.sha) is an ancestor oforigin/main(git merge-base --is-ancestor) or anN-1v*tag onorigin/release/*descending from a matchingvMAJOR.MINOR.*tag on an advancedorigin/main, polls active trustedci.ymlworkflow runs (scripts/verify-release-target.sh --poll-ci) and verifies the latest completed trustedci.ymlrun succeeded (scripts/verify-release-target.sh --ci-only), and—onpush(v*tags) andworkflow_dispatchruns—inspectsghcr.io/<owner>/<repo>:<resolved_sha>(scripts/ghcr-release-promotion.sh inspect-preflight,extract-promoted-sboms, andmirror-promoted-digestswith temporaryDOCKER_CONFIGisolation) to verify bothlinux/amd64andlinux/arm64manifests,org.opencontainers.image.revision, and OIDC SLSA provenance + SPDX SBOM attestations signed by.github/workflows/publish-artifact.yml(outputs.promote_existing, uploadingpromoted-oci-metadata). - When
promote_existing != 'true'(ondeploy.ymlworkflow_callruns aftermainmerges or whenever no complete attested:<sha>artifact exists yet), builds nativelinux/amd64(ubuntu-latest) andlinux/arm64(ubuntu-24.04-arm) container images once per architecture as local OCI archives (outputs: type=oci,dest=/tmp/oci-<arch>.tar,provenance: false,sbom: false, stamped withorg.opencontainers.image.revisionlabels andmanifest:org.opencontainers.image.revisionannotations) in parallel (buildmatrix job,needs: [preflight],contents: read) without QEMU emulation, hydrating and persisting non-empty per-architecture BuildKit cache mounts (/var/cache/apt,/var/lib/apt,/root/.npm,/app/.next/cache) via hash-lockedrelease-buildkit-deps-*andrelease-buildkit-next-*actions/cachekeys (omitting prefixrestore-keys, extracting validated archives with--no-same-owner --no-same-permissions, and exporting viascripts/persist-buildkit-mounts.sh) while isolating release BuildKit GitHub Actions cache scopes (release-app-amd64andrelease-app-arm64, includingGHA_CACHE_SCOPEfordocker-compose.ci.ymlsmoke tests) fromci.yml(app-amd64andapp-arm64). - Loads
wedding-website:latestdirectly from each exported OCI archive into the local Docker daemon viaskopeo copy, executes Trivy vulnerability scanning (aquasecurity/trivy-action) on bothlinux/amd64andlinux/arm64native images—failing the workflow before archive handoff whenever either architecture contains fixableCRITICAL,HIGH, orMEDIUMseverity vulnerabilities (ignore-unfixed: true) or embedded secrets—and generates per-architecture SPDX JSON SBOMs (sbom-amd64.spdx.jsonandsbom-arm64.spdx.json). - Exports per-architecture SARIF vulnerability artifacts (
trivy-sarif-amd64andtrivy-sarif-arm64) frombuildand submits them to GitHub Code Scanning viagithub/codeql-action/upload-sarifinside the separate checkout-freeupload-sarifjob (contents: read,security-events: write). - Runs native container & clean-database migration smoke tests (
scripts/test-container.mjswithSKIP_IMAGE_BUILD=true) against that exact loaded image on bothubuntu-latestandubuntu-24.04-armhosts, validates non-empty SPDX.packagesarrays viascripts/release-integrity.sh verify-spdx, compresses each verified OCI archive withzstd, computes and verifiessha256-${arch}.sumsoveroci-${arch}.tar.zstandsbom-${arch}.spdx.jsonviascripts/release-integrity.sh, and uploads the archive, its inspectedsha256manifest digest, its validated SPDX SBOM, andsha256-${arch}.sumsas workflow artifacts (oci-archive-amd64andoci-archive-arm64). - Executes the isolated checkout-free
publishjob withoutactions/checkout,npm, or repository scripts, scopingdocker/login-actionand registry commands to a temporaryDOCKER_CONFIGdirectory (mktemp -d) that is deleted viaif: always()beforeSummaryruns: whenpromote_existing == 'true', downloadspromoted-oci-metadatafrompreflight, verifies non-empty SPDX.packagesarrays, re-verifies the promoted index'samd64/arm64digests andorg.opencontainers.image.revisionviadocker buildx imagetools inspect, and mirrors verifiedamd64/arm64digests to optionaldocker.ioviaskopeo copy --preserve-digests; otherwise downloadsoci-archive-amd64andoci-archive-arm64, verifiessha256-amd64.sumsandsha256-arm64.sumsviasha256sum --check --strictplus non-empty SPDX.packagesarrays beforezstddecompression,skopeo inspect, or OIDC signing, decompresses the archives, re-verifies bothlinux/amd64andlinux/arm64archive manifest digests viaskopeo inspectbefore any external registry upload, and pushes each verified archive viaskopeo copy --preserve-digeststoghcr.io(and optionaldocker.io). In both paths,publishmerges the verified digests into multi-platform OCI indexes viadocker buildx imagetools create(stampingindex:org.opencontainers.image.revision, verifying bothlinux/amd64andlinux/arm64manifests plusorg.opencontainers.image.revisionviadocker buildx imagetools inspect, and taggingGITHUB_REF_NAME, the commit SHA, and SemVer-gated:latestidentically across GHCR and optional Docker Hub), and synthesizes a combined multi-platform index SPDX 2.3 SBOM (sbom-index.spdx.json) validated for non-empty.packages. - Generates signed OIDC SLSA build provenance (
actions/attest-build-provenance# v4.2.2) and SPDX SBOM (actions/attest# v4.2.2) attestations across per-architecture (amd64,arm64) and merged multi-platform index digests whenpromote_existing != 'true', while gating per-architectureactions/attest-build-provenance(GHCR and Docker Hub) and GHCR per-architectureactions/attestwhenpromote_existing == 'true'soubuntu-latestnever misattributes nativelinux/arm64build provenance while keeping multi-platform index provenance and index SPDX SBOM attestations active on all runs (compatible withgh attestation verifyindeploy-provider.yml,deploy.yml,rollback.yml, andrelease.yml, and conditionally signing Docker Hub attestations withcreate-storage-record: falsewhen Docker Hub credentials are configured).
- Runs a
- Outputs:
image_uri: Primary OCI URI (ghcr.io/<owner>/<repo>:<sha>onmain/workflow_call, orghcr.io/<owner>/<repo>:v*onv*tag pushes alongside:<sha>).image_tag: Resolved version tag (GITHUB_REF_NAMEonv*tag pushes) or immutable commit SHA.image_digest: Attested OCI image digest (sha256:<64-hex>) propagated to staging and production deployment jobs.
2b. GitHub Release Publication (release.yml)
- Triggers & Concurrency: Triggers via
workflow_runafterPublish Release Artifact(publish-artifact.yml) completes successfully onv*tag pushes (without automatically invokingdeploy.yml), or via manualworkflow_dispatchwith an explicittag_name(v*), serialized per release tag viaconcurrency: { group: github-release-${{ github.event.workflow_run.head_branch || inputs.tag_name || github.ref_name }}, cancel-in-progress: false, queue: max }. - Secrets required: None (authenticates via built-in
github.tokenand GitHub OIDC provenance signing). - Permissions & Untrusted-Trigger Isolation: Top-level
contents: read; splits work into a strictly read-onlyprepare-releasejob (timeout-minutes: 15,contents: read,actions: read,packages: read,attestations: read, zero write scopes) and a checkout-freepublish-releasejob (timeout-minutes: 10,contents: write,id-token: write,attestations: write, zeroactions/checkoutand zeronpm ci) complying withnpm run check:action-pinsworkflow_runwrite-isolation rules. - Actions:
prepare-release(release.yml): Sets up Docker Buildx ahead ofresolve, validates the Semantic Versioningv*tag, fetchesorigin/mainandrefs/tags/v*, verifies tag commit alignment withworkflow_run.head_sha, delegatesorigin/mainancestry (orpublish-artifact.ymlOIDCmaintenance-tagprovenance) and paginated trustedci.ymlverification toscripts/verify-release-target.sh --target-sha "$TARGET_SHA" --release-tag "$TAG_NAME"(forcingMAKE_LATEST=falseoutsideorigin/main), verifies OIDC SLSA provenance on the published GHCRv*multi-platform index pluslinux/amd64andlinux/arm64digests and extracts all three validated SPDX SBOMs (sbom-index.spdx.json,sbom-amd64.spdx.json,sbom-arm64.spdx.json) viascripts/ghcr-release-promotion.sh extract-release-sboms, archives the deterministic Track C host source bundle (wedding-website-<tag>.tar.gzviagit archive), generates and verifiesSHA256SUMSviascripts/release-integrity.sh, extracts categorized release notes fromCHANGELOG.md(extract-changelog-notes), and uploadsrelease-bundle.publish-release(release.yml): Downloadsrelease-bundlewithout checking out repository code, verifiessha256sum --check --strict SHA256SUMS, symlink absence, exact asset list parity, and non-empty SPDX.packagesarrays before signing, attestsSHA256SUMS,sbom-index.spdx.json,sbom-amd64.spdx.json,sbom-arm64.spdx.json, andwedding-website-<tag>.tar.gzviaactions/attest-build-provenance(# v4.2.2), and publishes (or idempotently updates on manual dispatch reruns) the GitHub Release viagh release createwith SemVer--prerelease/--latestflags.
3. Database Migration (db-migrate.yml)
- Triggers: Reusable
workflow_callfromdeploy-stage.yml(confirmdefaults totrue,caller_holds_lock: true), or standalone manualworkflow_dispatchwith target environment (production,staging,development) and explicit confirmation (confirmdefaults tofalse). - Concurrency: Acquires
deploy-env-${{ inputs.environment || 'production' }}(cancel-in-progress: false,queue: max) on standalone runs (caller_holds_lock: false), or scopes tocaller-db-migrate-<environment>-${{ github.run_id }}-${{ github.run_attempt }}whencaller_holds_lock: trueso nested stage runs avoid nested lock contention againstdeploy-stage.yml. - Secrets required:
DATABASE_URL(plus optionalPOSTGRES_URL_NON_POOLINGdirect connection URL whenDATABASE_URLuses PgBouncer). - Timeouts:
preflightenforcestimeout-minutes: 5(with1m–3mstep bounds) andmigrate(needs: [preflight]) enforcestimeout-minutes: 10at the job level withtimeout-minutes: 5onstatus_check(Pre-flight schema migration check and summary) andmigrate(Run Prisma Migrate Deploy). - Actions:
- Runs a read-only
preflightjob (contents: read,actions: read,packages: read,attestations: read, zeroenvironment:secret exposure) beforemigratethat enforcesinputs.confirm == truefirst, checks out the repository (fetch-depth: 0,persist-credentials: false), and verifiesinputs.commit_sha || github.shaviascripts/verify-release-target.sh(origin/mainancestry or OIDC-attestedrefs/tags/v*maintenance provenance plus a completed passingci.ymlrun ongithub.repository), failing unmerged branches and unattested tags before unlockingsecrets.DATABASE_URL. - Declares
needs: [preflight]andenvironment: ${{ inputs.environment || 'production' }}on themigratejob (Execute Database Migrations), enforcing GitHub Environment Protection Rules and pausing for human reviewer sign-off before exposingproductionsecrets. - Verifies
inputs.confirm == true(Verify Manual Migration Confirmation), checks out and aligns toneeds.preflight.outputs.target_sha, and installs dependencies vianpm ci --ignore-scriptsso lifecycle scripts never execute in the secret-bearing environment. - After environment unlock and confirmation, runs
npm run lint:migrationsand validatesDATABASE_URL(and non-emptyPOSTGRES_URL_NON_POOLING) format. - Queries the live target database via
npx prisma migrate status(npx tsx scripts/preflight-migration-summary.ts --require-db, preserving normalizedPOSTGRES_URL_NON_POOLINGforprisma.config.tsand verifying libpq TLS handshakes viaverifyPostgresTlsHandshakeagainst the effective migration target URL first) after theconfirmgate to emit pending migration SQL DDL summaries and fail closed with redacted diagnostics on TLS errors, connectivity errors, schema drift, or failed migrations in$GITHUB_STEP_SUMMARY. - Verifies libpq TLS handshakes (
verifyPostgresTlsHandshake) on the effective migration endpoint, executesnpx prisma migrate deployagainstDATABASE_URL(and optionalPOSTGRES_URL_NON_POOLINGviaprisma.config.ts) withPGOPTIONS="-c lock_timeout=5000ms -c statement_timeout=30000ms", and recordsRecord Migrated Commit (<target_sha>)asserting workspaceHEADmatchesneeds.preflight.outputs.target_shafor downstreamstandalone-gateverification. - Emits diagnostic error signaling and resolution guidance if migration fails.
- Runs a read-only
4. Provider Deployment Adapter (deploy-provider.yml)
- Triggers: Reusable
workflow_callfromdeploy-stage.ymlwithimage_digestandcaller_holds_lock: true, rollback pipeline (workflow_callfromrollback.yml) withimage_digest/image_tag, optionalrollback_environment, andcaller_holds_lock: true, or standalone manualworkflow_dispatchwith an explicitimage_digest(sha256:<64-hex>) or immutable release/commitimage_tag(unpinnedlatesttags are rejected). - Concurrency: Acquires
deploy-env-${{ inputs.environment || 'production' }}(cancel-in-progress: false,queue: max) whencaller_holds_lockisfalse(keyed on targetenvironment, neverrollback_environment), or scopes tocaller-deploy-provider-<environment>-${{ github.run_id }}-${{ github.run_attempt }}whencaller_holds_lockistrue. - Permissions: Top-level
contents: read; read-onlypreflightscopesactions: read,contents: read,packages: read, andattestations: read(withoutenvironment:or write tokens) for repository checkouts,scripts/resolve-oci-provenance.sh,npm run lint:migrations, and signed-revisionci.yml/db-migrate.ymlverification, while checkout-freedeploy(and reusable workflow caller jobs) scopesactions: read,contents: read,packages: read,attestations: read,deployments: write, andid-token: writefor active revision capture, environment-filtered GitHub Deployments state tracking, and Google Cloud Workload Identity Federation. - Secrets & Variables:
- Environment Variables:
SERVICE_URL(vars.SERVICE_URLprimary, withsecrets.SERVICE_URLsupported as a legacy fallback),CLOUD_RUN_SERVICE(defaults towedding-website-stagingforstagingandwedding-websiteforproduction),CLOUD_RUN_REGION(defaults tous-central1), and primary keyless OIDC authentication variablesGCP_WORKLOAD_IDENTITY_PROVIDER+GCP_SERVICE_ACCOUNT. - Environment Secrets: Static fallback
GCP_SA_KEYand optionalGCP_PROJECT_IDforgoogle-cloud-run, orDEPLOY_WEBHOOK_URLand mandatory HMAC signing secretDEPLOY_WEBHOOK_SECRETforgeneric-webhookanddocker-host(DATABASE_URLandPOSTGRES_URL_NON_POOLINGare omitted fromdeploy-provider.yml).
- Environment Variables:
- Inputs:
environment: Target deployment environment (productionorstaging).rollback_environment: Optional unguarded GitHub Environment override (workflow_callonly) for rollback secret resolution when invoked byrollback.yml.commit_sha: Optional 40-character hexadecimal commit SHA checked out (fetch-depth: 0inpreflight), stamped onto Cloud Runcommit-shalabels, and assigned toCURRENT_SHAfor rollback history guards and GitHub Deployments tracking (defaults togithub.shawhen omitted onworkflow_dispatch).image_digest: Immutable OCI image digest (sha256:<64-hex>) to deploy directly.image_tag: Immutable version tag (v*, verifying--source-ref refs/tags/<image_tag>) or commit SHA (verifying--source-ref refs/heads/main, resolved to an immutablesha256digest viadocker buildx imagetools inspectwhenimage_digestis omitted).source_ref: Optional expected OIDC provenance source ref override (refs/heads/mainorrefs/tags/v*; digest-only and SHA rollouts also acceptrefs/tags/v*-attested release artifacts).provider: Hosting provider adapter (google-cloud-run,docker-host, orgeneric-webhook).cloud_run_service/cloud_run_region: Optional Cloud Run target overrides resolved ahead ofvars.CLOUD_RUN_SERVICE/vars.CLOUD_RUN_REGIONand environment defaults.dry_run: Explicit dry-run validation flag (falseby default;is_dry_runis never coerced totruewhen secrets are missing).caller_holds_lock: Boolean (falseby default) indicating whether the parent workflow (deploy-stage.ymlorrollback.yml) already holdsdeploy-env-<environment>.auto_rollback_on_failure/previous_tag/is_rollback: Optionalworkflow_callinputs enabling automatic in-job fallback restoration insidedeploy-provider.ymlwhen/api/healthor/api/readyfails or times out androllback_environmentis empty, and marking cancellation-safe rollback redeployments invoked byrollback.yml.
- Outputs:
service_url: Target deployment service URL (secrets.SERVICE_URLvalues are redacted from$GITHUB_OUTPUTand$GITHUB_STEP_SUMMARY).is_dry_run: Boolean flag indicating if deployment executed in explicit dry-run mode (inputs.dry_run == true).previous_image_tag: Prior immutable container image tag or GHCR-verified release SHA captured before rollout.previous_image_digest: Prior immutablesha256OCI image digest captured before rollout (from the serving Cloud Run revision forgoogle-cloud-run, or resolved viadocker buildx imagetools inspectfrom the last non-dry-run target-environment release fordocker-hostandgeneric-webhook).image_digest: Verified immutablesha256OCI image digest deployed.image_uri: Full digest-pinned OCI image URI (ghcr.io/<owner>/<repo>@sha256:<hex>).attestation_status: OIDC build provenance attestation verification status (verified).cloud_run_service/cloud_run_region: Resolved Cloud Run service name and region forwarded to downstream rollback jobs.health_status/http_status: Bounded/api/healthand/api/readyprobe outcome (healthy/unhealthy) and HTTP status code consumed bydeploy-stage.ymlandrollback.yml.rollout_executed/inline_rollback_completed: Provider rollout and automatic in-job fallback rollback completion flags consumed bydeploy-stage.yml.
- Actions:
- Splits execution into a read-only
preflightjob (if: always(),timeout-minutes: 10, zero write scopes and noenvironment:) and a checkout-freedeployjob (needs: [preflight],if: always() && (!cancelled() || needs.preflight.outputs.is_rollback_call == 'true') && needs.preflight.result == 'success',environment: ${{ (github.event_name == 'workflow_call' && inputs.rollback_environment) || inputs.environment || 'production' }}, andtimeout-minutes: 20with step-leveltimeout-minutesof2–5minutes across GCP auth, active revision capture, Cloud Run / webhook rollout, GitHub Deployments API updates,120s/api/health+/api/readypolling, and inline fallback rollback, plus cancellation-safe prior-step outcome guards vianeeds.preflight.outputs.is_rollback_callon rollback paths), enforcing GitHub Environment Protection Rules and reviewer sign-off for allworkflow_dispatchand forwardproductionreleases while supporting unguarded rollback environments and cancelled-run recovery exclusively duringworkflow_callrollbacks without exposing deployment secrets or write tokens toactions/checkout,npm, or repository scripts. - In
preflight, checks out the trusted default branch (fetch-depth: 0,persist-credentials: false), rejects unpinnedlatesttags, resolves tag-only manual or rollback dispatches to immutablesha256digests viadocker buildx imagetools inspect(with scoped temporaryDOCKER_CONFIG), validates digests against^sha256:[a-f0-9]{64}$, runsnpm run lint:migrationsviaactions/setup-node(.nvmrc) strictly against verified release/default-branch code before checking outcommit_sha(path: target-commit,fetch-depth: 0,persist-credentials: false) solely to export parent commit SHAs (git rev-list), and deletestarget-commitimmediately without executing any code fromcommit_sha. - Runs
gh attestation verifyagainstoci://ghcr.io/<owner>/<repo>@sha256:<hex>with--owner,--signer-workflow <owner>/<repo>/.github/workflows/publish-artifact.yml, and--source-ref(refs/tags/<image_tag>forv*tags orrefs/heads/main), resolves the signed 40-charactersource_revisionviascripts/resolve-oci-provenance.shfrom attested OCIorg.opencontainers.image.revisionmetadata and SLSAinputs.commit_shaahead of OIDCGITHUB_SHAdigests (failing closed if OCI indexorg.opencontainers.image.revisionconflicts with SLSAinputs.commit_sha), aligns non-rollback checkouts wheninputs.commit_shais empty tosteps.provenance.outputs.source_revision(git checkout --detachwith parent history), emitscloud_run_labels(commit-sha=<source_revision>) ahead ofinputs.commit_sha, and confirms viascripts/verify-release-target.sh --ci-onlythat the latest completed trustedci.ymlrun for that revision succeeded before invoking any provider adapter or dry-run step. - On standalone live promotions (
workflow_dispatchwith!inputs.dry_run), resolvestarget_sha(fromimage_tagor verified OIDC attestation reading OCIorg.opencontainers.image.revisionand SLSAinputs.commit_shaahead ofsourceRepositoryDigest), verifiesorigin/mainancestry (or OIDC-attestedrefs/tags/v*maintenance provenance) and passingci.ymlstatus viascripts/verify-release-target.sh, detachesHEADtotarget_shawith parent history, and instandalone-gateconfirms passingci.ymlstatus viascripts/verify-release-target.sh --ci-onlyand queries completeddb-migrate.ymlanddeploy.ymlruns (exclude_pull_requests: true, non-nullhead_repository == github.repository, without ahead_shafilter soworkflow_dispatchruns onmainare discovered) requiringExecute Database Migrationsto succeed onVerify Manual Migration Confirmation,Record Target Environment (<env>), andRecord Migrated Commit (<target_sha>)before touching provider credentials or deploying. - Fails closed on live runs (
!inputs.dry_run) inVerify Selected Provider Credentialswhen required adapter credentials are absent (requiringGCP_WORKLOAD_IDENTITY_PROVIDER+GCP_SERVICE_ACCOUNTor fallbackGCP_SA_KEYforgoogle-cloud-run, and bothDEPLOY_WEBHOOK_URL+DEPLOY_WEBHOOK_SECRETforgeneric-webhook/docker-host). - Captures
previous_image_digestandprevious_image_tagbefore rollout:google-cloud-runinspects the currently serving Cloud Run revision in the resolved service and region (extractingprevious_image_tagon@sha256:serving revisions from OIDC provenance attestations, Cloud Runcommit-sha/ OCIorg.opencontainers.image.revisionlabels, or image tags), falling back across all providers (google-cloud-run,docker-host, andgeneric-webhook) to environment-scoped GitHub Deployments (deployments: write) withsuccessstatus, completed non-dry_runtarget-environment (stagingorproduction)deploy.yml(matching both nesteddeploy-stage.ymljob prefixesStaging Deployment Stage / Provider Deployment (staging)/Production Deployment Stage / Provider Deployment (production)and legacy job names) anddeploy-provider.ymlworkflow runs, GHCR-published candidate tags verified viadocker buildx imagetools inspect(skipping unpublishedHEAD^1commits), andHEAD^1/ commit parents relative toEFFECTIVE_TARGET_SHA(needs.preflight.outputs.standalone_target_sha || needs.preflight.outputs.source_revision || inputs.commit_sha || github.sha). - Deploys the digest-pinned
@sha256:container URI to the hosting provider (Google Cloud Run via Workload Identity Federation OIDC orGCP_SA_KEYfallback with attestedsource_revisioncommit-sharevision labels, or stateless webhookPOSTfordocker-hostandgeneric-webhooktoDEPLOY_WEBHOOK_URLsigned with HMAC-SHA256 headersX-Hub-Signature-256,X-Deploy-Timestamp, andX-Deploy-Signature-256plus--fail-with-bodyHTTP error enforcement), creates the GitHub Deployment (refandpayload.commit_shaset fromsource_revision/target_sha) withstate: "in_progress"(auto_inactive: false), polls${TARGET_URL}/api/healthand${TARGET_URL}/api/ready(curl --connect-timeout 5 --max-time 10, resolvingvars.SERVICE_URL, Cloud Run URL, and legacysecrets.SERVICE_URLin memory), postsstate: "success"(auto_inactive: true) only after/api/healthand/api/readysucceed (orstate: "failure"viaif: always()on failure/cancellation), runs automatic in-job fallback restoration whenauto_rollback_on_failure: trueandrollback_environmentis empty, and writes the deployment summary to$GITHUB_STEP_SUMMARY.
- Splits execution into a read-only
- Signed Webhook Wire Contract (
docker-host&generic-webhook):- Endpoint & Secrets: Sends an authenticated
POSTrequest (Content-Type: application/json, 10s connect timeout, 30s max runtime) tosecrets.DEPLOY_WEBHOOK_URLsigned withsecrets.DEPLOY_WEBHOOK_SECRET. - JSON Payload (
{image, digest, environment}) & Multi-Line Raw-Byte Formatting: ConstructsPAYLOADviajq -n(without-c), producing pretty-printed multi-line UTF-8 JSON with 2-space indentation and internal\nnewlines (trailing newline stripped by command substitution;digestis omitted only when empty):jsonStateless webhook listeners must compute HMAC digests over the exact raw HTTP request body bytes ({ "image": "ghcr.io/<owner>/<repo>@sha256:<64-hex>", "digest": "sha256:<64-hex>", "environment": "production" }PAYLOAD) before parsing JSON — re-serializing withJSON.stringify(body)changes whitespace and invalidates both signatures. - Dual-HMAC & Replay Headers:
X-Deploy-Timestamp: <unix-seconds>— UTC epoch timestamp (date -u +%s). Receivers should enforce a replay window (recommended±300seconds) before pulling containers.X-Hub-Signature-256: sha256=<64-hex>—HMAC-SHA256(DEPLOY_WEBHOOK_SECRET, PAYLOAD)computed over the rawPAYLOADbytes.X-Deploy-Signature-256: sha256=<64-hex>—HMAC-SHA256(DEPLOY_WEBHOOK_SECRET, "${X-Deploy-Timestamp}.${PAYLOAD}")computed over${X-Deploy-Timestamp}.${PAYLOAD}, cryptographically binding the timestamp and raw payload against replay attacks.
- Endpoint & Secrets: Sends an authenticated
5. Stage Orchestration, Post-Deployment Verification & Automated Rollback (deploy.yml, deploy-stage.yml & rollback.yml)
- Triggers:
deploy.ymltriggers viaworkflow_runafterCIcompletes successfully onmainpushes (or viaworkflow_dispatch/workflow_callwith optionalimage_tag,release_ref,image_digest, orworkflow_callcommit_sha, resolvingv*release tags and attestedimage_digestprovenance via OCIorg.opencontainers.image.revision/ SLSA provenance totarget_shaand confirming a successfulCIrun fortarget_shabefore executingschema-compatibilityand delegatingstaging/productionstages to.github/workflows/deploy-stage.yml), running health verification automatically post-provider deployment (rollback.ymlcan also be invoked manually viaworkflow_dispatchwithprevious_digestand/orprevious_tagand optional 40-charactercommit_sha, defaulting togithub.sha). - Stage Concurrency, FIFO Queuing & Timeouts:
deploy.ymldefines no root-levelconcurrencyblock so preflight gates (ci-gateandschema-compatibility, each bounded attimeout-minutes: 10with3m–5mstep bounds on SHA/provenance resolution, CI status verification, and commit alignment) andpublish-artifactstart immediately.deploy-stage.ymlholdsconcurrency: { group: deploy-env-${{ inputs.environment }}, cancel-in-progress: false, queue: max }across the full sequential stage lifecycle (database-migration->deploy-provider->verify-deployment-> conditionalrollback), passescaller_holds_lock: trueand minimal explicit secret maps to child workflows (forwardingDATABASE_URLandPOSTGRES_URL_NON_POOLINGsolely todb-migrate.yml, and only provider/service secrets todeploy-provider.ymlandrollback.yml), and boundsverify-deploymentattimeout-minutes: 5(withtimeout-minutes: 3on the120shealth/readiness probe step).- Standalone
rollback.ymldispatches (caller_holds_lock: false) acquiredeploy-env-${{ inputs.target_environment || 'production' }}(cancel-in-progress: false,queue: max) keyed ontarget_environment(neverrollback_environment), passcaller_holds_lock: truefromredeploytodeploy-provider.ymlso manualproduction-rollbackruns serialize cleanly against activeproductionpromotions, and cap all three runner jobs (preflight,verify, andreport) attimeout-minutes: 5(withtimeout-minutes: 3onVerify Rollback Digest Deployment Historyandtimeout-minutes: 2onPoll Restored Service Health) so hung API or registry calls abort quickly and releasedeploy-env-<environment>.
- Actions:
verify-deployment(deploy-stage.yml) enforcestimeout-minutes: 5and consumeshealth_statusandhttp_statusfromdeploy-provider.yml(with fallback/api/healthand/api/readypolling usingcurl --connect-timeout 5 --max-time 10, exponential backoff, and a 2-minute loop timeout).- Validates HTTP status code 200 on
/api/health(.data.database == "connected"and.data.status == "ok") and/api/ready(status == "ready"anddatabase == "connected"). - Automatically invokes
rollback.yml(withcaller_holds_lock: true,commit_sha,previous_image_digest,previous_image_tag,provider,cloud_run_service,cloud_run_region, and job-scopedactions: readanddeployments: write) if health or readiness probes fail or are cancelled (failure() || cancelled()), accepting digest-pinned rollbacks while rejecting mutablelatestor the failingCURRENT_SHA(inputs.commit_sha || github.sha) outside explicit dry-run mode. rollback.ymlverifies inpreflight(deployments: read,packages: read,attestations: read) thatprevious_digest/previous_tagdoes not matchCURRENT_SHAand succeeded earlier intarget_environmentGitHub Deployments beforeredeploystarts, checks out the pinnedcommit_sha(persist-credentials: false, rather than driftedHEAD) to runnpm run lint:migrations, callsdeploy-provider.yml(caller_holds_lock: true) using the unguardedrollback_environment, consumeshealth_statusandhttp_statusfromdeploy-provider.yml(with fallback${SERVICE_URL}/api/healthpolling for.data.status == "ok"and.data.database == "connected"and${SERVICE_URL}/api/readypolling forstatus == "ready"anddatabase == "connected") without a duplicateproductionenvironment gate onverify, and gates$GITHUB_STEP_SUMMARYstatus reporting so any failed stage logsFAILEDand exits non-zero.
🚀 Rollout Sequence & Zero-Downtime Migration Expectations
To ensure zero downtime and prevent application outages:
- Schema Changes Must Be Backward-Compatible:
- Use the expand-contract migration pattern.
- Adding new columns/tables: Must be nullable or have default values.
- Deleting or renaming columns/tables: Must be performed in a subsequent release after application code no longer queries old schema elements.
- Execution Order:
- Step 1: CI verifies codebase integrity and container runtime.
- Step 2: Artifact Publication builds and pushes immutable image tagged by SHA.
- Step 3: Database Migration applies non-breaking migrations to production database.
- Step 4: Provider Deployment updates container instances to the new image SHA.
- Container Entrypoint:
- Application containers default to skipping automatic migrations (
RUN_MIGRATIONS=false). - Migrations are managed explicitly via
db-migrate.ymlor dedicated release jobs to prevent concurrent migration race conditions across multi-replica deployments.
- Application containers default to skipping automatic migrations (
Database Migrations & Portable PostgreSQL Contract
The application defines a strict PostgreSQL Database Contract. It depends solely on standard PostgreSQL capabilities and is completely portable across database providers and self-hosted environments.
Database migrations are run automatically using npx prisma migrate deploy in the db-migrate.yml workflow before the new application code goes live. Schema migrations are completely decoupled from application container boot (docker-entrypoint.sh), allowing application instances to start immediately without database lock contention during horizontal scaling. In local Docker Compose environments, a dedicated migration task service executes ./node_modules/.bin/prisma migrate deploy offline before the application service starts (and standalone containers setting RUN_MIGRATIONS=true or RUN_MIGRATIONS=1 run /usr/local/bin/prisma migrate deploy offline via /opt/prisma-cli). Before migrations are executed, a pre-migration backwards compatibility check (npm run lint:migrations) runs to verify zero-downtime safety.
Minimum Supported Database Specification
- Supported Database: PostgreSQL 15 or higher (
PostgreSQL 15+; the CI test suite and standard container setup usepostgres:15-alpine). - ORM / Client: Prisma ORM with
@prisma/adapter-pgdriver adapter andpgpool.
Connection String Expectations
DATABASE_URL(Required —datasource.urlinprisma.config.ts): The primary connection string read by both the Next.js runtime application andnpx prisma migrate deploy.- Standard URI Format:
postgresql://[user]:[password]@[host]:[port]/[database]?sslmode=[mode] - Example (Local PostgreSQL):
postgresql://wedding:wedding123@localhost:5432/wedding - Example (Cloud Host with SSL):
postgresql://user:pass@ep-example.us-east-1.aws.neon.tech/wedding?sslmode=require - Example (Cloud SQL / Unix Domain Socket):
postgresql://wedding_user:STRONG_PASSWORD@localhost/wedding_db?host=/cloudsql/YOUR_PROJECT_ID:us-central1:wedding-db(specify@localhostin the authority segment for Prisma CLI compatibility; legacy empty-host@/socket URIs with a valid?host=/...path are normalized to@localhostautomatically) - URI Schema, Pool & Timeout Flags: Runtime
pg.Pooland@prisma/adapter-pghonor?schema=(defaultpublic; validated as a 1–63 byte PostgreSQL identifier/^[A-Za-z_][A-Za-z0-9_$]*$/, double-quoted across/api/ready,AuthLockout, and all raw SQL$queryRaw/$executeRawqueries, and bound via-c search_pathon direct non-pooledpg.Poolconnections while omitting startupoptionson PgBouncer/transaction poolers),?connection_limit=(defaultmax=5, keeping three instances safely belowdb-f1-micro'smax_connections=25),?connect_timeout=/?pool_timeout=in seconds (default10s/10000msto tolerate serverless cold wakes),?socket_timeout=in seconds (default clientquery_timeout=10000msonpg.Poolso hung PostgreSQL queries never block/api/healthindefinitely), and?statement_timeout=in milliseconds.
- Standard URI Format:
POSTGRES_URL_NON_POOLING(Optional — inspected byresolvePrismaDatasourceUrlandresolvePrismaShadowDatabaseUrlinprisma.config.ts): Direct, unpooled connection string. WhenDATABASE_URLuses a PgBouncer pooler (isPooledPostgresUrl) andPOSTGRES_URL_NON_POOLINGis an unpooled PostgreSQL URL targeting the same database and schema,resolvePrismaDatasourceUrlinprisma.config.tspromotesPOSTGRES_URL_NON_POOLINGasdatasource.urlforprisma migrate deploy,status, andresolvewhile keepingdatasource.shadowDatabaseUrlundefinedoutsidedev,reset, anddiff(preventing PrismaP3025collisions); during localprisma migrate dev, a distinctwedding_shadowURL inPOSTGRES_URL_NON_POOLINGis bound todatasource.shadowDatabaseUrl.- Example (Direct Migration Endpoint):
postgresql://user:pass@ep-example-direct.us-east-1.aws.neon.tech/wedding?sslmode=require - Example (Dedicated Dev Shadow DB):
postgresql://user:pass@ep-example-direct.us-east-1.aws.neon.tech/wedding_shadow?sslmode=require
- Example (Direct Migration Endpoint):
SSL/TLS Configuration Behavior
- Endpoint-Aware Strict Resolution:
parsePostgresUrl(src/lib/postgres-url.js) and runtimesrc/lib/postgresPool.ts(src/lib/prisma.ts) default omittedsslmode/sslparameters toverify-fullon non-loopback TCP hosts anddisableonly on loopback addresses (localhost,*.localhost,127.0.0.0/8,::1,::ffff:127.0.0.0/8) and local Unix domain sockets (?host=/...). InNODE_ENV=production,src/env.tsblocksdisable,allow,prefer, andno-verifyon remoteDATABASE_URLandPOSTGRES_URL_NON_POOLINGendpoints (preserving explicit?sslmode=disableon internal Docker Compose@db:5432containers). - Supported TLS Modes:
sslmode=disable(orssl=false/ssl=0): Connects over plaintext TCP or Unix domain sockets without TLS negotiation (permitted in production only for loopback sockets/hosts and internal Compose@db:5432?sslmode=disable).sslmode=allow: Non-production fallback mode that attempts plaintext TCP first and upgrades to TLS if required by the server (blocked on remote hosts in production).sslmode=prefer: Non-production fallback mode that attempts TLS encryption first and falls back to plaintext if SSL is unavailable (blocked on remote hosts in production).sslmode=no-verify(orssl=no-verify): Non-production encrypted TLS mode without CA verification (blocked on remote hosts in production).sslmode=requireorssl=true(ssl=1): Enforces encrypted TLS transport with strict CA certificate chain validation (rejectUnauthorized: trueagainstsslrootcertor the system trust store) and server hostname/SAN verification. Recommended alongsideverify-fullfor managed cloud databases (Neon, Supabase, Render, Railway).sslmode=verify-ca: Enforces strict CA certificate chain verification againstsslrootcert(or the system trust store) without hostname matching.sslmode=verify-full(default for remote TCP hosts whensslmode/sslare omitted, or explicitsslmode=verify-full/sslrootcert=system): Enforces both strict CA certificate chain validation (sslrootcertor system trust store) and server hostname/SAN verification.
- Prisma CLI Normalization & Pre-Migration TLS Gate:
prisma.config.ts(rewritePostgresUrlForPrismaCli) translates omitted-sslmoderemote defaults,ssl=flags, andsslmode/sslrootcertparameters into Prisma Schema Engine equivalents (sslaccept=strict/sslaccept=accept_invalid_certs), failing closed if simultaneoussslrootcertandsslcertparameters collide, whileverifyPostgresTlsHandshake(src/lib/postgres-url.js) performs a zero-dependency Nodetlshandshake verification against the effective migration target URL (resolveDirectMigrationPostgresUrl) beforeprisma migrateruns indocker-entrypoint.sh,scripts/preflight-migration-summary.ts, anddb-migrate.yml.
Connection Pooling vs. Direct Migration Connections
- Application Runtime (
DATABASE_URL):- Can connect through transaction-level or session-level connection poolers (e.g., PgBouncer, RDS Proxy, Supabase Pooler, Neon Connection Pooler).
- Uses connection pooling managed by
pg.Poolwith@prisma/adapter-pgto minimize connection overhead during serverless / containerized scaling.
- Prisma Migrations (
npx prisma migrate deploy/dev):- Requirement: Schema migration commands require advisory locks and session-level state that transaction-mode connection poolers (like PgBouncer in transaction mode) do not support.
- When
DATABASE_URLpoints to a PgBouncer pooler (isPooledPostgresUrl) andPOSTGRES_URL_NON_POOLING(orCONTAINER_POSTGRES_URL_NON_POOLINGin Docker Compose) provides an unpooled URL targeting the same database and schema,resolvePrismaDatasourceUrlinprisma.config.tspromotesPOSTGRES_URL_NON_POOLINGasdatasource.urlwhileresolvePrismaShadowDatabaseUrlreturnsundefinedoutsidedev,reset, anddiffso Prisma 7 never triggersP3025. Operators overridingDATABASE_URLmanually on the CLI should still unsetPOSTGRES_URL_NON_POOLING(DATABASE_URL="${POSTGRES_URL_NON_POOLING:-$DATABASE_URL}" env -u POSTGRES_URL_NON_POOLING npx prisma migrate deploy).
Prisma Migration Lifecycle
- Local Development:
- Run
npm run migrate:dev(prisma migrate dev) to generate new SQL migration files inprisma/migrations/and synchronize your development schema.
- Run
- Production Pipeline:
- Migrations are automatically run in CI/CD (
db-migrate.ymlinvoked bydeploy.yml) vianpx prisma migrate deploy—or offline in containers via./node_modules/.bin/prisma migrate deploy(docker-compose.ymlmigrationservice ordocker-entrypoint.shwhenRUN_MIGRATIONS=true/RUN_MIGRATIONS=1)—before new application code goes live. prisma migrate deploychecks applied migrations in the_prisma_migrationstable and applies any pending migrations in sequential order.
- Migrations are automatically run in CI/CD (
Migration Backwards Compatibility Linter
Automated linter checks (npm run lint:migrations) run during pre-commit and pre-push hooks, local quality gates (npm run quality), PR CI workflows (ci.yml), migration executions (db-migrate.yml), releases (deploy.yml), and zero-install rollbacks (rollback.yml). The linter (scripts/verify-migration-compatibility.ts) tokenizes SQL migrations in prisma/migrations/ into semicolon-delimited statements—including multi-line statements, comma-separated ALTER TABLE clauses, PL/pgSQL DO blocks (dollar-quoted and single-quoted, including CASE headers), CREATE FUNCTION / CREATE PROCEDURE bodies, and dynamic EXECUTE statements (joining || string literals, parsing format() % placeholders, and rejecting unannotated variable EXECUTE)—and blocks destructive, locking, or N-1-incompatible SQL:
- Destructive DDL & DML:
DROP TABLE,DROP COLUMN,DROP CONSTRAINT,DROP TYPE,DROP SCHEMA,DROP VIEW,DROP MATERIALIZED VIEW,DROP TRIGGER,DROP FUNCTION,DROP PROCEDURE,DROP SEQUENCE,TRUNCATE, andDELETE FROM - Breaking Renames, Column Defaults & Type Mutations:
RENAME COLUMN,RENAME TO,RENAME VALUE,ADD COLUMNwithNOT NULLlackingDEFAULT,ADD COLUMN ... PRIMARY KEY,ADD GENERATED ALWAYS,DROP DEFAULT,SET NOT NULL, andSET DATA TYPE - Zero-Downtime Index & Constraint Locking Rules: Requires
CONCURRENTLYonCREATE INDEXandDROP INDEXfor pre-existing tables—each isolated in a dedicated single-statementmigration.sqlfile withoutBEGINso Prisma Migrate never triggers PostgreSQL error25001underlock_timeout=5000ms—and requiresNOT VALIDonCHECKandFOREIGN KEYconstraints referencing pre-existing tables (followed byVALIDATE CONSTRAINT) andUSING INDEXonUNIQUEconstraints (exempting newly created tables in the same migration file and the frozen historical baseline).
If an intentional breaking cleanup is required in a dedicated contract release after code removal, see docs/versioning.md for the statement-scoped annotation contract enforced by scripts/verify-migration-compatibility.ts.
Backup & Restore Guidelines
Before applying schema migrations to production, always perform a database snapshot or logical backup:
- Logical Dump (
pg_dump):bashpg_dump -h [host] -U [user] -d [dbname] -F c -b -v -f backup_$(date +%Y%m%d_%H%M%S).dump - Logical Restore (
pg_restore):bashpg_restore -h [host] -U [user] -d [dbname] -v -c backup_YYYYMMDD_HHMMSS.dump
Rollback Limitations & Compensating Migrations
- Forward-Only Migration Policy: Prisma Migrate does not generate automatic
downmigrations or support automated rollbacks for applied migration files. Production databases must always move forward to maintain transactional integrity and prevent catastrophic data loss. - Handling Failed Migrations:
- Do NOT manually edit or remove migration files that have already been executed in production.
- Create a compensating forward migration using
prisma migrate diffor manual SQL to reverse desired changes safely. - Mark failed migration states resolved if needed using
npx prisma migrate resolve --rolled-back [migration_name].
Zero-Downtime Schema Expansion Guidance (Expand-Migrate-Contract)
To maintain zero database downtime and preserve N-1 rollback compatibility across releases, all database mutations follow the three-phase Expand-Migrate-Contract policy enforced in CI, migration, and deployment workflows via npm run lint:migrations (ci.yml, db-migrate.yml, deploy.yml):
- Additive Releases by Default: Minor and patch deployments keep
prisma/migrations/strictly additive (new tables, nullable columns,DROP NOT NULL, orNOT NULLcolumns accompanied by an explicitDEFAULT) while dual-reading/dual-writing and backfilling data before any legacy structure is retired. - Canonical Phase & Linter Policy: See
docs/versioning.mdfor the authoritative three-phase Expand-Migrate-Contract rules, deprecation windows, and destructive SQL annotation requirements.
N-1 Application Container Compatibility Requirements
Continuous deployment and automated rollback architectures depend on N-1 compatibility:
- Backward Compatibility Guarantee: Application containers from the previous release (
N-1) must operate reliably against database schemas from the subsequent release (N). - Additive Schema Guardrail: Because previous application containers cannot anticipate new mandatory table columns, any
NOT NULLcolumn added without aDEFAULTconstraint causes existingINSERTqueries fromN-1containers to fail withNOT NULL constraint violation. - Preflight Enforcer: Both
.github/workflows/db-migrate.ymland.github/workflows/deploy.ymlenforce backwards compatibility rules as a mandatory safety gate before executing schema mutations or routing production traffic.
Automated Rollback Safety Protocols & Guarantees
When a post-deployment verification probe (/api/health or /api/ready) fails in .github/workflows/deploy-stage.yml (called by .github/workflows/deploy.yml), automated rollback procedures activate immediately:
- Fast Container Restoration: The rollback workflow (
.github/workflows/rollback.yml) restores the previous validated container image (previous_tag) in under 60 seconds without taking the database offline. - Zero Schema Reversal Needed: Because the applied database migrations comply with Expand-Migrate-Contract rules and N-1 backwards compatibility, the database schema remains fully compatible with the restored container image. No destructive database rollback or down-migration is executed.
- Pre-Rollback Database Safety Gate: Prior to container redeployment,
.github/workflows/rollback.ymlexecutesnpm run lint:migrationsto verify that all applied migrations comply with N-1 safety standards. - Diagnostic Visibility: The rollback workflow outputs comprehensive diagnostics to
$GITHUB_STEP_SUMMARY, detailing the target environment, restored tag, failure cause, database compatibility status, and follow-up remediation instructions.
Portable Provider Examples
The application works with any standard PostgreSQL server. Examples of compatible managed providers and hosting options include (labeled as examples):
- Local PostgreSQL: Docker container (
postgres:15-alpine), native installation. - Neon: Serverless PostgreSQL with pooling and direct connection strings.
- Supabase: Managed PostgreSQL with direct port 5432 and pooled port 6543 endpoints.
- Railway: Containerized PostgreSQL service.
- Amazon RDS / Aurora PostgreSQL: Enterprise managed database.
- Google Cloud SQL for PostgreSQL: Managed Cloud Run compatible database.
- Azure Database for PostgreSQL: Flexible server deployment.
⚠️ Safe Failure Semantics & Emergency Resolution Runbook
If a deployment or database migration fails during release execution, follow this operational runbook:
Pipeline Halts & Rollback Triggering:
- If migration preflight checks fail,
Release Pipelineaborts before container deployment begins. The live production container instances remain untouched on the existing healthy database. - If post-deployment container verification fails,
verify-deploymentautomatically triggersrollback.yml, restoringprevious_tagwhile keeping the compatible database schema intact.
- If migration preflight checks fail,
Diagnostic Triage:
- Review workflow logs and
$GITHUB_STEP_SUMMARYin GitHub Actions. - For migration linter failures, identify whether a migration SQL statement introduced a destructive operation (
DROP TABLE,DROP COLUMN) or an additive breaking change (ADD COLUMN ... NOT NULLwithoutDEFAULT). - For runtime probe failures, check
/api/healthand/api/readystatus, database connection pool limits, and container error logs.
- Review workflow logs and
Remediation & Resolution Commands:
- If a migration failed mid-execution and was marked failed in
_prisma_migrations, inspect the database state and resolve using Prisma CLI:bash# Mark a failed migration as rolled back in the database metadata table: npx prisma migrate resolve --rolled-back "<migration_name>" # OR mark a migration as applied if changes were manually verified: npx prisma migrate resolve --applied "<migration_name>" - If a forward schema fix is required, author a compensating migration rather than rolling back:bash
# Generate a compensating migration diff under Prisma 7 (reads DATABASE_URL via prisma.config.ts): npx prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --script > fix.sql
- If a migration failed mid-execution and was marked failed in
Re-triggering Release:
- After addressing the root cause and verifying local checks with
npm run lint:migrationsandnpm run test, trigger the release pipeline again.
- After addressing the root cause and verifying local checks with
Health Checks & Liveness Probes
- Container Liveness Probe (
GET /api/live): Targeted by theDockerfileHEALTHCHECK,docker-compose.ymlapphealthcheck, and Google Cloud Run--liveness-probe=httpGet.path=/api/live,httpGet.port=3000,periodSeconds=30(or KnativelivenessProbe). ReturnsHTTP 200 OKwith{ "status": "alive", "timestamp": "<ISO-8601>" }(Cache-Control: no-store) without querying PostgreSQL so transient database blips never trigger container restart loops. - Startup & Rollout Health Probe (
GET /api/health): Targeted by Cloud Run KnativestartupProbe(httpGet.path: /api/health,port: 3000) and paired with/api/readyin.github/workflows/deploy-stage.yml/.github/workflows/rollback.yml. Wrapped inwithApiMiddleware(isHealthProbe: trueinsrc/utils/withApiMiddleware.ts), returningHTTP 200 OK(Cache-Control: no-store) with{ "success": true, "data": { "status": "ok", "timestamp": "<ISO-8601>", "database": "connected" } }when PostgreSQL responds toSELECT 1. When PostgreSQL is unreachable (HTTP 503 Service Unavailable,Cache-Control: no-store),withApiMiddleware(isHealthProbe: true) preserves diagnostic probe fields{ "success": false, "status": "degraded", "database": "disconnected", "timestamp": "<ISO-8601>", "error": "Database connection failed" }with sanitized error text inNODE_ENV=production. - Readiness Probe (
GET /api/ready): Unwrapped Route Handler (Cache-Control: no-store) polled alongside/api/healthin.github/workflows/deploy-stage.yml,.github/workflows/rollback.yml, and./scripts/rollout-vps.sh, verifying PostgreSQL connectivity, all 16 persistedprisma/schema.prismatables (REQUIRED_SCHEMA_TABLESinsrc/lib/readinessManifest.ts), and all 47 committed migrations in_prisma_migrations(REQUIRED_MIGRATION_NAMESinsrc/lib/readinessManifest.ts, allowing extra forwardN+1migrations duringN-1rollbacks and_prisma_migrations-lessprisma db pushschemas when all 16 tables exist) without requiring seededAppConfigrows; returnsHTTP 200 OKwith{ "status": "ready", "database": "connected", "timestamp": "<ISO-8601>" }, orHTTP 503 Service Unavailablewith{ "status": "unhealthy", "database": "connected", "error": "Database schema is not ready", "timestamp": "<ISO-8601>" }on missing tables/migrations or{ "status": "unhealthy", "database": "disconnected", "error": "Database connection failed", "timestamp": "<ISO-8601>" }when PostgreSQL is unreachable. Read-only (GETandHEAD) requests to/api/live,/api/health, and/api/readyenforce syntacticHostvalidation (isHostSyntaxValid) without requiringALLOWED_HOSTSmembership. - Graceful Shutdown Timeout (
15s):docker-compose.ymlconfiguresstop_grace_period: 15sonapp(pass--stop-timeout 15on standalonedocker run) so Next.js finishes active HTTP requests beforesrc/lib/prisma.tsdrainspg.Poolwithin its5000msshutdown safety timer (exitcode130onSIGINT,143onSIGTERM).
🔑 Setup and Secrets
Configure the following workflow-consumed secrets in GitHub Settings (Settings > Environments for staging, production, and production-rollback, or Settings > Secrets and variables > Actions for repository-wide registry credentials):
| Secret | Description | Required By |
|---|---|---|
DATABASE_URL | Production/staging PostgreSQL connection string (direct or pooled when paired with POSTGRES_URL_NON_POOLING) | db-migrate.yml |
POSTGRES_URL_NON_POOLING | Optional direct (non-pooled) PostgreSQL connection string promoted by prisma.config.ts when DATABASE_URL uses PgBouncer | db-migrate.yml |
GCP_SA_KEY | Google Cloud Service Account JSON Key (legacy static fallback when Workload Identity Federation variables are not set for provider: google-cloud-run) | deploy-provider.yml, rollback.yml |
GCP_PROJECT_ID | Google Cloud Project ID (optional override when provider: google-cloud-run) | deploy-provider.yml, rollback.yml |
DEPLOY_WEBHOOK_URL | Deployment Webhook URL (required when provider: generic-webhook or docker-host) | deploy-provider.yml, rollback.yml |
DEPLOY_WEBHOOK_SECRET | HMAC-SHA256 signing secret required to authenticate generic-webhook and docker-host payloads | deploy-provider.yml, rollback.yml |
DOCKERHUB_USERNAME | Docker Hub username (optional secondary registry) | publish-artifact.yml |
DOCKERHUB_TOKEN | Docker Hub access token (optional secondary registry) | publish-artifact.yml |
Configure the following GitHub Environment and repository Variables (Settings > Environments for environment-scoped target URLs, Cloud Run topology, and Workload Identity Federation providers, and Settings > Secrets and variables > Actions > Variables for optional rollback environment bindings):
| Variable | Description | Consumed By |
|---|---|---|
SERVICE_URL | Public base URL of the target web service for /api/health and /api/ready probes (vars.SERVICE_URL primary; secrets.SERVICE_URL supported as a legacy fallback without cross-job $GITHUB_OUTPUT export) | deploy-stage.yml, deploy-provider.yml, rollback.yml |
CLOUD_RUN_SERVICE | Target Google Cloud Run service name (defaults to wedding-website-staging for staging and wedding-website for production) | deploy-provider.yml |
CLOUD_RUN_REGION | Target Google Cloud Run region (defaults to us-central1) | deploy-provider.yml |
GCP_WORKLOAD_IDENTITY_PROVIDER | Google Cloud Workload Identity Provider resource name for keyless OIDC authentication (id-token: write) | deploy-provider.yml |
GCP_SERVICE_ACCOUNT | Google Cloud Service Account email impersonated via Workload Identity Federation | deploy-provider.yml |
PRODUCTION_ROLLBACK_ENVIRONMENT | Optional unguarded GitHub Environment name (e.g., production-rollback) for automated production rollback credential resolution | deploy.yml |
STAGING_ROLLBACK_ENVIRONMENT | Optional unguarded GitHub Environment name for automated staging rollback credential resolution | deploy.yml |
Application runtime secrets (ADMIN_PASSWORD, GUEST_PASSCODE, GUEST_SESSION_SECRET, S3_*, STRIPE_*) are configured directly in the target hosting provider rather than GitHub Actions.