cli icon indicating copy to clipboard operation
cli copied to clipboard

Automatically retry partners requests that fail with 401

Open shauns opened this issue 10 months ago β€’ 4 comments

WHY are these changes introduced?

To improve error handling in the Partners API client by adding support for token refresh when unauthorized responses are received.

WHAT is this pull request doing?

Adds an unauthorized handler to the Partners API client that automatically refreshes the token when an unauthorized response is received. This prevents API requests from failing due to expired tokens by:

  1. Adding an optional unauthorizedHandler parameter to partnersRequest and partnersRequestDoc functions
  2. Creating a handler in the PartnersClient class that refreshes the token when needed
  3. Updating tests to expect the new handler parameter

Measuring impact

We should see an improvement in our internal command success metrics.

Look out for

Do we need to increase the scope of this? Other services and such.

Checklist

  • [x] I've considered possible cross-platform impacts (Mac, Linux, Windows)
  • [x] I've considered possible documentation changes

shauns avatar Apr 14 '25 14:04 shauns

This stack of pull requests is managed by Graphite. Learn more about stacking.

shauns avatar Apr 14 '25 14:04 shauns

Coverage report

St.:grey_question:
Category Percentage Covered / Total
🟑 Statements
76.59% (-0.11% πŸ”»)
9513/12420
🟑 Branches
71.75% (-0.06% πŸ”»)
4679/6521
🟑 Functions
76.41% (-0.06% πŸ”»)
2465/3226
🟑 Lines
77.12% (-0.11% πŸ”»)
8994/11662
Show files with reduced coverage πŸ”»
St.:grey_question:
File Statements Branches Functions Lines
πŸ”΄
... / partners-client.ts
25% (-0.66% πŸ”»)
28.57% (-3.01% πŸ”»)
18.03% (+1.08% πŸ”Ό)
24.68% (-0.66% πŸ”»)
🟒
... / api.ts
83.49% (-0.17% πŸ”»)
71.01% (+0.25% πŸ”Ό)
92.31% (-7.69% πŸ”»)
83.65% (+0.65% πŸ”Ό)
🟑
... / graphql.ts
80% (-20% πŸ”»)
60% (-11.43% πŸ”»)
90.91% (-9.09% πŸ”»)
79.59% (-20.41% πŸ”»)

Test suite run success

2217 tests passing in 966 suites.

Report generated by πŸ§ͺjest coverage report action from 23f1745887e8157507e578f8935e4385c5dcd51d

github-actions[bot] avatar Apr 14 '25 14:04 github-actions[bot]

