diff --git a/.changeset/theme-admin-api-5xx-shopify-side.md b/.changeset/theme-admin-api-5xx-shopify-side.md new file mode 100644 index 00000000000..07f00a20f48 --- /dev/null +++ b/.changeset/theme-admin-api-5xx-shopify-side.md @@ -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. diff --git a/packages/cli-kit/src/private/node/api/graphql.ts b/packages/cli-kit/src/private/node/api/graphql.ts index 60e8e05a62a..f85453dc6a2 100644 --- a/packages/cli-kit/src/private/node/api/graphql.ts +++ b/packages/cli-kit/src/private/node/api/graphql.ts @@ -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 { if (error instanceof ClientError) return Array.isArray(error.response.errors) ? error.response.errors : [] if (error instanceof GraphQLClientError) return Array.isArray(error.errors) ? error.errors : [] diff --git a/packages/cli-kit/src/public/node/api/admin.test.ts b/packages/cli-kit/src/public/node/api/admin.test.ts index 8faa69cfdb1..00197d66d34 100644 --- a/packages/cli-kit/src/public/node/api/admin.test.ts +++ b/packages/cli-kit/src/public/node/api/admin.test.ts @@ -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; diff --git a/packages/cli-kit/src/public/node/api/admin.ts b/packages/cli-kit/src/public/node/api/admin.ts index 842d98709d3..088ed6f2fe0 100644 --- a/packages/cli-kit/src/public/node/api/admin.ts +++ b/packages/cli-kit/src/public/node/api/admin.ts @@ -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' @@ -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. * @@ -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 diff --git a/packages/cli-kit/src/public/node/api/graphql.ts b/packages/cli-kit/src/public/node/api/graphql.ts index a62158e9582..5b8f10104fe 100644 --- a/packages/cli-kit/src/public/node/api/graphql.ts +++ b/packages/cli-kit/src/public/node/api/graphql.ts @@ -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' @@ -291,17 +291,6 @@ async function performGraphQLRequest(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') } diff --git a/packages/cli-kit/src/public/node/themes/api.test.ts b/packages/cli-kit/src/public/node/themes/api.test.ts index 4a47643865d..f4fd734cb8d 100644 --- a/packages/cli-kit/src/public/node/themes/api.test.ts +++ b/packages/cli-kit/src/public/node/themes/api.test.ts @@ -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() + return {...actual, adminRequestDoc: vi.fn(), supportedApiVersions: vi.fn()} +}) vi.mock('../context/fqdn.js') vi.mock('../ui.js') vi.mock('@shopify/cli-kit/node/system') @@ -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)) }) }) @@ -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})) }) @@ -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) }) }) @@ -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, @@ -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('') 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', () => { @@ -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', () => { @@ -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( @@ -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( { diff --git a/packages/cli-kit/src/public/node/themes/api.ts b/packages/cli-kit/src/public/node/themes/api.ts index 4dec8c948f4..05fcb04b77e 100644 --- a/packages/cli-kit/src/public/node/themes/api.ts +++ b/packages/cli-kit/src/public/node/themes/api.ts @@ -27,10 +27,10 @@ import {GetThemes} from '../../../cli/api/graphql/admin/generated/get_themes.js' import {GetTheme} from '../../../cli/api/graphql/admin/generated/get_theme.js' import {FindDevelopmentThemeByName} from '../../../cli/api/graphql/admin/generated/find_development_theme_by_name.js' import {OnlineStorePasswordProtection} from '../../../cli/api/graphql/admin/generated/online_store_password_protection.js' -import {errorHandler, extractGraphQLErrors} from '../../../private/node/api/graphql.js' +import {errorHandler, extractGraphQLErrors, requestIdFromClientError} from '../../../private/node/api/graphql.js' import {TrustChallengeError, withTrustChallengeRetry} from '../../../private/node/themes/trust-challenge.js' import {RequestModeInput} from '../http.js' -import {adminRequestDoc, type AdminRequestOptions} from '../api/admin.js' +import {adminRequestDoc, AdminServerError, type AdminRequestOptions} from '../api/admin.js' import {AdminSession} from '../session.js' import {AbortError} from '../error.js' import {outputDebug} from '../output.js' @@ -76,8 +76,8 @@ export async function fetchTheme(id: number, session: AdminSession): Promise( return response } catch (error) { abortIfMissingThemeAccessScope(error) - abortIfTransientServerError(error) + abortIfServerError(error, options.session) throw error } } /** - * Requests a theme read with transient retries. An exhausted transient error gets the friendly theme - * error; any other API failure gets the default Admin API error mapping. + * Requests a theme read with transient retries. A server error gets the Shopify-side theme error; + * any other API failure gets the default Admin API error mapping. * * @param options - The Admin API request, without response options or request behaviour. * @returns The response data. @@ -677,22 +677,21 @@ async function requestThemeReadDoc( } /** - * Turns a transient server-side failure that is still failing after retries into a friendly, - * expected error instead of a crash with the raw GraphQL response. + * Turns a Shopify-side failure of a theme request into an `AbortError`, so it does not reach the + * error reporter as a CLI bug. It covers every HTTP 5xx, and a transient server error that still + * fails after its retries. Theme requests set `handleErrors: false`, so the GraphQL error handler + * does not map these errors for them. * * @param error - The error thrown by the Admin API request. + * @param session - The session of the request, for the store name in the message. */ -function abortIfTransientServerError(error: unknown): void { - if (!isTransientServerError(error)) return +function abortIfServerError(error: unknown, session: AdminSession): void { + if (!(error instanceof ClientError)) return + const {status} = error.response + if (status < 500 && !isTransientServerError(error)) return - const requestId = clientErrorRequestId(error) throw recordError( - new AbortError( - 'Shopify had a temporary problem and could not complete the request.', - requestId - ? `Wait a moment and try again. If the problem continues, contact Shopify support and include this request ID: ${requestId}` - : 'Wait a moment and try again.', - ), + new AdminServerError(session.storeFqdn, status >= 500 ? status : undefined, clientErrorRequestId(error)), ) } @@ -704,8 +703,7 @@ function clientErrorRequestId(error: ClientError): string | undefined { if (typeof requestId === 'string') return requestId } } - const headers = error.response.headers as {get?: (name: string) => string | null} | undefined - return headers?.get?.('x-request-id') ?? undefined + return requestIdFromClientError(error) } function abortIfMissingThemeAccessScope(error: unknown): void { diff --git a/packages/cli-kit/src/public/node/themes/theme-manager.test.ts b/packages/cli-kit/src/public/node/themes/theme-manager.test.ts index 0d7ee58a84c..92659e86509 100644 --- a/packages/cli-kit/src/public/node/themes/theme-manager.test.ts +++ b/packages/cli-kit/src/public/node/themes/theme-manager.test.ts @@ -2,10 +2,16 @@ import {ThemeManager} from './theme-manager.js' import {Theme} from './types.js' import {fetchTheme, findDevelopmentThemeByName, themeCreate} from './api.js' import {DEVELOPMENT_THEME_ROLE, UNPUBLISHED_THEME_ROLE} from './utils.js' -import {BugError} from '../error.js' +import {adminRequestDoc} from '../api/admin.js' +import {AbortError, BugError} from '../error.js' import {test, describe, expect, vi, beforeEach} from 'vitest' +import {ClientError} from 'graphql-request' vi.mock('./api.js') +vi.mock('../api/admin.js', async (importOriginal) => { + const actual = await importOriginal() + return {...actual, adminRequestDoc: vi.fn()} +}) vi.mock('../../../private/node/themes/generate-theme-name.js', () => ({ generateThemeName: vi.fn((context: string) => `${context} (test-123-hostname)`), })) @@ -29,6 +35,10 @@ class TestThemeManager extends ThemeManager { this.themeId = themeId } + storeThemeId(themeId: string): void { + this.setTheme(themeId) + } + protected setTheme(themeId: string): void { this.storedThemeId = themeId this.themeId = themeId @@ -162,6 +172,25 @@ describe('ThemeManager', () => { expect(result).toBeUndefined() expect(manager.getStoredThemeId()).toBeUndefined() }) + + test('keeps the stored theme ID when the Admin API returns a server error', async () => { + // Given + const api = await vi.importActual('./api.js') + vi.mocked(fetchTheme).mockImplementation(api.fetchTheme) + vi.mocked(adminRequestDoc).mockRejectedValue( + new ClientError({status: 500, errors: 'Internal Server Error' as any, headers: new Headers()} as any, { + query: '', + }), + ) + manager.storeThemeId('123') + + // When + const result = manager.fetch() + + // Then + await expect(result).rejects.toThrowError(AbortError) + expect(manager.getStoredThemeId()).toBe('123') + }) }) describe('generateThemeName', () => { diff --git a/packages/store/src/cli/services/store/execute/admin-transport.test.ts b/packages/store/src/cli/services/store/execute/admin-transport.test.ts index 4990a9085ff..ad1884b5fc0 100644 --- a/packages/store/src/cli/services/store/execute/admin-transport.test.ts +++ b/packages/store/src/cli/services/store/execute/admin-transport.test.ts @@ -436,9 +436,7 @@ describe('fetchPublicApiVersions', () => { expect(captured).toBeInstanceOf(AbortError) expect(captured).not.toBeInstanceOf(BugError) // A raw `ClientError` reaching the reporter is filed as an unexpected CLI bug; an AbortError is not. - expect(captured?.message).toBe( - `Couldn't read the supported API versions for ${store}: the Admin API returned a server error (HTTP 500).`, - ) + expect(captured?.message).toBe(`The Admin API for ${store} returned a server error (HTTP 500).`) expect(String((captured as unknown as {tryMessage?: string})?.tryMessage ?? '')).toContain( 'This is a problem on the Shopify side', ) diff --git a/packages/store/src/cli/services/store/execute/admin-transport.ts b/packages/store/src/cli/services/store/execute/admin-transport.ts index df976d0f5f3..5b0342c4a9c 100644 --- a/packages/store/src/cli/services/store/execute/admin-transport.ts +++ b/packages/store/src/cli/services/store/execute/admin-transport.ts @@ -5,7 +5,7 @@ import { throwIfStoredStoreAuthIsInvalid, ABORTED_FETCH_MESSAGE_FRAGMENTS, } from '../admin-errors.js' -import {adminUrl} from '@shopify/cli-kit/node/api/admin' +import {AdminServerError, adminUrl} from '@shopify/cli-kit/node/api/admin' import {graphqlRequest} from '@shopify/cli-kit/node/api/graphql' import {AbortError} from '@shopify/cli-kit/node/error' import {outputContent} from '@shopify/cli-kit/node/output' @@ -65,10 +65,7 @@ export async function fetchPublicApiVersions(input: { // Not in `classifyAdminApiError`, which `runAdminStoreGraphQLOperation` also calls. There a // 5xx can carry GraphQL errors about the user's own query, which must stay visible. if (isGraphQLClientErrorLike(error) && typeof error.response.status === 'number' && error.response.status >= 500) { - throw new AbortError( - `Couldn't read the supported API versions for ${input.adminSession.storeFqdn}: the Admin API returned a server error (HTTP ${error.response.status}).`, - 'This is a problem on the Shopify side, not with your command. Wait a moment and run it again.', - ) + throw new AdminServerError(input.adminSession.storeFqdn, error.response.status) } throw error