Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/upgrade-target-per-node.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@shopify/cli-kit': patch
'@shopify/cli': patch
---

Auto-upgrade, `shopify upgrade` and the upgrade notice no longer pick a release your Node doesn't support from a stale update check or one cached by an older CLI or another Node version
30 changes: 28 additions & 2 deletions packages/cli-kit/src/private/node/cli-version-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,15 @@ export function getCLIVersionCacheKey(registry: string, versionRange?: string):
return `npm-package-@shopify/cli${versionRange ? `@${versionRange}` : ''}:registry:${hashString(registry)}`
}

/**
* The cache key for the upgrade target in `versionRange`: the newest release there whose `engines` admit the running
* Node. It names the running Node, because a target picked under one Node can exclude another, and older CLIs cache a
* target picked without that check under the same key without it.
*/
export function getCLIUpgradeTargetCacheKey(registry: string, versionRange: string): PackageVersionKey {
return `${getCLIVersionCacheKey(registry, versionRange)}:node:${process.version}`
}

export function getCLINodeRangeCacheKey(registry: string): PackageVersionKey {
return `${getCLIVersionCacheKey(registry)}:node`
}
Expand All @@ -37,9 +46,13 @@ export function getPublicCLIVersionCacheKey(registry: string, versionRange?: str
return versionRange ? `${latestCacheKey}:range:${versionRange}` : latestCacheKey
}