We detected some changes at packages/*/src and there are no updates in the .changeset. If the changes are user-facing, run "pnpm changeset add" to track your changes and include them in the next release CHANGELOG.

github-actions[bot] avatar Apr 15 '25 12:04 github-actions[bot]

Differences in type declarations

We detected differences in the type declarations generated by Typescript for this branch compared to the baseline ('main' branch). Please, review them to ensure they are backward-compatible. Here are some important things to keep in mind:

  • Some seemingly private modules might be re-exported through public modules.
  • If the branch is behind main you might see odd diffs, rebase main into this branch.

New type declarations

We found no new type declarations in this PR

Existing type declarations

packages/cli-kit/dist/private/node/api.d.ts
@@ -11,6 +11,13 @@ type RequestOptions<T> = {
     request: () => Promise<T>;
     url: string;
 } & NetworkRetryBehaviour;
+export interface UnauthorizedHandlerThrow {
+    action: 'throw';
+}
+type UnauthorizedHandlerContinue = {
+    action: 'continue';
+} | undefined;
+export type UnauthorizedHandlerResult = Promise<UnauthorizedHandlerThrow | UnauthorizedHandlerContinue>;
 export declare function simpleRequestWithDebugLog<T extends {
     headers: Headers;
     status: number;
@@ -35,7 +42,7 @@ export declare function simpleRequestWithDebugLog<T extends {
 export declare function retryAwareRequest<T extends {
     headers: Headers;
     status: number;
-}>(requestOptions: RequestOptions<T>, errorHandler?: (error: unknown, requestId: string | undefined) => unknown, unauthorizedHandler?: () => Promise<void>, retryOptions?: {
+}>(requestOptions: RequestOptions<T>, errorHandler?: (error: unknown, requestId: string | undefined) => unknown, unauthorizedHandler?: () => UnauthorizedHandlerResult, retryOptions?: {
     limitRetriesTo?: number;
     defaultDelayMs?: number;
     scheduleDelay: (fn: () => void, delay: number) => void;

packages/cli-kit/dist/public/node/api/graphql.d.ts
@@ -1,3 +1,4 @@
+import { UnauthorizedHandlerResult, UnauthorizedHandlerThrow } from '../../../private/node/api.js';
 import { ConfSchema, TimeInterval } from '../../../private/node/conf-store.js';
 import { LocalStorage } from '../local-storage.js';
 import { rawRequest, RequestDocument, Variables } from 'graphql-request';
@@ -16,6 +17,11 @@ export interface CacheOptions {
     cacheExtraKey?: string;
     cacheStore?: LocalStorage<ConfSchema>;
 }
+interface RefreshTokenOnAuthorizedResponseRetryWithNewToken {
+    action: 'retry';
+    token: string;
+}
+export type RefreshTokenOnAuthorizedResponse = Promise<UnauthorizedHandlerThrow | RefreshTokenOnAuthorizedResponseRetryWithNewToken>;
 interface GraphQLRequestBaseOptions<TResult> {
     api: string;
     url: string;
@@ -25,18 +31,19 @@ interface GraphQLRequestBaseOptions<TResult> {
     };
     responseOptions?: GraphQLResponseOptions<TResult>;
     cacheOptions?: CacheOptions;
+    refreshTokenOnAuthorizedResponse?: () => RefreshTokenOnAuthorizedResponse;
 }
 export type GraphQLRequestOptions<T> = GraphQLRequestBaseOptions<T> & {
     query: RequestDocument;
     variables?: Variables;
-    unauthorizedHandler?: () => Promise<void>;
+    unauthorizedHandler?: () => UnauthorizedHandlerResult;
 };
 export type GraphQLRequestDocOptions<TResult, TVariables> = GraphQLRequestBaseOptions<TResult> & {
     query: TypedDocumentNode<TResult, TVariables> | TypedDocumentNode<TResult, Exact<{
         [key: string]: never;
     }>>;
     variables?: TVariables;
-    unauthorizedHandler?: () => Promise<void>;
+    unauthorizedHandler?: () => UnauthorizedHandlerResult;
 };
 export interface GraphQLResponseOptions<T> {
     handleErrors?: boolean;

packages/cli-kit/dist/public/node/api/partners.d.ts
@@ -1,4 +1,4 @@
-import { GraphQLVariables, GraphQLResponse, CacheOptions } from './graphql.js';
+import { GraphQLVariables, GraphQLResponse, CacheOptions, RefreshTokenOnAuthorizedResponse } from './graphql.js';
 import { Variables } from 'graphql-request';
 import { TypedDocumentNode } from '@graphql-typed-document-node/core';
 /**
@@ -8,9 +8,10 @@ import { TypedDocumentNode } from '@graphql-typed-document-node/core';
  * @param token - Partners token.
  * @param variables - GraphQL variables to pass to the query.
  * @param cacheOptions - Cache options.
+ * @param refreshTokenOnAuthorizedResponse - Optional handler for unauthorized requests.
  * @returns The response of the query of generic type <T>.
  */
-export declare function partnersRequest<T>(query: string, token: string, variables?: GraphQLVariables, cacheOptions?: CacheOptions): Promise<T>;
+export declare function partnersRequest<T>(query: string, token: string, variables?: GraphQLVariables, cacheOptions?: CacheOptions, refreshTokenOnAuthorizedResponse?: () => RefreshTokenOnAuthorizedResponse): Promise<T>;
 export declare const generateFetchAppLogUrl: (cursor?: string, filters?: {
     status?: string;
     source?: string;
@@ -21,9 +22,10 @@ export declare const generateFetchAppLogUrl: (cursor?: string, filters?: {
  * @param query - GraphQL query to execute.
  * @param token - Partners token.
  * @param variables - GraphQL variables to pass to the query.
+ * @param refreshTokenOnAuthorizedResponse - Optional handler for unauthorized requests.
  * @returns The response of the query of generic type <TResult>.
  */
-export declare function partnersRequestDoc<TResult, TVariables extends Variables>(query: TypedDocumentNode<TResult, TVariables>, token: string, variables?: TVariables): Promise<TResult>;
+export declare function partnersRequestDoc<TResult, TVariables extends Variables>(query: TypedDocumentNode<TResult, TVariables>, token: string, variables?: TVariables, refreshTokenOnAuthorizedResponse?: () => RefreshTokenOnAuthorizedResponse): Promise<TResult>;
 /**
  * Sets the next deprecation date from [GraphQL response extensions](https://www.apollographql.com/docs/resources/graphql-glossary/#extensions)
  * if  objects contain a  (ISO 8601-formatted string).

github-actions[bot] avatar Apr 23 '25 12:04 github-actions[bot]

This PR seems inactive. If it's still relevant, please add a comment saying so. Otherwise, take no action. β†’ If there's no activity within a week, then a bot will automatically close this. Thanks for helping to improve Shopify's dev tooling and experience.

github-actions[bot] avatar May 26 '25 03:05 github-actions[bot]