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
5 changes: 5 additions & 0 deletions .changeset/theme-admin-api-5xx-shopify-side.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/cli-kit': patch
---

Theme commands and the Admin API version check report an HTTP 5xx as a Shopify-side error with its request ID, and theme commands no longer forget the stored theme on one.
17 changes: 17 additions & 0 deletions packages/cli-kit/src/private/node/api/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,23 @@ ${outputToken.json(error.response.errors)}
}
}

/**
* Reads the `x-request-id` header of a failed GraphQL response.
*
* @param error - The error thrown by graphql-request.
* @returns The request ID, or undefined when the response has none.
*/
export function requestIdFromClientError(error: ClientError): string | undefined {
try {
// graphql-request types the response without headers, but it carries the fetch Response's headers.
const headers = (error.response as {headers?: {get?: (name: string) => string | null}}).headers
return headers?.get?.('x-request-id') ?? undefined
// eslint-disable-next-line no-catch-all/no-catch-all
} catch {
return undefined
}
}

export function extractGraphQLErrors(error: unknown): NonNullable<ClientError['response']['errors']> {
if (error instanceof ClientError) return Array.isArray(error.response.errors) ? error.response.errors : []
if (error instanceof GraphQLClientError) return Array.isArray(error.errors) ? error.errors : []
Expand Down
19 changes: 19 additions & 0 deletions packages/cli-kit/src/public/node/api/admin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,25 @@ describe('fetchApiVersions error classification', () => {
)
})

test('includes the request ID of an Admin API 5xx in the server error', async () => {
// Given
vi.mocked(graphqlRequestDoc).mockRejectedValue(
new ClientError({status: 503, headers: new Headers({'x-request-id': 'request-id'})} as any, {query: ''}),
)

// When
const error = await admin.fetchApiVersions(Session).catch((err: unknown) => err)

// Then
expect(error).toBeInstanceOf(AbortError)
expect((error as AbortError).message).toBe(
`The Admin API for ${Session.storeFqdn} returned a server error (HTTP 503).`,
)
expect(String((error as AbortError).tryMessage)).toBe(
'This is a problem on the Shopify side, not with your command. Wait a moment and try again. If the problem continues, contact Shopify support and include this request ID: request-id',
)
})

// The literal messages the runtimes emit, not the production constant: asserting against real
// observed wording keeps the test honest if someone edits the fragment list.
// 'The user aborted a request.' is node-fetch; 'This operation was aborted' is undici;
Expand Down
30 changes: 26 additions & 4 deletions packages/cli-kit/src/public/node/api/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
isThemeAccessSession,
} from '../../../private/node/api/rest.js'
import {isAbortedFetchError, isNetworkError} from '../../../private/node/api.js'
import {requestIdFromClientError} from '../../../private/node/api/graphql.js'
import {RequestModeInput, shopifyFetch} from '../http.js'
import {PublicApiVersions} from '../../../cli/api/graphql/admin/generated/public_api_versions.js'
import {themeKitAccessDomain} from '../../../private/node/constants.js'
Expand Down Expand Up @@ -154,6 +155,30 @@ export async function supportedApiVersions(
.sort()
}

/**
* An Admin API request that failed on the Shopify side, such as an HTTP 5xx. It is an `AbortError`,
* so the CLI does not report it as a bug.
*/
export class AdminServerError extends AbortError {
/**
* Creates the error with the store, the HTTP status and the request ID in its message.
*
* @param storeFqdn - The store that the request went to.
* @param status - The HTTP status of the response, when it is a 5xx.
* @param requestId - The request ID of the response, when it has one.
*/
constructor(storeFqdn: string, status?: number, requestId?: string) {
const httpStatus = status === undefined ? '' : ` (HTTP ${status})`
const contactSupport = requestId
? ` If the problem continues, contact Shopify support and include this request ID: ${requestId}`
: ''
super(
`The Admin API for ${storeFqdn} returned a server error${httpStatus}.`,
`This is a problem on the Shopify side, not with your command. Wait a moment and try again.${contactSupport}`,
)
}
}