/**
* A fresh cached version: the latest release, or, with a range, the upgrade target in it for the running Node.
*/
export function getCachedCLIVersion(versionRange?: string, registry = currentRegistry): string | undefined {
if (!registry) return undefined
const cached = cacheRetrieve(getCLIVersionCacheKey(registry, versionRange))
const cacheKey = versionRange ? getCLIUpgradeTargetCacheKey(registry, versionRange) : getCLIVersionCacheKey(registry)
const cached = cacheRetrieve(cacheKey)
if (
cached &&
valid(cached.value) &&
Expand Down Expand Up @@ -68,12 +81,25 @@ export function cliNodeRangeCacheValue(version: string, nodeRange: string | unde
* Undefined when the release declares none, or when nothing fresh is cached for it.
*/
export function getCachedCLINodeRange(version: string, registry = currentRegistry): string | undefined {
const nodeRange = cachedCLINodeRangeEntry(version, registry)
return nodeRange === '' ? undefined : nodeRange
}

/**
* Whether the version lookup cached a fresh entry for the Node range of `version`, including one saying it declares
* none. Other lookups, such as older CLIs', cache a latest version without it.
*/
export function hasCachedCLINodeRange(version: string, registry = currentRegistry): boolean {
return cachedCLINodeRangeEntry(version, registry) !== undefined
}

function cachedCLINodeRangeEntry(version: string, registry: string | undefined): string | undefined {
if (!registry) return undefined
const cached = cacheRetrieve(getCLINodeRangeCacheKey(registry))
if (!cached || Date.now() - cached.timestamp >= cacheExpiryMs) return undefined
const separator = cached.value.indexOf(' ')
if (separator === -1 || cached.value.slice(0, separator) !== version) return undefined
return cached.value.slice(separator + 1) || undefined
return cached.value.slice(separator + 1)
}

/**
Expand Down
213 changes: 201 additions & 12 deletions packages/cli-kit/src/private/node/cli-version-check.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import * as cliVersionCheck from './cli-version-check.js'
import {checkForCLIVersions, getCachedCurrentMajorCLIVersion} from './cli-version-check.js'
import {getCLIVersionCacheKey, resolveCLIRegistry} from './cli-version-cache.js'
import {
cliNodeRangeCacheValue,
getCLINodeRangeCacheKey,
getCLIUpgradeTargetCacheKey,
getCLIVersionCacheKey,
resolveCLIRegistry,
} from './cli-version-cache.js'
import * as confStore from './conf-store.js'
import {CLI_KIT_VERSION} from '../../public/common/version.js'
import {inTemporaryDirectory} from '../../public/node/fs.js'
Expand Down Expand Up @@ -41,7 +47,8 @@ const metadata = {
),
}
const latestCacheKey = getCLIVersionCacheKey('https://registry.npmjs.org/')
const currentMajorCacheKey = getCLIVersionCacheKey('https://registry.npmjs.org/', currentMajorRange)
const currentMajorCacheKey = getCLIUpgradeTargetCacheKey('https://registry.npmjs.org/', currentMajorRange)
const nodeRangeCacheKey = getCLINodeRangeCacheKey('https://registry.npmjs.org/')

beforeEach(() => {
vi.stubEnv('SHOPIFY_CLI_FORCE_AUTO_UPGRADE', undefined)
Expand Down Expand Up @@ -251,6 +258,69 @@ test('keeps a release that declares no engines eligible', async () => {
)
})

test('ignores the current-major target that a CLI without the Node check cached', async () => {
const unsupportedVersion = new SemVer(CLI_KIT_VERSION).inc('minor').version
let requests = 0
await withRegistry(
http.get('https://registry.npmjs.org/*', () => {
requests += 1
return HttpResponse.json({
'dist-tags': {latest: unsupportedVersion},
versions: {
[currentMajorVersion]: {version: currentMajorVersion, engines: {node: `>=${process.versions.node}`}},
[unsupportedVersion]: {version: unsupportedVersion, engines: {node: `>${process.versions.node}`}},
},
})
}),
async () => {
// An older CLI on the same machine, such as one that a project pins, caches its unchecked pick here.
confStore.cacheStore(latestCacheKey, unsupportedVersion)
confStore.cacheStore(getCLIVersionCacheKey('https://registry.npmjs.org/', currentMajorRange), unsupportedVersion)
expect(getCachedCurrentMajorCLIVersion()).toBeUndefined()
expect(versionToAutoUpgrade()).toBeUndefined()

await checkForNewVersionInBackground()
await checkForCLIVersions()
expect(requests).toBe(1)
expect(versionToAutoUpgrade()).toBe(currentMajorVersion)
},
)
})

test('picks the current-major target again after a switch to a Node version that the cached one excludes', async () => {
const newerVersion = new SemVer(CLI_KIT_VERSION).inc('minor').version
const runningNode = Object.getOwnPropertyDescriptor(process, 'version')!
const useNode = (version: string) => Object.defineProperty(process, 'version', {...runningNode, value: version})
let requests = 0
await withRegistry(
http.get('https://registry.npmjs.org/*', () => {
requests += 1
return HttpResponse.json({
'dist-tags': {latest: newerVersion},
versions: {
[currentMajorVersion]: {version: currentMajorVersion},
[newerVersion]: {version: newerVersion, engines: {node: '>=24.5.0'}},
},
})
}),
async () => {
try {
useNode('v24.5.0')
await checkForCLIVersions()
expect(versionToAutoUpgrade()).toBe(newerVersion)

useNode('v24.4.0')
expect(versionToAutoUpgrade()).toBeUndefined()
await checkForCLIVersions()
expect(versionToAutoUpgrade()).toBe(currentMajorVersion)
expect(requests).toBe(2)
} finally {
Object.defineProperty(process, 'version', runningNode)
}
},
)
})

test('caches the Node range that the latest release needs with the versions', async () => {
const latest = new SemVer(CLI_KIT_VERSION).inc('minor').version
let requests = 0
Expand All @@ -271,22 +341,119 @@ test('caches the Node range that the latest release needs with the versions', as
)
})

test('ignores a cached Node range once another lookup refreshes latest to a different release', async () => {
test('looks the versions up again once another lookup caches a new latest release without its Node range', async () => {
const latest = new SemVer(CLI_KIT_VERSION).inc('minor').version
const refreshedLatest = new SemVer(latest).inc('patch').version
let publishedLatest = latest
let requests = 0
await withRegistry(
http.get('https://registry.npmjs.org/*', () =>
HttpResponse.json({
'dist-tags': {latest},
versions: {[latest]: {version: latest, engines: {node: '>=22.20.0'}}},
}),
),
http.get('https://registry.npmjs.org/*', () => {
requests += 1
return HttpResponse.json({
'dist-tags': {latest: publishedLatest},
versions: {
[latest]: {version: latest, engines: {node: '>=0.10.0'}},
[refreshedLatest]: {version: refreshedLatest, engines: {node: '>=0.12.0'}},
},
})
}),
async () => {
await checkForCLIVersions()
// The generic latest-version lookup refreshes the same entry and caches no Node range.
// An older CLI, or the generic latest-version lookup, refreshes the same entry and caches no Node range.
publishedLatest = refreshedLatest
confStore.cacheStore(latestCacheKey, refreshedLatest)

await expect(checkForCLIVersions()).resolves.toEqual({latest: refreshedLatest, currentMajor: latest})
await expect(checkForCLIVersions()).resolves.toEqual({
latest: refreshedLatest,
currentMajor: refreshedLatest,
latestNodeRange: '>=0.12.0',
})
expect(requests).toBe(2)
},
)
})

test('a refresh looks the versions up again despite a fresh cache or a recent failure', async () => {
const floorRaise = new SemVer(CLI_KIT_VERSION).inc('minor').version
const refreshed = {
latest: floorRaise,
currentMajor: currentMajorVersion,
latestNodeRange: `>${process.versions.node}`,
}
let publishedLatest = currentMajorVersion
let registryFails = false
let requests = 0
await withRegistry(
http.get('https://registry.npmjs.org/*', () => {
requests += 1
if (registryFails) return new HttpResponse(null, {status: 503})
return HttpResponse.json({
'dist-tags': {latest: publishedLatest},
versions: {
[currentMajorVersion]: {version: currentMajorVersion},
[floorRaise]: {version: floorRaise, engines: {node: `>${process.versions.node}`}},
},
})
}),
async () => {
await checkForCLIVersions()
// A release that raises the Node floor ships after the cached lookup.
publishedLatest = floorRaise
await expect(checkForCLIVersions()).resolves.toEqual({
latest: currentMajorVersion,
currentMajor: currentMajorVersion,
})
expect(requests).toBe(1)

await expect(checkForCLIVersions({refresh: true})).resolves.toEqual(refreshed)
expect(requests).toBe(2)

registryFails = true
await expect(checkForCLIVersions({refresh: true})).resolves.toEqual({})
// A failed refresh leaves the cached lookup for a manual upgrade to fall back on.
await expect(checkForCLIVersions()).resolves.toEqual(refreshed)
expect(requests).toBe(3)
registryFails = false
await expect(checkForCLIVersions({refresh: true})).resolves.toEqual(refreshed)
expect(requests).toBe(4)
},
)
})

test('after a Node switch and a failed refresh, the cached latest release and its Node range stay readable', async () => {
const floorRaise = new SemVer(CLI_KIT_VERSION).inc('minor').version
const runningNode = Object.getOwnPropertyDescriptor(process, 'version')!
const useNode = (version: string) => Object.defineProperty(process, 'version', {...runningNode, value: version})
let registryFails = false
await withRegistry(
http.get('https://registry.npmjs.org/*', () => {
if (registryFails) return new HttpResponse(null, {status: 503})
return HttpResponse.json({
'dist-tags': {latest: floorRaise},
versions: {
[currentMajorVersion]: {version: currentMajorVersion},
[floorRaise]: {version: floorRaise, engines: {node: '>=24.5.0'}},
},
})
}),
async () => {
try {
useNode('v24.5.0')
await checkForCLIVersions()
// The same user switches to an older Node, where only an older CLI's unchecked pick is cached as a target.
useNode('v24.4.0')
confStore.cacheStore(getCLIVersionCacheKey('https://registry.npmjs.org/', currentMajorRange), floorRaise)
registryFails = true
await expect(checkForCLIVersions({refresh: true})).resolves.toEqual({})

await expect(checkForCLIVersions()).resolves.toEqual({})
await expect(checkForCLIVersions({includeCurrentMajor: false})).resolves.toEqual({
latest: floorRaise,
latestNodeRange: '>=24.5.0',
})
} finally {
Object.defineProperty(process, 'version', runningNode)
}
},
)
})
Expand Down Expand Up @@ -433,7 +600,11 @@ test.each([true, false])(
try {
await withCache(async (storage) => {
confStore.cacheStore(getCLIVersionCacheKey(secondRegistry), CLI_KIT_VERSION)
confStore.cacheStore(getCLIVersionCacheKey(secondRegistry, currentMajorRange), CLI_KIT_VERSION)
confStore.cacheStore(
getCLINodeRangeCacheKey(secondRegistry),
cliNodeRangeCacheValue(CLI_KIT_VERSION, undefined),
)
confStore.cacheStore(getCLIUpgradeTargetCacheKey(secondRegistry, currentMajorRange), CLI_KIT_VERSION)
vi.mocked(registryUrl).mockReturnValueOnce('https://registry.npmjs.org/').mockReturnValue(secondRegistry)

// Both source resolutions finish before either caller resumes its cache reads.
Expand Down Expand Up @@ -641,12 +812,30 @@ test('does not refresh a missing major cache when auto-upgrade is disabled and l
const fetch = vi.spyOn(httpClient, 'fetch')
await withCache(async () => {
confStore.cacheStore(latestCacheKey, nextMajorVersion)
confStore.cacheStore(nodeRangeCacheKey, cliNodeRangeCacheValue(nextMajorVersion, undefined))
await checkForNewVersionInBackground()
expect(versionToAutoUpgrade()).toBeUndefined()
expect(fetch).not.toHaveBeenCalled()
})
})

test('looks up the Node range of a latest release that another lookup cached when auto-upgrade is disabled', async () => {
vi.mocked(confStore.getAutoUpgradeEnabled).mockReturnValue(false)
let requests = 0
await withRegistry(
http.get('https://registry.npmjs.org/*', () => {
requests += 1
return HttpResponse.json(metadata)
}),
async () => {
confStore.cacheStore(latestCacheKey, nextMajorVersion)
await checkForNewVersionInBackground()
await checkForCLIVersions({includeCurrentMajor: false})
expect(requests).toBe(1)
},
)
})

test('reads a fresh current-major version even when latest is not cached', async () => {
const fetch = vi.spyOn(httpClient, 'fetch')
await withCache(async () => {
Expand Down
23 changes: 18 additions & 5 deletions packages/cli-kit/src/private/node/cli-version-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import {
getCachedCLINodeRange,
getCachedCLIVersion,
getCLINodeRangeCacheKey,
getCLIUpgradeTargetCacheKey,
getCLIVersionCacheKey,
hasCachedCLINodeRange,
resolveCLIRegistry,
supportsRunningNode,
} from './cli-version-cache.js'
Expand Down Expand Up @@ -43,21 +45,32 @@ export function getCachedLatestCLINodeRange(): string | undefined {
return latest ? getCachedCLINodeRange(latest) : undefined
}

export async function checkForCLIVersions({includeCurrentMajor = true} = {}): Promise<CLIVersions> {
/**
* Whether the version lookup cached the Node range of the cached latest release, including that it declares none, so
* its `engines` can be checked against the running Node.
*/
export function hasCachedLatestCLINodeRange(): boolean {
const latest = getCachedCLIVersion()
return latest ? hasCachedCLINodeRange(latest) : false
}

export async function checkForCLIVersions({includeCurrentMajor = true, refresh = false} = {}): Promise<CLIVersions> {
try {
const registry = await resolveCLIRegistry()
const lookupKey = getCLIVersionCacheKey(registry, currentMajorRange)
const lookupKey = getCLIUpgradeTargetCacheKey(registry, currentMajorRange)
const pendingLookup = pendingLookups.get(lookupKey)
if (pendingLookup) return pendingLookup

const latest = getCachedCLIVersion(undefined, registry)
const currentMajor = getCachedCLIVersion(currentMajorRange, registry)
if (latest && (!includeCurrentMajor || currentMajor)) {
// A refresh, for a command about to install the result, skips the cache and the failure backoff. A latest version
// that another lookup cached comes without its Node range, which a manual upgrade needs.
if (!refresh && latest && hasCachedCLINodeRange(latest, registry) && (!includeCurrentMajor || currentMajor)) {
return {latest, currentMajor, latestNodeRange: getCachedCLINodeRange(latest, registry)}
}

const failure = cacheRetrieve(`${lookupKey}-lookup-failure`)
if (failure && Date.now() - failure.timestamp < failureBackoffMs) return {}
if (!refresh && failure && Date.now() - failure.timestamp < failureBackoffMs) return {}

const lookup = fetchAndCacheVersions(registry)
.catch(() => ({}))
Expand All @@ -75,7 +88,7 @@ export async function checkForCLIVersions({includeCurrentMajor = true} = {}): Pr

async function fetchAndCacheVersions(registry: string): Promise<CLIVersions> {
const latestCacheKey = getCLIVersionCacheKey(registry)
const currentMajorCacheKey = getCLIVersionCacheKey(registry, currentMajorRange)
const currentMajorCacheKey = getCLIUpgradeTargetCacheKey(registry, currentMajorRange)
const failureCacheKey = `${currentMajorCacheKey}-lookup-failure` as const
try {
const [{fetch}, {default: registryAuthToken}] = await Promise.all([
Expand Down
Loading
Loading