Skip to content

armgit / spree

Public Imported from GitHub
0

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.

Fix: spree upgrade left the dashboard packages on the old release when a backfill failed (#14843)

Damian Legawiec0289bbdd1ecc
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdx
index 20d8123a0d..db22f9459a 100644
--- a/docs/developer/cli/quickstart.mdx
+++ b/docs/developer/cli/quickstart.mdx
@@ -94,11 +94,12 @@ spree build --yes # Skip confirmation prompts (for CI)
Upgrade your project to the latest Spree release in one go. It works for both kinds of project:
-1. **Update the server**
- - On a project that runs the prebuilt image, it pulls the latest Spree image and recreates the containers. Database migrations run as the containers start.
- - On an [ejected](#spree-eject) project, it updates the Spree gems with `bundle update`, applies pending migrations, and restarts the app so it loads the new gems.
-2. **Run data backfills** — the version-specific steps from the upgrade manifest that convert existing records.
-3. **Update the `@spree/*` packages** — `@spree/cli` in the project root, and the dashboard packages and Admin SDK in `apps/dashboard` and `apps/seller-dashboard`. Each package moves to the newest release its declared range in `package.json` allows, the same way `bundle update` respects your `Gemfile`. To move to a new major version, change the range in `package.json` first.
+1. **Update the server** — on a project that runs the prebuilt image, it pulls the latest Spree image. On an [ejected](#spree-eject) project, it updates the Spree gems with `bundle update`.
+2. **Update the `@spree/*` packages** — `@spree/cli` in the project root, and the dashboard packages and Admin SDK in `apps/dashboard` and `apps/seller-dashboard`. Each package moves to the newest release its declared range in `package.json` allows, the same way `bundle update` respects your `Gemfile`. To move to a new major version, change the range in `package.json` first.
+3. **Migrate the database** — on a prebuilt-image project, it recreates the containers and the migrations run as they start. On an ejected project, it applies pending migrations.
+4. **Run data backfills** — the version-specific steps from the upgrade manifest that convert existing records. An ejected project's app is then restarted so it loads the new gems.
+
+The packages are updated before the database steps, so a failed migration or backfill no longer stops them from moving to the newest release their ranges allow. Fix the cause and run `spree upgrade` again.
```bash
spree upgrade # Run every step, asking before each one
diff --git a/docs/developer/create-spree-app/quickstart.mdx b/docs/developer/create-spree-app/quickstart.mdx
index e2d5e9af48..9aa6ac13d1 100644
--- a/docs/developer/create-spree-app/quickstart.mdx
+++ b/docs/developer/create-spree-app/quickstart.mdx
@@ -155,7 +155,7 @@ To update to the latest Spree version:
spree upgrade
```
-This updates the server (the Docker image, or the Spree gems on an ejected project), runs database migrations and data backfills, and updates the `@spree/*` packages of the project and its dashboard apps. See [`spree upgrade`](/developer/cli/quickstart#spree-upgrade) for details.
+This updates the server (the Docker image, or the Spree gems on an ejected project) and the `@spree/*` packages of the project and its dashboard apps, then runs database migrations and data backfills. See [`spree upgrade`](/developer/cli/quickstart#spree-upgrade) for details.
To pin a specific version, edit `SPREE_VERSION_TAG` in `.env`:
diff --git a/docs/developer/upgrades/quickstart.mdx b/docs/developer/upgrades/quickstart.mdx
index 15730bc69c..aa7c58779a 100644
--- a/docs/developer/upgrades/quickstart.mdx
+++ b/docs/developer/upgrades/quickstart.mdx
@@ -11,7 +11,7 @@ We strongly advise upgrading Spree incrementally, rather than in one big go.
## How to upgrade
-An upgrade updates the server, migrates the database, runs the version's data backfills, and updates the `@spree/*` packages of your dashboard apps. Always read the guide for the version you're moving to first — it lists the behavior changes to review.
+An upgrade updates the server and the `@spree/*` packages of your dashboard apps, migrates the database, and runs the version's data backfills. Always read the guide for the version you're moving to first — it lists the behavior changes to review.
<Tabs>
<Tab title="Spree CLI">
@@ -19,22 +19,22 @@ An upgrade updates the server, migrates the database, runs the version's data ba
spree upgrade
```
- One command for every project: it pulls the new image, or updates the Spree gems on an [ejected](/developer/cli/quickstart#spree-eject) project, then runs migrations, data backfills and the package updates. See [`spree upgrade`](/developer/cli/quickstart#spree-upgrade) for its options.
+ One command for every project: it pulls the new image, or updates the Spree gems on an [ejected](/developer/cli/quickstart#spree-eject) project, then updates the packages and runs migrations and data backfills. See [`spree upgrade`](/developer/cli/quickstart#spree-upgrade) for its options.
</Tab>
<Tab title="Without CLI">
Run from the project root:
```bash
- cd server
- bundle update $(bundle list --name-only | grep ^spree)
- bin/rails spree:install:migrations db:migrate
- bin/rails spree:upgrade
- cd ..
+ (cd server && bundle update $(bundle list --name-only | grep ^spree))
# The project root and each dashboard app have their own package.json
pnpm update "@spree/*"
(cd apps/dashboard && pnpm update "@spree/*")
(cd apps/seller-dashboard && pnpm update "@spree/*")
+
+ cd server
+ bin/rails spree:install:migrations db:migrate
+ bin/rails spree:upgrade
```
On npm or Yarn, run `npm update` or `yarn upgrade` instead, naming each `@spree/*` package from that `package.json` (they do not accept the `"@spree/*"` pattern).
diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md
index 97638bfbc5..967f05f4ee 100644
--- a/packages/cli/CHANGELOG.md
+++ b/packages/cli/CHANGELOG.md
@@ -1,5 +1,11 @@
# @spree/cli
+## 3.2.1
+
+### Patch Changes
+
+- [#14843](https://github.com/spree/spree/pull/14843) [`6ff684e`](https://github.com/spree/spree/commit/6ff684e20192d4a29b08cb63f356248705d162ec) Thanks [@damianlegawiec](https://github.com/damianlegawiec)! - `spree upgrade` now updates the `@spree/*` packages right after the server (gems or image) and before migrations and data backfills, so a failing migration or backfill no longer prevents the `@spree/*` packages from updating.
+
## 3.2.0
### Minor Changes
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 1e0bb4cef8..970352402a 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -17,7 +17,7 @@ Run from your Spree project directory:
|---------|-------------|
| `spree dev` | Run the app in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically; co-runs the Admin Dashboard dev server when `apps/dashboard` exists |
| `spree stop` | Stop backend services |
-| `spree upgrade` | Upgrade Spree — the server (image or gems), migrations, data backfills and `@spree/*` packages |
+| `spree upgrade` | Upgrade Spree — the server (image or gems), `@spree/*` packages, migrations and data backfills |
| `spree eject` | Switch from the prebuilt image to building from `backend/` |
| `spree add dashboard` | Add the Admin Dashboard to an existing project, to customize it |
| `spree add seller-dashboard` | Add the marketplace seller panel to an existing project |
diff --git a/packages/cli/package.json b/packages/cli/package.json
index f246341692..8687282687 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/cli",
- "version": "3.2.0",
+ "version": "3.2.1",
"description": "CLI for managing Spree Commerce projects",
"type": "module",
"bin": {
diff --git a/packages/cli/src/commands/upgrade.ts b/packages/cli/src/commands/upgrade.ts
index d7724daeb7..389cdd9734 100644
--- a/packages/cli/src/commands/upgrade.ts
+++ b/packages/cli/src/commands/upgrade.ts
@@ -24,17 +24,19 @@ interface UpgradeFlags {
// One command for both project shapes. The server half depends on where the
// Rails app comes from: a prebuilt-image project pulls the new image (its
-// entrypoint migrates on boot), an ejected project bumps the Spree gems and
-// migrates itself. Both then run the spree:upgrade rake backfills and bump the
-// @spree/* packages of the root and the admin apps. Flags map to env vars on
-// the rake task: --plan → DRY_RUN, --step → STEP, --to → TO. --plan and --step
-// run the rake task alone.
+// entrypoint migrates when the containers are recreated), an ejected project
+// bumps the Spree gems and migrates itself. The @spree/* packages of the root
+// and the admin apps are bumped right after the server, before migrations and
+// the spree:upgrade rake backfills, so a failing backfill can't leave the
+// dashboards on the old release. Flags map to env vars on the rake task:
+// --plan → DRY_RUN, --step → STEP, --to → TO. --plan and --step run the rake
+// task alone.
export function registerUpgradeCommand(program: Command): void {
withUpgradeOptions(
program
.command('upgrade')
.description(
- 'Upgrade Spree: the server (image or gems), migrations, data backfills and @spree/* packages',
+ 'Upgrade Spree: the server (image or gems), @spree/* packages, migrations and data backfills',
),
).action(upgrade)
@@ -76,16 +78,17 @@ async function upgrade(flags: UpgradeFlags): Promise<void> {
if (isEjectedProject(ctx.projectDir)) {
const gemsUpdated = await runBundleUpdate(ctx.projectDir, flags)
+ await updateSpreePackages(ctx.projectDir, flags)
await runMigrate(ctx.projectDir, flags)
await runRakeUpgrade(ctx.projectDir, flags)
if (gemsUpdated) await restartAppServices(ctx.projectDir)
} else {
- await pullImage(ctx.projectDir, flags)
+ const imagePulled = await pullImage(ctx.projectDir, flags)
+ await updateSpreePackages(ctx.projectDir, flags)
+ if (imagePulled) await recreateContainers(ctx.projectDir)
await runRakeUpgrade(ctx.projectDir, flags)
}
- await updateSpreePackages(ctx.projectDir, flags)
-
printPostUpgradeReminder(ctx.projectDir)
}
@@ -99,18 +102,21 @@ async function confirmStep(message: string, flags: UpgradeFlags): Promise<boolea
return confirmed
}
-// The image's entrypoint runs db:prepare before Puma starts, and web's
-// healthcheck only passes once Puma answers — so `--wait` returns with the
-// migrations applied and the container ready for the rake step.
-async function pullImage(projectDir: string, flags: UpgradeFlags): Promise<void> {
+async function pullImage(projectDir: string, flags: UpgradeFlags): Promise<boolean> {
if (!(await confirmStep('Pull the latest Spree image and recreate the containers?', flags))) {
p.log.info('Skipping the image pull.')
- return
+ return false
}
p.log.step(pc.bold('docker compose pull'))
await dockerCompose(['pull'], projectDir, { stdio: 'inherit' })
+ return true
+}
+// The image's entrypoint runs db:prepare before Puma starts, and web's
+// healthcheck only passes once Puma answers — so `--wait` returns with the
+// migrations applied and the container ready for the rake step.
+async function recreateContainers(projectDir: string): Promise<void> {
p.log.step(pc.bold('Recreating containers and running migrations'))
// Prime the shared bundle_cache volume with web alone first so the up
// below doesn't race the copy-up if this follows a `down -v` (cold volume).
diff --git a/packages/cli/tests/upgrade.test.ts b/packages/cli/tests/upgrade.test.ts
index e7efa647a8..7cc4005dc4 100644
--- a/packages/cli/tests/upgrade.test.ts
+++ b/packages/cli/tests/upgrade.test.ts
@@ -1,15 +1,38 @@
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { Command } from 'commander'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('execa', () => ({ execa: vi.fn() }))
+let projectDir: string
+
+vi.mock('../src/context', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../src/context')>()),
+ detectProject: () => ({ mode: 'docker', projectDir, port: 3000 }),
+}))
+
+vi.mock('../src/commands/add', () => ({
+ APP_DIRS: ['dashboard'],
+ detectPackageManager: () => 'pnpm',
+ generateRouteTree: vi.fn(),
+}))
+
+vi.mock('@clack/prompts', () => ({
+ log: { step: vi.fn(), info: vi.fn(), warn: vi.fn() },
+ note: vi.fn(),
+ confirm: vi.fn(),
+ isCancel: () => false,
+ cancel: vi.fn(),
+}))
+
import { execa } from 'execa'
import {
detectSpreeGems,
detectSpreePackages,
packageUpdateArgs,
+ registerUpgradeCommand,
sdkAdvisory,
} from '../src/commands/upgrade'
@@ -196,3 +219,110 @@ describe('packageUpdateArgs', () => {
}
})
})
+
+describe('spree upgrade', () => {
+ const mockExeca = vi.mocked(execa)
+ let commands: string[]
+
+ // Every docker and package-manager call goes through execa; record them in
+ // order, leaving out the read-only probes (`compose ps`, `bundle list`, …).
+ function routeExeca({ failOn }: { failOn?: string } = {}): void {
+ mockExeca.mockImplementation((async (cmd: string, args: string[]) => {
+ if (args.includes('ps')) return { stdout: 'running' }
+ if (args.includes('list')) return { stdout: 'spree\nspree_core\n' }
+ if (args.includes('config')) return { stdout: 'web\n' }
+ const command = `${cmd} ${args.join(' ')}`
+ commands.push(command)
+ if (failOn && command.includes(failOn)) throw new Error(`${failOn} failed`)
+ return { stdout: '' }
+ }) as never)
+ }
+
+ function writeProject({ ejected }: { ejected: boolean }): void {
+ projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'spree-cli-upgrade-run-test-'))
+ fs.writeFileSync(
+ path.join(projectDir, 'docker-compose.yml'),
+ ejected
+ ? 'services:\n web:\n build: ./server\n'
+ : 'services:\n web:\n image: spree\n',
+ )
+ fs.writeFileSync(
+ path.join(projectDir, 'package.json'),
+ JSON.stringify({ devDependencies: { '@spree/cli': '^3.2.0' } }),
+ )
+ const dashboardDir = path.join(projectDir, 'apps', 'dashboard')
+ fs.mkdirSync(dashboardDir, { recursive: true })
+ fs.writeFileSync(
+ path.join(dashboardDir, 'package.json'),
+ JSON.stringify({ dependencies: { '@spree/dashboard': '^1.0.0' } }),
+ )
+ }
+
+ async function runUpgrade(argv: string[] = []): Promise<void> {
+ const program = new Command()
+ registerUpgradeCommand(program)
+ await program.parseAsync(['upgrade', '--yes', ...argv], { from: 'user' })
+ }
+
+ beforeEach(() => {
+ commands = []
+ routeExeca()
+ })
+
+ afterEach(() => {
+ mockExeca.mockReset()
+ fs.rmSync(projectDir, { recursive: true, force: true })
+ })
+
+ it('bumps the packages after the gems and before migrations and backfills on an ejected project', async () => {
+ writeProject({ ejected: true })
+
+ await runUpgrade()
+
+ expect(commands).toEqual([
+ 'docker compose exec web bundle update spree spree_core',
+ 'pnpm update @spree/cli',
+ 'pnpm update @spree/dashboard',
+ 'docker compose exec web bin/rails spree:install:migrations db:migrate',
+ 'docker compose exec web bin/rake spree:upgrade',
+ 'docker compose restart web',
+ ])
+ })
+
+ it('bumps the packages after the image pull and before the migrating recreate on an image-based project', async () => {
+ writeProject({ ejected: false })
+
+ await runUpgrade()
+
+ expect(commands).toEqual([
+ 'docker compose pull',
+ 'pnpm update @spree/cli',
+ 'pnpm update @spree/dashboard',
+ 'docker compose up -d --no-deps web',
+ 'docker compose up -d --wait',
+ 'docker compose exec web bin/rake spree:upgrade',
+ ])
+ })
+
+ it('has already bumped the packages when a backfill fails', async () => {
+ writeProject({ ejected: true })
+ routeExeca({ failOn: 'spree:upgrade' })
+
+ await expect(runUpgrade()).rejects.toThrow(/spree:upgrade failed/)
+
+ expect(commands).toContain('pnpm update @spree/dashboard')
+ expect(commands.at(-1)).toBe('docker compose exec web bin/rake spree:upgrade')
+ })
+
+ it('runs only the rake task with --plan or --step', async () => {
+ writeProject({ ejected: true })
+
+ await runUpgrade(['--plan'])
+ await runUpgrade(['--step', 'channels'])
+
+ expect(commands).toEqual([
+ 'docker compose exec -e DRY_RUN=1 web bin/rake spree:upgrade',
+ 'docker compose exec -e STEP=channels web bin/rake spree:upgrade',
+ ])
+ })
+})