From 49d12fa1ca6bff6b21793617e8014471db873e38 Mon Sep 17 00:00:00 2001 From: "shopify-build-cli[bot]" <145388831+shopify-build-cli[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 21:17:55 +0000 Subject: [PATCH] Update from World Published by the World mirror. World-Commit: 122739b81d3d8e964ce161344ccb35dc19821bb0 --- .changeset/app-logs-throttle-retry.md | 5 ++ .changeset/node-22-20-floor.md | 6 ++ .changeset/post-quantum-tunnel.md | 5 ++ .../generated/generated_docs_data_v2.json | 4 +- packages/app/package.json | 2 +- .../app/src/cli/commands/app/logs.test.ts | 65 ++++++++++++++ packages/app/src/cli/commands/app/logs.ts | 4 +- .../src/cli/services/historical-logs/api.ts | 47 ++++++++-- .../src/cli/services/historical-logs/flags.ts | 3 +- .../services/historical-logs/service.test.ts | 90 ++++++++++++++++--- .../cli/services/historical-logs/service.ts | 22 +++-- .../src/cli/services/historical-logs/types.ts | 11 +++ packages/cli-kit/package.json | 2 +- packages/cli/README.md | 36 +++++++- packages/cli/oclif.manifest.json | 6 +- packages/cli/package.json | 2 +- packages/create-app/package.json | 2 +- packages/e2e/package.json | 2 +- packages/organizations/package.json | 2 +- packages/plugin-cloudflare/package.json | 2 +- .../src/install-cloudflared.test.ts | 5 ++ packages/plugin-cloudflare/src/tunnel.test.ts | 70 +++++++++++++++ packages/plugin-cloudflare/src/tunnel.ts | 16 +++- packages/plugin-did-you-mean/package.json | 2 +- packages/store/package.json | 2 +- packages/theme/package.json | 2 +- 26 files changed, 364 insertions(+), 51 deletions(-) create mode 100644 .changeset/app-logs-throttle-retry.md create mode 100644 .changeset/node-22-20-floor.md create mode 100644 .changeset/post-quantum-tunnel.md diff --git a/.changeset/app-logs-throttle-retry.md b/.changeset/app-logs-throttle-retry.md new file mode 100644 index 00000000000..aaf44c4789e --- /dev/null +++ b/.changeset/app-logs-throttle-retry.md @@ -0,0 +1,5 @@ +--- +'@shopify/app': patch +--- + +`shopify app logs` now says how long to wait when a search is throttled, and `--json` gives the wait in `error.details.retryAfterSeconds` and the remaining budget in `throttleStatus`. diff --git a/.changeset/node-22-20-floor.md b/.changeset/node-22-20-floor.md new file mode 100644 index 00000000000..e1168368733 --- /dev/null +++ b/.changeset/node-22-20-floor.md @@ -0,0 +1,6 @@ +--- +'@shopify/cli-kit': minor +'@shopify/cli': minor +--- + +Require Node ^22.20.0 or >=24.5.0, the first releases built on OpenSSL 3.5 diff --git a/.changeset/post-quantum-tunnel.md b/.changeset/post-quantum-tunnel.md new file mode 100644 index 00000000000..b513cfdf56c --- /dev/null +++ b/.changeset/post-quantum-tunnel.md @@ -0,0 +1,5 @@ +--- +'@shopify/plugin-cloudflare': patch +--- + +Cloudflare tunnels now require post-quantum key agreement; set `SHOPIFY_CLI_CLOUDFLARED_ENFORCE_POST_QUANTUM=0` to allow classical key agreement on networks that can't negotiate it. diff --git a/docs-shopify.dev/generated/generated_docs_data_v2.json b/docs-shopify.dev/generated/generated_docs_data_v2.json index 86b285fb00f..c2e403b120b 100644 --- a/docs-shopify.dev/generated/generated_docs_data_v2.json +++ b/docs-shopify.dev/generated/generated_docs_data_v2.json @@ -3347,7 +3347,7 @@ "syntaxKind": "PropertySignature", "name": "--sort ", "value": "string", - "description": "Select the oldest/newest matches using server-side sorting. Omit for faster, less-throttled retrieval.", + "description": "Select the oldest/newest matches using server-side sorting. Costs 2 credits per search instead of 1.", "isOptional": true, "environmentValue": "SHOPIFY_FLAG_SORT" }, @@ -3442,7 +3442,7 @@ "environmentValue": "SHOPIFY_FLAG_STORE" } ], - "value": "export interface applogs {\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias '?: string\n\n /**\n * The Client ID of your app.\n * @environment SHOPIFY_FLAG_CLIENT_ID\n */\n '--client-id '?: string\n\n /**\n * The name of the app configuration.\n * @environment SHOPIFY_FLAG_APP_CONFIG\n */\n '-c, --config '?: string\n\n /**\n * Exact app event or app billing event handle; excludes other record types.\n * @environment SHOPIFY_FLAG_EVENT_HANDLE\n */\n '--event-handle '?: string\n\n /**\n * Exact Function extension handle; excludes non-Function records.\n * @environment SHOPIFY_FLAG_FUNCTION_HANDLE\n */\n '--function-handle '?: string\n\n /**\n * Output the result as JSON. Automatically disables color output.\n * @environment SHOPIFY_FLAG_JSON\n */\n '-j, --json'?: ''\n\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n\n /**\n * Maximum number of records to return, from 1 through 1000.\n * @environment SHOPIFY_FLAG_LIMIT\n */\n '--limit '?: string\n\n /**\n * Exact REST HTTP method; excludes non-REST records.\n * @environment SHOPIFY_FLAG_METHOD\n */\n '--method '?: string\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Disable interactive prompts and browser authentication.\n * @environment SHOPIFY_FLAG_NO_INPUT\n */\n '--no-input'?: ''\n\n /**\n * Exact GraphQL operation name; excludes non-GraphQL records.\n * @environment SHOPIFY_FLAG_OPERATION_NAME\n */\n '--operation-name '?: string\n\n /**\n * Exact GraphQL operation type; excludes non-GraphQL records.\n * @environment SHOPIFY_FLAG_OPERATION_TYPE\n */\n '--operation-type '?: string\n\n /**\n * Sort direction: asc (oldest first, default with --sort) or desc (newest first).\n * @environment SHOPIFY_FLAG_ORDER\n */\n '--order '?: string\n\n /**\n * The path to your app directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path '?: string\n\n /**\n * Exact GraphQL or REST request ID; excludes other record types.\n * @environment SHOPIFY_FLAG_REQUEST_ID\n */\n '--request-id '?: string\n\n /**\n * Exact REST request path; excludes non-REST records.\n * @environment SHOPIFY_FLAG_REQUEST_PATH\n */\n '--request-path '?: string\n\n /**\n * Inclusive start: positive duration (s/m/h/d) or whole-second RFC 3339 timestamp.\n * @environment SHOPIFY_FLAG_SINCE\n */\n '--since '?: string\n\n /**\n * Select the oldest/newest matches using server-side sorting. Omit for faster, less-throttled retrieval.\n * @environment SHOPIFY_FLAG_SORT\n */\n '--sort '?: string\n\n /**\n * Recorded result status; not inferred from HTTP codes or response bodies.\n * @environment SHOPIFY_FLAG_STATUS\n */\n '--status '?: string\n\n /**\n * Exact webhook or REST HTTP status code (100–599); no status classes.\n * @environment SHOPIFY_FLAG_STATUS_CODE\n */\n '--status-code '?: string\n\n /**\n * Exact store handle or myshopify.com domain/URL.\n * @environment SHOPIFY_FLAG_STORE\n */\n '-s, --store '?: string\n\n /**\n * Exact Function execution or UI extension target; excludes other record types.\n * @environment SHOPIFY_FLAG_TARGET\n */\n '--target '?: string\n\n /**\n * Exact webhook topic; excludes non-webhook records.\n * @environment SHOPIFY_FLAG_TOPIC\n */\n '--topic '?: string\n\n /**\n * Log type; repeat to select multiple. Defaults to all supported types.\n * @environment SHOPIFY_FLAG_TYPE\n */\n '--type '?: string\n\n /**\n * Exclusive whole-second RFC 3339 end; defaults to the current time.\n * @environment SHOPIFY_FLAG_UNTIL\n */\n '--until '?: string\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" + "value": "export interface applogs {\n /**\n * Alias of the Shopify account to use for authentication.\n * @environment SHOPIFY_FLAG_AUTH_ALIAS\n */\n '--auth-alias '?: string\n\n /**\n * The Client ID of your app.\n * @environment SHOPIFY_FLAG_CLIENT_ID\n */\n '--client-id '?: string\n\n /**\n * The name of the app configuration.\n * @environment SHOPIFY_FLAG_APP_CONFIG\n */\n '-c, --config '?: string\n\n /**\n * Exact app event or app billing event handle; excludes other record types.\n * @environment SHOPIFY_FLAG_EVENT_HANDLE\n */\n '--event-handle '?: string\n\n /**\n * Exact Function extension handle; excludes non-Function records.\n * @environment SHOPIFY_FLAG_FUNCTION_HANDLE\n */\n '--function-handle '?: string\n\n /**\n * Output the result as JSON. Automatically disables color output.\n * @environment SHOPIFY_FLAG_JSON\n */\n '-j, --json'?: ''\n\n /**\n * Print the command's JSON schemas.\n * @environment SHOPIFY_FLAG_JSON_SCHEMA\n */\n '--json-schema'?: ''\n\n /**\n * Maximum number of records to return, from 1 through 1000.\n * @environment SHOPIFY_FLAG_LIMIT\n */\n '--limit '?: string\n\n /**\n * Exact REST HTTP method; excludes non-REST records.\n * @environment SHOPIFY_FLAG_METHOD\n */\n '--method '?: string\n\n /**\n * Disable color output.\n * @environment SHOPIFY_FLAG_NO_COLOR\n */\n '--no-color'?: ''\n\n /**\n * Disable interactive prompts and browser authentication.\n * @environment SHOPIFY_FLAG_NO_INPUT\n */\n '--no-input'?: ''\n\n /**\n * Exact GraphQL operation name; excludes non-GraphQL records.\n * @environment SHOPIFY_FLAG_OPERATION_NAME\n */\n '--operation-name '?: string\n\n /**\n * Exact GraphQL operation type; excludes non-GraphQL records.\n * @environment SHOPIFY_FLAG_OPERATION_TYPE\n */\n '--operation-type '?: string\n\n /**\n * Sort direction: asc (oldest first, default with --sort) or desc (newest first).\n * @environment SHOPIFY_FLAG_ORDER\n */\n '--order '?: string\n\n /**\n * The path to your app directory.\n * @environment SHOPIFY_FLAG_PATH\n */\n '--path '?: string\n\n /**\n * Exact GraphQL or REST request ID; excludes other record types.\n * @environment SHOPIFY_FLAG_REQUEST_ID\n */\n '--request-id '?: string\n\n /**\n * Exact REST request path; excludes non-REST records.\n * @environment SHOPIFY_FLAG_REQUEST_PATH\n */\n '--request-path '?: string\n\n /**\n * Inclusive start: positive duration (s/m/h/d) or whole-second RFC 3339 timestamp.\n * @environment SHOPIFY_FLAG_SINCE\n */\n '--since '?: string\n\n /**\n * Select the oldest/newest matches using server-side sorting. Costs 2 credits per search instead of 1.\n * @environment SHOPIFY_FLAG_SORT\n */\n '--sort '?: string\n\n /**\n * Recorded result status; not inferred from HTTP codes or response bodies.\n * @environment SHOPIFY_FLAG_STATUS\n */\n '--status '?: string\n\n /**\n * Exact webhook or REST HTTP status code (100–599); no status classes.\n * @environment SHOPIFY_FLAG_STATUS_CODE\n */\n '--status-code '?: string\n\n /**\n * Exact store handle or myshopify.com domain/URL.\n * @environment SHOPIFY_FLAG_STORE\n */\n '-s, --store '?: string\n\n /**\n * Exact Function execution or UI extension target; excludes other record types.\n * @environment SHOPIFY_FLAG_TARGET\n */\n '--target '?: string\n\n /**\n * Exact webhook topic; excludes non-webhook records.\n * @environment SHOPIFY_FLAG_TOPIC\n */\n '--topic '?: string\n\n /**\n * Log type; repeat to select multiple. Defaults to all supported types.\n * @environment SHOPIFY_FLAG_TYPE\n */\n '--type '?: string\n\n /**\n * Exclusive whole-second RFC 3339 end; defaults to the current time.\n * @environment SHOPIFY_FLAG_UNTIL\n */\n '--until '?: string\n\n /**\n * Increase the verbosity of the output. May include sensitive data.\n * @environment SHOPIFY_FLAG_VERBOSE\n */\n '--verbose'?: ''\n}" } }, "apprelease": { diff --git a/packages/app/package.json b/packages/app/package.json index b8d9ab2fe0c..30e24dd6413 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -89,7 +89,7 @@ "@vitest/coverage-istanbul": "^3.2.7" }, "engines": { - "node": ">=22.12.0" + "node": "^22.20.0 || >=24.5.0" }, "os": [ "darwin", diff --git a/packages/app/src/cli/commands/app/logs.test.ts b/packages/app/src/cli/commands/app/logs.test.ts index 205cbadb6b5..638fb0bf2b9 100644 --- a/packages/app/src/cli/commands/app/logs.test.ts +++ b/packages/app/src/cli/commands/app/logs.test.ts @@ -6,12 +6,27 @@ import {prepareLogInput} from '../../services/historical-logs/input.js' import {logsOutput, type LogsResult} from '../../services/historical-logs/types.js' import {Config} from '@oclif/core' import {afterEach, beforeEach, expect, test, vi} from 'vitest' +import {appManagementRequestDoc} from '@shopify/cli-kit/node/api/app-management' +import {Response, shopifyFetch} from '@shopify/cli-kit/node/http' +import {ensureAuthenticatedAppManagementAndBusinessPlatform} from '@shopify/cli-kit/node/session' import {mockAndCaptureOutput, withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' vi.mock('../../services/historical-logs/service.js', async (importOriginal) => ({ ...(await importOriginal()), retrieveLogs: vi.fn(), })) +vi.mock('@shopify/cli-kit/node/http', async (importOriginal) => ({ + ...(await importOriginal()), + shopifyFetch: vi.fn(), +})) +vi.mock('@shopify/cli-kit/node/session', async (importOriginal) => ({ + ...(await importOriginal()), + ensureAuthenticatedAppManagementAndBusinessPlatform: vi.fn(), +})) +vi.mock('@shopify/cli-kit/node/api/app-management', async (importOriginal) => ({ + ...(await importOriginal()), + appManagementRequestDoc: vi.fn(), +})) const originalColumns = Object.getOwnPropertyDescriptor(process.stdout, 'columns') @@ -65,6 +80,56 @@ test('help states the backend time-window limits', () => { expect(Logs.description).toContain('Maximum: 1-day window within the last 7 days, 1000 records.') }) +// The network, the session, the command's init hooks and process.exit are fake. The command, its service, the +// fatal-error handler and the JSON renderer are real, and the assertions read the bytes written to stdout. +test('a throttled --json search writes one JSON line that keeps line breaks in its messages', async () => { + const actualService = await vi.importActual( + '../../services/historical-logs/service.js', + ) + vi.mocked(retrieveLogs).mockImplementation(actualService.retrieveLogs) + vi.mocked(ensureAuthenticatedAppManagementAndBusinessPlatform).mockResolvedValue({ + appManagementToken: 'test-identity-token', + userId: 'test-user', + businessPlatformToken: 'test-business-token', + }) + vi.mocked(appManagementRequestDoc).mockResolvedValue({ + app: {key: 'test-app', organizationId: 'gid://shopify/Organization/42'}, + }) + const errors = [ + { + message: 'Usage throttled\n\nTry again', + path: ['app', 'logs'], + extensions: {code: 'THROTTLED', retryAfterSeconds: 42}, + }, + ] + vi.mocked(shopifyFetch).mockResolvedValue( + new Response(JSON.stringify({data: {app: {logs: null}}, errors}), { + status: 200, + headers: {'x-request-id': 'request-123'}, + }), + ) + vi.stubEnv('SHOPIFY_CLI_NO_ANALYTICS', '1') + vi.spyOn(Logs.prototype as unknown as {init(): Promise}, 'init').mockResolvedValue(undefined) + vi.spyOn(process, 'exit').mockImplementation(() => undefined as never) + const command = new Logs(['--client-id', 'test-app', '--json', '--no-input'], await Config.load()) + + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await (command as unknown as {_run(): Promise})._run() + + expect(stdout().trimEnd().split('\n')).toHaveLength(1) + expect(JSON.parse(stdout())).toEqual({ + error: { + type: 'abort', + message: 'App Logs throttled this query. Try again in about 42 seconds.\n\nRequest ID: request-123', + code: 'rate-limited', + details: {requestId: 'request-123', errors, retryAfterSeconds: 42}, + }, + }) + expect(stderr()).toBe('') + }) + expect(process.exit).toHaveBeenCalledWith(1) +}) + test('parses space/equals forms and forwards effective defaults', async () => { vi.mocked(retrieveLogs).mockResolvedValue(result()) await new Logs( diff --git a/packages/app/src/cli/commands/app/logs.ts b/packages/app/src/cli/commands/app/logs.ts index 30b3a7199f2..0f901f8aab9 100644 --- a/packages/app/src/cli/commands/app/logs.ts +++ b/packages/app/src/cli/commands/app/logs.ts @@ -11,10 +11,12 @@ export default class Logs extends BaseCommand { static summary = 'Lists historical app logs.' static descriptionWithMarkdown = `Returns a list of historical app logs and exits. Defaults to all supported log types. Use --type to select a type; repeat it to select multiple. -Fast retrieval is the default: leave out --sort. Prefer this mode with a narrow time window and selective filters to consume less throttle capacity. The CLI orders the returned records oldest first, but when the limit is reached they aren't necessarily the oldest or newest matches. +Fast retrieval is the default: leave out --sort. The CLI orders the returned records oldest first, but when the limit is reached they aren't necessarily the oldest or newest matches. Use server-side sorting only when selecting the oldest or newest matching records matters: --sort timestamp selects oldest first; add --order desc for newest first. This sorts before the result limit and is subject to API query limits. +Each search spends credits from your throttle budget for the organization, which all your apps and CLI sessions there share. A search without --sort costs 1 credit; a search with --sort costs 2. The time window and --limit don't change the cost, and a throttled search costs nothing. With --json, a throttled search fails with the error code rate-limited, and error.details.retryAfterSeconds gives the seconds to wait when the API returns it. + When fewer than --limit records are returned, all matching records available at query time were returned. Sorting isn't needed to establish completeness. Different filters combine with AND; each accepts one exact value. Type-specific filters, such as --topic, need a --type they apply to and exclude records without that field; combining --topic and --operation-name returns no records. --store, --status, --request-id and --status-code work without --type. diff --git a/packages/app/src/cli/services/historical-logs/api.ts b/packages/app/src/cli/services/historical-logs/api.ts index 413331c54d9..c686b7d6897 100644 --- a/packages/app/src/cli/services/historical-logs/api.ts +++ b/packages/app/src/cli/services/historical-logs/api.ts @@ -1,4 +1,5 @@ import {logError} from './catalog.js' +import {throttleStatus} from './types.js' import {LogApp} from '../../api/graphql/app-management/generated/log-app.js' import {TypedDocumentNode} from '@graphql-typed-document-node/core' import {numericIdFromGid} from '@shopify/cli-kit/common/gid' @@ -20,6 +21,7 @@ const responseSchema = zod.object({ errors: zod.array(graphqlError.passthrough()).optional(), extensions: zod.record(zod.unknown()).optional(), }) +const costExtensions = zod.object({cost: zod.object({throttleStatus})}) const queryErrorCodes = new Map([ ['THROTTLED', 'rate-limited'], @@ -78,6 +80,7 @@ export async function logsRequest, variables: NoInfer, + {throttledHint}: {throttledHint?: string} = {}, ) { const response = await shopifyFetch( `${connection.origin}/app_logs/unstable/organizations/${connection.organizationId}/graphql`, @@ -100,6 +103,8 @@ export async function logsRequest )[response.status] ?? 'logs-api-unavailable') + const retryAfter = response.headers.get('retry-after') + const retryAfterSeconds = + retryAfter && /^\d+$/.test(retryAfter) ? Number(retryAfter) : longestRequestedWait(errors ?? []) const message = errors?.length ? errors.map(({message}) => message).join('\n') : 'Check API availability, access, and authentication.' - const error = logError( - code, - response.ok ? message : `App Logs request failed (HTTP ${response.status}). ${message}`, - requestId, - ) - const retryAfter = response.headers.get('retry-after') + let displayedMessage = response.ok ? message : `App Logs request failed (HTTP ${response.status}). ${message}` + if (code === 'rate-limited') { + // The app lookup (path ["app"]) has its own App Management API rate limit, and an HTTP 429 comes from before the + // logs budget: --sort changes neither. + const appLookup = errors?.length ? errors.every(({path}) => path?.length === 1 && path[0] === 'app') : false + if (!response.ok) { + displayedMessage = throttledMessage(`App Logs request failed (HTTP ${response.status}).`, retryAfterSeconds) + } else if (appLookup) { + displayedMessage = throttledMessage('The App Management API throttled the app lookup.', retryAfterSeconds) + } else { + displayedMessage = throttledMessage('App Logs throttled this query.', retryAfterSeconds, throttledHint) + } + } + const error = logError(code, displayedMessage, requestId) const details = { ...(requestId ? {requestId} : {}), ...(result.success && errors?.length ? { errors, ...(result.data.extensions === undefined ? {} : {extensions: result.data.extensions}), + ...(currentThrottleStatus ? {throttleStatus: currentThrottleStatus} : {}), } : {}), - ...(retryAfter && /^\d+$/.test(retryAfter) ? {retryAfterSeconds: Number(retryAfter)} : {}), + ...(retryAfterSeconds === undefined ? {} : {retryAfterSeconds}), } if (Object.keys(details).length) error.details = details throw error @@ -139,7 +156,21 @@ export async function logsRequest}[]): number | undefined { + const waits = errors + .map(({extensions}) => extensions?.retryAfterSeconds) + .filter((wait): wait is number => typeof wait === 'number' && Number.isInteger(wait) && wait > 0) + return waits.length ? Math.max(...waits) : undefined +} + +function throttledMessage(summary: string, retryAfterSeconds: number | undefined, hint?: string): string { + const wait = retryAfterSeconds + ? `Try again in about ${retryAfterSeconds} ${retryAfterSeconds === 1 ? 'second' : 'seconds'}.` + : 'Try again shortly.' + return [summary, wait, hint].filter(Boolean).join(' ') } function throwIfRequestFailed(error: unknown, requestId?: string | null): void { diff --git a/packages/app/src/cli/services/historical-logs/flags.ts b/packages/app/src/cli/services/historical-logs/flags.ts index 51cc07d39c9..bddab6ebb43 100644 --- a/packages/app/src/cli/services/historical-logs/flags.ts +++ b/packages/app/src/cli/services/historical-logs/flags.ts @@ -94,8 +94,7 @@ export const historicalLogFlags = { env: 'SHOPIFY_FLAG_LIMIT', }), sort: Flags.string({ - description: - 'Select the oldest/newest matches using server-side sorting. Omit for faster, less-throttled retrieval.', + description: 'Select the oldest/newest matches using server-side sorting. Costs 2 credits per search instead of 1.', options: ['timestamp'], helpGroup: 'QUERY', env: 'SHOPIFY_FLAG_SORT', diff --git a/packages/app/src/cli/services/historical-logs/service.test.ts b/packages/app/src/cli/services/historical-logs/service.test.ts index 4145e4e84e4..c7a565f06f0 100644 --- a/packages/app/src/cli/services/historical-logs/service.test.ts +++ b/packages/app/src/cli/services/historical-logs/service.test.ts @@ -9,6 +9,7 @@ import {getAppAutomationToken} from '@shopify/cli-kit/node/environment' import {inTemporaryDirectory, writeFile} from '@shopify/cli-kit/node/fs' import {joinPath} from '@shopify/cli-kit/node/path' import {handler} from '@shopify/cli-kit/node/error' +import {unstyled} from '@shopify/cli-kit/node/output' import {withCapturedStandardStreams} from '@shopify/cli-kit/node/testing/output' import {afterEach, beforeEach, expect, test, vi} from 'vitest' @@ -46,6 +47,7 @@ const record = { shopId: 'gid://shopify/Shop/123', futureField: {nested: [null, false, 'unchanged']}, } +const throttleStatus = {maximumAvailable: 20, currentlyAvailable: 12.5, restoreRate: 1 / 60} beforeEach(() => { vi.useFakeTimers({toFake: ['Date'], now: new Date('2026-10-06T14:00:00Z')}) @@ -132,12 +134,17 @@ test.each(['client_id = ""', 'name = "unlinked-app"', 'client_id = ['])( test('submits one bounded search and preserves the native record JSON exactly', async () => { authorize() - logResponse() + respond({ + data: {app: {logs: {records: [{json: record}]}}}, + extensions: {cost: {requestedQueryCost: 1, actualQueryCost: 1, throttleStatus: {...throttleStatus, future: 1}}}, + }) const result = await retrieveLogs({...scope, status: 'failure', topic: 'orders/create'}) expect(result.logs).toEqual([record]) + expect(result.throttleStatus).toEqual(throttleStatus) await withCapturedStandardStreams(async ({stdout}) => { renderHistoricalLogs(result, true, 20) expect(JSON.parse(stdout()).logs).toEqual([record]) + expect(JSON.parse(stdout()).throttleStatus).toEqual(throttleStatus) expect(JSON.parse(stdout())).not.toHaveProperty('query') expect(JSON.parse(stdout())).not.toHaveProperty('pageInfo') expect(stdout()).not.toContain('test-identity-token') @@ -684,13 +691,15 @@ test.each([ const failure = await retrieveLogs(scope).catch((error: unknown) => error) expect(failure).toMatchObject({code: 'rate-limited', details: {errors, extensions}}) expect(failure).not.toHaveProperty('details.data') + expect(failure).not.toHaveProperty('details.retryAfterSeconds') + expect(failure).not.toHaveProperty('details.throttleStatus') vi.stubEnv('SHOPIFY_FLAG_JSON', '1') await withCapturedStandardStreams(async ({stdout, stderr}) => { await handler(failure) expect(JSON.parse(stdout())).toEqual({ error: { type: 'abort', - message: 'Timed out', + message: 'App Logs throttled this query. Try again shortly.', code: 'rate-limited', details: {errors, extensions}, }, @@ -766,17 +775,66 @@ test.each([ expect(shopifyFetch).toHaveBeenCalledTimes(1) }) -test('preserves the supplied retry header for HTTP-200 GraphQL throttling', async () => { - const errors = [{message: 'Throttled', extensions: {code: 'THROTTLED'}}] - authorize() - respond({errors}, 200, {'retry-after': '60'}) +test.each([ + { + source: 'the retry header before the errors', + headers: {'retry-after': '60'}, + input: {}, + seconds: 60, + message: 'App Logs throttled this query. Try again in about 60 seconds.', + }, + { + source: 'the longest wait in the errors', + headers: {}, + input: {sort: 'timestamp'}, + seconds: 42, + message: + 'App Logs throttled this query. Try again in about 42 seconds. Omit --sort to spend 1 credit instead of 2.', + }, + { + source: 'the app lookup, which --sort does not change', + headers: {}, + input: {sort: 'timestamp'}, + lookupOnly: true, + seconds: 7, + message: 'The App Management API throttled the app lookup. Try again in about 7 seconds.', + }, +])( + 'reports the wait of an HTTP-200 GraphQL throttle from $source', + async ({headers, input, lookupOnly, seconds, message}) => { + const lookupError = { + message: 'App lookup throttled', + path: ['app'], + extensions: {code: 'THROTTLED', retryAfterSeconds: 7}, + } + const searchError = { + message: 'Search throttled', + path: ['app', 'logs'], + extensions: {code: 'THROTTLED', retryAfterSeconds: 42}, + } + // Two aliased searches can each be throttled; a throttled lookup leaves no search to run. + const errors = lookupOnly + ? [lookupError] + : [{...searchError, extensions: {code: 'THROTTLED', retryAfterSeconds: 7}}, searchError] + const extensions = {cost: {requestedQueryCost: 2, actualQueryCost: 0, throttleStatus}} + authorize() + respond({data: {app: lookupOnly ? null : {logs: null}}, errors, extensions}, 200, headers) - await expect(retrieveLogs(scope)).rejects.toMatchObject({ - code: 'rate-limited', - details: {errors, retryAfterSeconds: 60}, - }) - expect(shopifyFetch).toHaveBeenCalledTimes(1) -}) + const failure = await retrieveLogs({...scope, ...input}).catch((error: unknown) => error) + + expect(failure).toMatchObject({ + code: 'rate-limited', + message, + details: {errors, extensions, throttleStatus, retryAfterSeconds: seconds}, + }) + await withCapturedStandardStreams(async ({stdout, stderr}) => { + await handler(failure) + expect(stdout()).toBe('') + expect(unstyled(stderr()).replace(/[\s│]+/g, ' ')).toContain(message) + }) + expect(shopifyFetch).toHaveBeenCalledTimes(1) + }, +) test.each([ [401, 'authentication-required'], @@ -791,6 +849,14 @@ test.each([ expect(shopifyFetch).toHaveBeenCalledTimes(1) }) +test('an HTTP 429 keeps its status and gives no --sort advice', async () => { + authorize() + respond({}, 429, {'retry-after': '5'}) + await expect(retrieveLogs({...scope, sort: 'timestamp'})).rejects.toMatchObject({ + message: 'App Logs request failed (HTTP 429). Try again in about 5 seconds.', + }) +}) + test.each([ {status: 200, code: 'log-query-failed', message: 'Access denied'}, {status: 403, code: 'forbidden', message: 'App Logs request failed (HTTP 403). Access denied'}, diff --git a/packages/app/src/cli/services/historical-logs/service.ts b/packages/app/src/cli/services/historical-logs/service.ts index b23b558c3c9..22433666cd8 100644 --- a/packages/app/src/cli/services/historical-logs/service.ts +++ b/packages/app/src/cli/services/historical-logs/service.ts @@ -19,14 +19,19 @@ export async function retrieveLogs(options: LogScopeOptions & LogInput): Promise const clientId = await resolveLogApp(options) const connection = await connectLogs(clientId, options['no-input'] ?? false) const window = resolveLogWindow(prepared.window) - const {data, requestId} = await logsRequest(connection, HistoricalLogs, { - clientId, - types: prepared.types.map(({backend}) => backend), - timestamp: {gte: window.since, lt: window.until}, - limit: prepared.limit, - filters: prepared.filters, - ...(prepared.ordering === 'none' ? {} : {sortKey: 'TIMESTAMP', reverse: prepared.ordering === 'timestamp-desc'}), - }) + const {data, requestId, throttleStatus} = await logsRequest( + connection, + HistoricalLogs, + { + clientId, + types: prepared.types.map(({backend}) => backend), + timestamp: {gte: window.since, lt: window.until}, + limit: prepared.limit, + filters: prepared.filters, + ...(prepared.ordering === 'none' ? {} : {sortKey: 'TIMESTAMP', reverse: prepared.ordering === 'timestamp-desc'}), + }, + prepared.ordering === 'none' ? {} : {throttledHint: 'Omit --sort to spend 1 credit instead of 2.'}, + ) const response = historicalLogsSchema.safeParse(data) if (!response.success || !response.data.app?.logs) throw logError('invalid-response', 'App Logs returned no valid log result.', requestId) @@ -61,6 +66,7 @@ export async function retrieveLogs(options: LogScopeOptions & LogInput): Promise }`, ] : [], + throttleStatus, }) } diff --git a/packages/app/src/cli/services/historical-logs/types.ts b/packages/app/src/cli/services/historical-logs/types.ts index b9552e46a7c..50640ac14c2 100644 --- a/packages/app/src/cli/services/historical-logs/types.ts +++ b/packages/app/src/cli/services/historical-logs/types.ts @@ -11,6 +11,16 @@ export const nativeLogRecord = zod .passthrough() .describe('Native record JSON. All additional approved API fields are preserved without renaming or truncation.') +export const throttleStatus = zod + .object({ + maximumAvailable: zod.number().describe('Credits in the throttle budget when it is full.'), + currentlyAvailable: zod.number().describe('Credits available when the API answered.'), + restoreRate: zod.number().describe('Credits restored per second.'), + }) + .describe( + 'The throttle budget that your apps in the organization share. Included when the API returns it, so scripts can pace their searches.', + ) + export const logsOutput = defineJsonOutputSchema({ name: 'HistoricalAppLogs', schema: zod @@ -22,6 +32,7 @@ export const logsOutput = defineJsonOutputSchema({ 'subset-timestamp-asc sorts only the returned subset in the CLI, not necessarily the oldest or newest matches when the limit is reached. timestamp-asc and timestamp-desc request server sorting before the limit.', ), limitations: zod.array(zod.string()).describe('Empty when fewer than the requested limit are returned.'), + throttleStatus: throttleStatus.optional(), }) .strict(), definitions: {AppLogRecord: nativeLogRecord}, diff --git a/packages/cli-kit/package.json b/packages/cli-kit/package.json index ddf66c5480d..4e9c0d6ea2a 100644 --- a/packages/cli-kit/package.json +++ b/packages/cli-kit/package.json @@ -177,7 +177,7 @@ "typedoc": "^0.28.20" }, "engines": { - "node": ">=22.12.0" + "node": "^22.20.0 || >=24.5.0" }, "os": [ "darwin", diff --git a/packages/cli/README.md b/packages/cli/README.md index 65be5e5ee16..b53501affff 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -5739,7 +5739,7 @@ QUERY FLAGS [env: SHOPIFY_FLAG_SINCE] --sort=