/**
* GraphQL query to retrieve all API versions.
*
Expand Down Expand Up @@ -238,10 +263,7 @@ export async function fetchApiVersions(
// cannot have caused it. `isExpectedApiError` covers 502/503/504, but only for raw errors, so
// it never sees one we have already wrapped in a BugError.
if (error instanceof ClientError && error.response.status >= 500) {
throw new AbortError(
`The Admin API for ${session.storeFqdn} returned a server error (HTTP ${error.response.status}).`,
'This is a problem on the Shopify side, not with your command. Wait a moment and try again.',
)
throw new AdminServerError(session.storeFqdn, error.response.status, requestIdFromClientError(error))
}

// A cancelled request is neither a store-state failure nor a CLI bug. Checked before
Expand Down
13 changes: 1 addition & 12 deletions packages/cli-kit/src/public/node/api/graphql.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {buildHeaders, httpsAgent} from '../../../private/node/api/headers.js'
import {debugLogRequestInfo, errorHandler} from '../../../private/node/api/graphql.js'
import {debugLogRequestInfo, errorHandler, requestIdFromClientError} from '../../../private/node/api/graphql.js'
import {addPublicMetadata, runWithTimer} from '../metadata.js'
import {retryAwareRequest} from '../../../private/node/api.js'
import {requestIdsCollection} from '../../../private/node/request-ids.js'
Expand Down Expand Up @@ -291,17 +291,6 @@ async function performGraphQLRequest<TResult>(options: PerformGraphQLRequestOpti
return JSON.parse(result) as TResult
}

function requestIdFromClientError(error: ClientError): string | undefined {
try {
// graphql-request types the response without headers, but it carries the fetch Response's headers.
const headers = (error.response as {headers?: {get?: (name: string) => string | null}}).headers
return headers?.get?.('x-request-id') ?? undefined
// eslint-disable-next-line no-catch-all/no-catch-all
} catch {
return undefined
}
}

function graphQLCachePrincipalHash(url: string, token: string | undefined): string {
return sha256(JSON.stringify([url, token ?? ''])).toString('hex')
}
Expand Down
127 changes: 113 additions & 14 deletions packages/cli-kit/src/public/node/themes/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ import {isTTY, keypress} from '../ui.js'
import {test, vi, expect, describe, beforeEach} from 'vitest'
import {ClientError} from 'graphql-request'

vi.mock('../api/admin.js')
vi.mock('../api/admin.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../api/admin.js')>()
return {...actual, adminRequestDoc: vi.fn(), supportedApiVersions: vi.fn()}
})
vi.mock('../context/fqdn.js')
vi.mock('../ui.js')
vi.mock('@shopify/cli-kit/node/system')
Expand Down Expand Up @@ -184,12 +187,23 @@ describe('fetchTheme', () => {
'The authenticated account or access token is missing `read_themes` access scope.',
)
})
test('throws a friendly error instead of returning undefined when the server has a temporary problem', async () => {

test('throws a Shopify-side error instead of returning undefined when the server has a temporary problem', async () => {
vi.mocked(adminRequestDoc).mockRejectedValue(internalServerError('request-id'))

await expect(fetchTheme(123, session)).rejects.toThrow(
'Shopify had a temporary problem and could not complete the request.',
)
await expect(fetchTheme(123, session)).rejects.toThrow(TRANSIENT_SERVER_ERROR_MESSAGE)
})

test('aborts with a Shopify-side error instead of returning undefined when the Admin API returns HTTP 500', async () => {
// Given
vi.mocked(adminRequestDoc).mockRejectedValue(serverError(500, 'request-id'))

// When
const error = await fetchTheme(123, session).catch((error: unknown) => error)

// Then
expect(error).toBeInstanceOf(AbortError)
expect((error as AbortError).message).toBe(serverErrorMessage(500))
})
})

Expand All @@ -200,7 +214,7 @@ describe('fetchThemeAssets', () => {
const error = await fetchThemeAssets(123, ['templates/index.json'], session).catch((error) => error)

expect(error).toBeInstanceOf(AbortError)
expect(error.message).toEqual('Shopify had a temporary problem and could not complete the request.')
expect(error.message).toEqual(TRANSIENT_SERVER_ERROR_MESSAGE)
expect(error.tryMessage).toContain('request-id')
expect(adminRequestDoc).toHaveBeenCalledWith(expect.objectContaining({preferredBehaviour: expectedApiOptions}))
})
Expand Down Expand Up @@ -251,16 +265,14 @@ describe('passwordProtected', () => {
})
})

test('keeps the default handled error for a non-transient server error', async () => {
vi.mocked(adminRequestDoc).mockRejectedValue(
new ClientError({status: 500, headers: new Headers({'x-request-id': 'request-id'})} as any, {query: ''}),
)
test('throws a Shopify-side error for a non-transient HTTP 500', async () => {
vi.mocked(adminRequestDoc).mockRejectedValue(serverError(500, 'request-id'))

const error = await passwordProtected(session).catch((error) => error)

expect(error).toBeInstanceOf(AbortError)
expect(error.message).toContain('The Admin GraphQL API responded unsuccessfully with the HTTP status 500.')
expect(error.message).toContain('Request ID: request-id')
expect(error.message).toEqual(serverErrorMessage(500))
expect(error.tryMessage).toContain('request-id')
expect(shouldReportErrorAsUnexpected(error)).toBe(false)
})
})
Expand Down Expand Up @@ -398,7 +410,7 @@ describe('fetchThemes', () => {
)
})

test('throws a friendly error without the HTML body when retries of an HTTP 520 are exhausted', async () => {
test('throws a Shopify-side error without the HTML body when retries of an HTTP 520 are exhausted', async () => {
// Given
const errorResponse = {
status: 520,
Expand All @@ -412,11 +424,53 @@ describe('fetchThemes', () => {

// Then
expect(error).toBeInstanceOf(AbortError)
expect(error.message).toEqual('Shopify had a temporary problem and could not complete the request.')
expect(error.message).toEqual(serverErrorMessage(520))
expect(error.tryMessage).toContain('edge-request-id')
expect(error.tryMessage).not.toContain('<!DOCTYPE html>')
expect(shouldReportErrorAsUnexpected(error)).toBe(false)
})

test('aborts with a Shopify-side error instead of rethrowing a raw HTTP 500 ClientError', async () => {
// Given
const rawError = serverError(500, 'request-id')
vi.mocked(adminRequestDoc).mockRejectedValue(rawError)

// When
const error = await fetchThemes(session).catch((error: unknown) => error)

// Then
expect(shouldReportErrorAsUnexpected(rawError)).toBe(true)
expect(error).toBeInstanceOf(AbortError)
expect(shouldReportErrorAsUnexpected(error as AbortError)).toBe(false)
expect((error as AbortError).message).toBe(serverErrorMessage(500))
expect(String((error as AbortError).tryMessage)).toBe(
'This is a problem on the Shopify side, not with your command. Wait a moment and try again. If the problem continues, contact Shopify support and include this request ID: request-id',
)
})

test.each([501, 503])('aborts with a Shopify-side error for a raw HTTP %i ClientError', async (status) => {
// Given
vi.mocked(adminRequestDoc).mockRejectedValue(serverError(status))

// When
const error = await fetchThemes(session).catch((error: unknown) => error)

// Then
expect(error).toBeInstanceOf(AbortError)
expect((error as AbortError).message).toBe(serverErrorMessage(status))
})

test('rethrows a raw HTTP 404 ClientError unchanged', async () => {
// Given
const clientError = new ClientError({status: 404, headers: new Headers()} as any, {query: ''})
vi.mocked(adminRequestDoc).mockRejectedValue(clientError)

// When
const request = fetchThemes(session)

// Then
await expect(request).rejects.toBe(clientError)
})
})

describe('fetchChecksums', () => {
Expand Down Expand Up @@ -468,6 +522,21 @@ describe('fetchChecksums', () => {
expect(checksum[1]!.checksum).toEqual('f14a0bd594f4fee47b13fc09543098ff')
expect(checksum[2]!.checksum).toEqual(null)
})

test('aborts with a Shopify-side error without a request ID when the HTTP 500 response has none', async () => {
// Given
vi.mocked(adminRequestDoc).mockRejectedValue(serverError(500))

// When
const error = await fetchChecksums(123, session).catch((error: unknown) => error)

// Then
expect(error).toBeInstanceOf(AbortError)
expect((error as AbortError).message).toBe(serverErrorMessage(500))
expect(String((error as AbortError).tryMessage)).toBe(
'This is a problem on the Shopify side, not with your command. Wait a moment and try again.',
)
})
})

describe('themeCreate', () => {
Expand Down Expand Up @@ -541,6 +610,19 @@ describe('themeCreate', () => {
})
})

test('aborts with a Shopify-side error and sends the mutation once when the Admin API returns HTTP 500', async () => {
// Given
vi.mocked(adminRequestDoc).mockRejectedValue(serverError(500, 'request-id'))

// When
const error = await themeCreate(params, session).catch((error: unknown) => error)

// Then
expect(error).toBeInstanceOf(AbortError)
expect((error as AbortError).message).toBe(serverErrorMessage(500))
expect(adminRequestDoc).toHaveBeenCalledTimes(1)
})

test('throws a friendly error when access is denied by a missing theme write access scope', async () => {
vi.mocked(adminRequestDoc).mockRejectedValue(
themeAccessDeniedError(
Expand Down Expand Up @@ -1140,6 +1222,23 @@ describe('parseThemeFileContent', () => {
})
})

const TRANSIENT_SERVER_ERROR_MESSAGE = 'The Admin API for my-shop.myshopify.com returned a server error.'

function serverErrorMessage(status: number): string {
return `The Admin API for my-shop.myshopify.com returned a server error (HTTP ${status}).`
}

function serverError(status: number, requestId?: string): ClientError {
return new ClientError(
{
status,
errors: 'Internal Server Error' as any,
headers: new Headers(requestId ? {'x-request-id': requestId} : {}),
} as any,
{query: ''},
)
}

function trustChallengeError(redirectTo: string): ClientError {
return new ClientError(
{
Expand Down
Loading
Loading