Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: spree eject preparing the database after the app server starts (#14758)
Damian Legawiecd1b27e2c9dfd
diff --git a/.changeset/eject-prepares-database-first.md b/.changeset/eject-prepares-database-first.mdnew file mode 100644index 0000000000..b6c88d2801--- /dev/null+++ b/.changeset/eject-prepares-database-first.md@@ -0,0 +1,5 @@+---+"@spree/cli": patch+---++Fixed `spree eject` failing on a fresh stack with `service "web" is not running`. The development database is now created before the app server starts, since the server exits when that database is missing; `spree init` on an ejected project does the same. Eject also switches older dev compose files to a Postgres health check that only passes once the database server is really up.diff --git a/docs/developer/deployment/docker.mdx b/docs/developer/deployment/docker.mdxindex f71d269793..fdc7b67ff1 100644--- a/docs/developer/deployment/docker.mdx+++ b/docs/developer/deployment/docker.mdx@@ -41,7 +41,7 @@ services:volumes:- postgres_data:/var/lib/postgresql/datahealthcheck:- test: pg_isready -U postgres+ test: pg_isready -h 127.0.0.1 -U postgresinterval: 5stimeout: 5sretries: 5diff --git a/packages/cli/src/commands/eject.ts b/packages/cli/src/commands/eject.tsindex cf68f9c768..0b303274ee 100644--- a/packages/cli/src/commands/eject.ts+++ b/packages/cli/src/commands/eject.ts@@ -4,7 +4,7 @@ import * as p from '@clack/prompts'import type { Command } from 'commander'import pc from 'picocolors'import { detectProject, findApiDir } from '../context.js'-import { dockerCompose, dockerComposeExec, primeBundleVolume } from '../docker.js'+import { dockerCompose, prepareDatabase } from '../docker.js'// Switch the project from the prebuilt-image compose to the bind-mounted// dev compose. Source under the API directory becomes live in the container —@@ -33,9 +33,7 @@ export function registerEjectCommand(program: Command) {process.exit(1)}- // Replace docker-compose.yml with the dev version. The dev compose has- // `build:` defined, so `up -d` below will build on first invocation —- // no separate explicit build step needed.+ // Replace docker-compose.yml with the dev version.//// Projects scaffolded before create-spree-app 1.0.3 shipped a dev// compose that bind-mounts the project root (`.:/rails`) instead of@@ -45,19 +43,29 @@ export function registerEjectCommand(program: Command) {composeContent = composeContent.replace('- .:/rails', `- ./${apiDir}:/rails`)fs.writeFileSync(devCompose, composeContent)}+ // Older dev composes check postgres over the unix socket, which the+ // image's temporary init server also answers on a brand-new volume —+ // so dependants started against a server that was about to restart.+ // Only the real server listens on TCP.+ if (composeContent.includes('test: pg_isready -U postgres')) {+ composeContent = composeContent.replace(+ 'test: pg_isready -U postgres',+ 'test: pg_isready -h 127.0.0.1 -U postgres',+ )+ fs.writeFileSync(devCompose, composeContent)+ }fs.writeFileSync(path.join(ctx.projectDir, 'docker-compose.yml'), composeContent)console.log(`\n${pc.bold(`Switching to dev compose (bind-mounts ./${apiDir})...`)}\n`)- // Prime the shared bundle_cache volume with web alone so the parallel up- // below doesn't race the cold-volume copy-up (web + worker → "file exists").- await primeBundleVolume(ctx.projectDir)- await dockerCompose(['up', '-d'], ctx.projectDir, { stdio: 'inherit' })- // The dev image bypasses bin/docker-entrypoint (which runs db:prepare- // in the prebuilt image), and the dev environment uses its own- // spree_development database — make sure it exists and is migrated.- console.log(`\n${pc.bold('Preparing the development database...')}\n`)- await dockerComposeExec(['bin/rails', 'db:prepare'], ctx.projectDir, { tty: false })+ // The dev environment uses its own spree_development database, and the+ // app server exits when it is missing — create and migrate it first.+ // The dev compose has `build:` defined, so this first `run` also builds+ // the image — no separate explicit build step needed.+ console.log(`${pc.bold('Preparing the development database...')}\n`)+ await prepareDatabase(ctx.projectDir, { stdio: 'inherit' })++ await dockerCompose(['up', '-d'], ctx.projectDir, { stdio: 'inherit' })p.note([diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex f191434f40..9ba095d5db 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -7,14 +7,20 @@ import { execa, execaCommand } from 'execa'import pc from 'picocolors'import { mintProjectCredentials, writeAdminEmail, writeProjectSetupMarker } from '../config.js'import { DASHBOARD_PORT, STOREFRONT_PORT } from '../constants.js'-import { detectProject, readSampleDataFromEnv } from '../context.js'+import { detectProject, isEjectedProject, readSampleDataFromEnv } from '../context.js'import {dashboardDevRunnable,hasDashboardApp,startDashboardDevServer,warnDashboardNotRunnable,} from '../dashboard-server.js'-import { dockerCompose, primeBundleVolume, rakeTask, streamLogs } from '../docker.js'+import {+ dockerCompose,+ prepareDatabase,+ primeBundleVolume,+ rakeTask,+ streamLogs,+} from '../docker.js'import { detectPackageManager, ensureDashboardDevEnv } from './add.js'const HEALTH_CHECK_INTERVAL_MS = 3000@@ -74,6 +80,15 @@ export async function runFirstRunSetup(flags: {await dockerCompose(['pull'], ctx.projectDir, { stdio: 'inherit' })const s = p.spinner()+ // The prebuilt image prepares its database in its entrypoint; the dev+ // compose of an ejected project does not, and its app server exits+ // without one.+ if (isEjectedProject(ctx.projectDir)) {+ s.start('Preparing the development database...')+ await prepareDatabase(ctx.projectDir)+ s.stop('Development database ready.')+ }+s.start('Starting Docker services...')// Prime the shared bundle_cache volume with web alone so the up below// doesn't race the cold-volume copy-up. stdio: 'ignore' keeps the spinnerdiff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.tsindex 1385d7e261..d0a2261463 100644--- a/packages/cli/src/docker.ts+++ b/packages/cli/src/docker.ts@@ -182,6 +182,32 @@ export async function dockerComposeRun(await execa('docker', args, { cwd: projectDir, ...stdio })}+// The dev compose (an ejected project) starts `bin/rails server` directly,+// bypassing bin/docker-entrypoint and its db:prepare. Puma runs the Solid Queue+// supervisor in-process, and when the database does not exist yet the+// supervisor fails and takes Puma down with it — so on a fresh stack the web+// container exits before anything can `exec` into it. Prepare the database in+// a one-off container instead (no Puma) before the app server is brought up.+// Postgres is started and health-waited explicitly first: older dev compose+// files give web no depends_on, so `run` alone would not wait for it. Being the only container that mounts a+// cold bundle_cache volume, it also wins the copy-up uncontended, so no+// separate primeBundleVolume is needed after it. `--build` makes it use the+// current Dockerfile rather than a dev image left over from an earlier eject,+// and the `up -d` that follows reuses that image.+//+// stdio defaults to piped so a spinner caller stays clean and a failure still+// carries compose's output on the thrown error.+export async function prepareDatabase(+ projectDir: string,+ options?: { stdio?: ExecaOptions['stdio'] },+): Promise<void> {+ const stdio = options?.stdio ?? 'pipe'+ await dockerCompose(['up', '-d', '--wait', 'postgres'], projectDir, { stdio })+ await dockerCompose(['run', '--rm', '--build', 'web', 'bin/rails', 'db:prepare'], projectDir, {+ stdio,+ })+}+export interface DockerComposeExecOrRunOptions {service?: stringenv?: Record<string, string>diff --git a/packages/cli/tests/docker.test.ts b/packages/cli/tests/docker.test.tsindex 2ab98a3b83..cf9ced26f5 100644--- a/packages/cli/tests/docker.test.ts+++ b/packages/cli/tests/docker.test.ts@@ -19,6 +19,7 @@ import {dockerComposeCapture,dockerComposeExecOrRun,dockerComposeRun,+ prepareDatabase,rakeTask,} from '../src/docker'@@ -110,6 +111,31 @@ describe('dockerComposeRun', () => {})})+describe('prepareDatabase', () => {+ afterEach(() => mockExeca.mockReset())++ it('waits for a healthy postgres, then runs db:prepare in a one-off web container', async () => {+ await prepareDatabase('/proj')++ expect(mockExeca).toHaveBeenCalledTimes(2)+ expect(mockExeca).toHaveBeenNthCalledWith(+ 1,+ 'docker',+ ['compose', 'up', '-d', '--wait', 'postgres'],+ {+ cwd: '/proj',+ stdio: 'pipe',+ },+ )+ expect(mockExeca).toHaveBeenNthCalledWith(+ 2,+ 'docker',+ ['compose', 'run', '--rm', '--build', 'web', 'bin/rails', 'db:prepare'],+ { cwd: '/proj', stdio: 'pipe' },+ )+ })+})+describe('dockerComposeExecOrRun', () => {class ExitError extends Error {constructor(public code: number) {diff --git a/packages/cli/tests/eject.test.ts b/packages/cli/tests/eject.test.tsindex 4582a11141..07b42d87c1 100644--- a/packages/cli/tests/eject.test.ts+++ b/packages/cli/tests/eject.test.ts@@ -4,7 +4,7 @@ import path from 'node:path'import { Command } from 'commander'import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest'import { registerEjectCommand } from '../src/commands/eject'-import { dockerCompose, dockerComposeExec, primeBundleVolume } from '../src/docker'+import { dockerCompose, prepareDatabase } from '../src/docker'const COMPOSE_DEV_STALE = `x-app: &appbuild:@@ -18,11 +18,18 @@ services:web:<<: *appcommand: ["bin/rails", "server", "-b", "0.0.0.0", "-p", "3000"]+ postgres:+ image: postgres:18-alpine+ healthcheck:+ test: pg_isready -U postgresvolumes:bundle_cache:`-const COMPOSE_DEV_FIXED = COMPOSE_DEV_STALE.replace('- .:/rails', '- ./backend:/rails')+const COMPOSE_DEV_FIXED = COMPOSE_DEV_STALE.replace('- .:/rails', '- ./backend:/rails').replace(+ 'pg_isready -U postgres',+ 'pg_isready -h 127.0.0.1 -U postgres',+)let projectDir: string@@ -34,8 +41,7 @@ vi.mock('../src/context', () => ({vi.mock('../src/docker', () => ({dockerCompose: vi.fn().mockResolvedValue(undefined),- dockerComposeExec: vi.fn().mockResolvedValue(undefined),- primeBundleVolume: vi.fn().mockResolvedValue(undefined),+ prepareDatabase: vi.fn().mockResolvedValue(undefined),}))function makeProject(devComposeContent: string, apiDir = 'server'): string {@@ -100,30 +106,28 @@ describe('spree eject', () => {expect(dev).toBe(COMPOSE_DEV_FIXED)})- it('brings the stack up and prepares the development database', async () => {+ it('switches the postgres healthcheck to TCP in both compose files', async () => {projectDir = makeProject(COMPOSE_DEV_STALE)await runEject()- expect(dockerCompose).toHaveBeenCalledWith(['up', '-d'], projectDir, { stdio: 'inherit' })- expect(dockerComposeExec).toHaveBeenCalledWith(['bin/rails', 'db:prepare'], projectDir, {- tty: false,- })+ for (const file of ['docker-compose.yml', 'docker-compose.dev.yml']) {+ const content = fs.readFileSync(path.join(projectDir, file), 'utf-8')+ expect(content).toContain('test: pg_isready -h 127.0.0.1 -U postgres')+ }})- it('primes the bundle volume with web before the parallel up', async () => {+ it('prepares the development database before starting the app server', async () => {projectDir = makeProject(COMPOSE_DEV_STALE)await runEject()- expect(primeBundleVolume).toHaveBeenCalledWith(projectDir)- // The primer must run before the parallel `up -d` so web wins the- // cold-volume copy-up uncontended (no web/worker "file exists" race).- const primeOrder = (primeBundleVolume as Mock).mock.invocationCallOrder[0]- const upCall = (dockerCompose as Mock).mock.calls.findIndex(- ([args]) => Array.isArray(args) && args.join(' ') === 'up -d',+ expect(prepareDatabase).toHaveBeenCalledWith(projectDir, { stdio: 'inherit' })+ expect(dockerCompose).toHaveBeenCalledWith(['up', '-d'], projectDir, { stdio: 'inherit' })+ // Puma exits when spree_development is missing, so the database must+ // exist before `up -d` starts it.+ expect((prepareDatabase as Mock).mock.invocationCallOrder[0]).toBeLessThan(+ (dockerCompose as Mock).mock.invocationCallOrder[0],)- expect(upCall).toBeGreaterThanOrEqual(0)- expect(primeOrder).toBeLessThan((dockerCompose as Mock).mock.invocationCallOrder[upCall])})})