-
Notifications
You must be signed in to change notification settings - Fork 2k
fix: replace 500 error with bad request due to bitbucket returning 429 #6872
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mathnogueira
wants to merge
7
commits into
main
Choose a base branch
from
fix/intercept-429-bitbucket
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+155
−86
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
3ec80f1
replace 500 error with bad request due to bitbucket returning 429
mathnogueira a45e660
better message
mathnogueira 767301a
fix lint issues
mathnogueira fd65269
search workspaces and repositories
mathnogueira 4894ca2
reviews
mathnogueira 560594f
fix lint
mathnogueira d3fa998
revert order
mathnogueira File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,4 +1,4 @@ | ||
| import { AxiosError } from "axios"; | ||
| import { AxiosError, HttpStatusCode } from "axios"; | ||
|
|
||
| import { request } from "@app/lib/config/request"; | ||
| import { BadRequestError } from "@app/lib/errors"; | ||
|
|
@@ -14,6 +14,19 @@ import { | |
| TBitbucketWorkspace | ||
| } from "./bitbucket-connection-types"; | ||
|
|
||
| const BITBUCKET_MAX_PAGES = 10; | ||
| const BITBUCKET_PAGE_SIZE = 100; | ||
|
|
||
| const ensureBitbucketRateLimitNotExceeded = (error: unknown): never => { | ||
| if (error instanceof AxiosError && error.response?.status === HttpStatusCode.TooManyRequests) { | ||
| throw new BadRequestError({ | ||
| message: | ||
| "Request to Bitbucket was blocked due to rate limiting. Bitbucket's rate limit window is 1 hour. Please try again later." | ||
| }); | ||
| } | ||
| throw error; | ||
| }; | ||
|
|
||
| export const getBitbucketConnectionListItem = () => { | ||
| return { | ||
| name: "Bitbucket" as const, | ||
|
|
@@ -62,7 +75,7 @@ interface BitbucketWorkspacesResponse { | |
| next?: string; | ||
| } | ||
|
|
||
| export const listBitbucketWorkspaces = async (appConnection: TBitbucketConnection) => { | ||
| export const listBitbucketWorkspaces = async (appConnection: TBitbucketConnection, search?: string) => { | ||
| const { email, apiToken } = appConnection.credentials; | ||
|
|
||
| const headers = { | ||
|
|
@@ -71,19 +84,22 @@ export const listBitbucketWorkspaces = async (appConnection: TBitbucketConnectio | |
| }; | ||
|
|
||
| let allWorkspaces: TBitbucketWorkspace[] = []; | ||
| let nextUrl: string | undefined = `${IntegrationUrls.BITBUCKET_API_URL}/2.0/user/workspaces?pagelen=100`; | ||
| let iterationCount = 0; | ||
|
|
||
| // Limit to 10 iterations, fetching at most 10 * 100 = 1000 workspaces | ||
| while (nextUrl && iterationCount < 10) { | ||
| // eslint-disable-next-line no-await-in-loop | ||
| const { data }: { data: BitbucketWorkspacesResponse } = await request.get<BitbucketWorkspacesResponse>(nextUrl, { | ||
| const baseUrl = new URL(`${IntegrationUrls.BITBUCKET_API_URL}/2.0/user/workspaces`); | ||
| baseUrl.searchParams.set("pagelen", BITBUCKET_PAGE_SIZE.toString()); | ||
| if (search) { | ||
| baseUrl.searchParams.set("q", `slug ~ "${search.replace(/"/g, "")}"`); | ||
| } | ||
|
|
||
| const endpoint = baseUrl.toString(); | ||
| try { | ||
| const { data }: { data: BitbucketWorkspacesResponse } = await request.get<BitbucketWorkspacesResponse>(endpoint, { | ||
| headers | ||
| }); | ||
|
|
||
| allWorkspaces = allWorkspaces.concat(data.values.map((membership) => ({ slug: membership.workspace.slug }))); | ||
| nextUrl = data.next; | ||
| iterationCount += 1; | ||
| } catch (error) { | ||
| ensureBitbucketRateLimitNotExceeded(error); | ||
| } | ||
|
|
||
| return allWorkspaces; | ||
|
|
@@ -94,27 +110,32 @@ interface BitbucketPaginatedResponse<T> { | |
| next?: string; | ||
| } | ||
|
|
||
| const BITBUCKET_MAX_PAGES = 10; | ||
| const BITBUCKET_PAGE_SIZE = 100; | ||
|
|
||
| const paginateBitbucketRequest = async <T>(url: string, headers: Record<string, string>): Promise<T[]> => { | ||
| let allItems: T[] = []; | ||
| let nextUrl: string | undefined = url; | ||
| let iterationCount = 0; | ||
|
|
||
| while (nextUrl && iterationCount < BITBUCKET_MAX_PAGES) { | ||
| // eslint-disable-next-line no-await-in-loop | ||
| const { data }: { data: BitbucketPaginatedResponse<T> } = await request.get(nextUrl, { headers }); | ||
| try { | ||
| while (nextUrl && iterationCount < BITBUCKET_MAX_PAGES) { | ||
| // eslint-disable-next-line no-await-in-loop | ||
| const { data }: { data: BitbucketPaginatedResponse<T> } = await request.get(nextUrl, { headers }); | ||
|
|
||
| allItems = allItems.concat(data.values); | ||
| nextUrl = data.next; | ||
| iterationCount += 1; | ||
| allItems = allItems.concat(data.values); | ||
| nextUrl = data.next; | ||
| iterationCount += 1; | ||
| } | ||
| } catch (error) { | ||
| ensureBitbucketRateLimitNotExceeded(error); | ||
| } | ||
|
|
||
| return allItems; | ||
| }; | ||
|
|
||
| export const listBitbucketRepositories = async (appConnection: TBitbucketConnection, workspaceSlug: string) => { | ||
| export const listBitbucketRepositories = async ( | ||
| appConnection: TBitbucketConnection, | ||
| workspaceSlug: string, | ||
| search?: string | ||
| ) => { | ||
| const { email, apiToken } = appConnection.credentials; | ||
|
|
||
| const headers = { | ||
|
|
@@ -124,22 +145,36 @@ export const listBitbucketRepositories = async (appConnection: TBitbucketConnect | |
|
|
||
| const encodedSlug = encodeURIComponent(workspaceSlug); | ||
|
|
||
| // Fetch repos per-project to avoid Bitbucket's 1,000-result pagination cap | ||
| const projects = await paginateBitbucketRequest<{ key: string }>( | ||
| `${IntegrationUrls.BITBUCKET_API_URL}/2.0/workspaces/${encodedSlug}/projects?pagelen=${BITBUCKET_PAGE_SIZE}`, | ||
| headers | ||
| ); | ||
| try { | ||
| if (search) { | ||
| const baseUrl = new URL(`${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${encodedSlug}`); | ||
| baseUrl.searchParams.set("pagelen", String(BITBUCKET_PAGE_SIZE)); | ||
| baseUrl.searchParams.set("sort", "slug"); | ||
| baseUrl.searchParams.set("q", `name ~ "${search.replace(/"/g, "")}"`); | ||
|
|
||
| const { data } = await request.get<BitbucketPaginatedResponse<TBitbucketRepo>>(baseUrl.toString(), { headers }); | ||
| return data.values; | ||
| } | ||
|
|
||
| const reposByProject = await Promise.all( | ||
| projects.map((project) => | ||
| paginateBitbucketRequest<TBitbucketRepo>( | ||
| `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${encodedSlug}?pagelen=${BITBUCKET_PAGE_SIZE}&sort=slug&q=project.key="${encodeURIComponent(project.key)}"`, | ||
| headers | ||
| // Fetch repos per-project to avoid Bitbucket's 1,000-result pagination cap | ||
| const projects = await paginateBitbucketRequest<{ key: string }>( | ||
| `${IntegrationUrls.BITBUCKET_API_URL}/2.0/workspaces/${encodedSlug}/projects?pagelen=${BITBUCKET_PAGE_SIZE}`, | ||
| headers | ||
| ); | ||
|
|
||
| const reposByProject = await Promise.all( | ||
| projects.map((project) => | ||
| paginateBitbucketRequest<TBitbucketRepo>( | ||
| `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${encodedSlug}?pagelen=${BITBUCKET_PAGE_SIZE}&sort=slug&q=project.key="${encodeURIComponent(project.key)}"`, | ||
| headers | ||
| ) | ||
| ) | ||
| ) | ||
| ); | ||
| ); | ||
|
|
||
| return reposByProject.flat(); | ||
| return reposByProject.flat(); | ||
| } catch (error) { | ||
| return ensureBitbucketRateLimitNotExceeded(error); | ||
| } | ||
| }; | ||
|
|
||
| export const listBitbucketEnvironments = async ( | ||
|
|
@@ -154,30 +189,8 @@ export const listBitbucketEnvironments = async ( | |
| Accept: "application/json" | ||
| }; | ||
|
|
||
| const environments: TBitbucketEnvironment[] = []; | ||
| let hasNextPage = true; | ||
|
|
||
| let environmentsUrl = `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${encodeURIComponent(workspaceSlug)}/${encodeURIComponent(repositorySlug)}/environments?pagelen=100`; | ||
|
|
||
| let iterationCount = 0; | ||
| // Limit to 10 iterations, fetching at most 10 * 100 = 1000 environments | ||
| while (hasNextPage && iterationCount < 10) { | ||
| // eslint-disable-next-line no-await-in-loop | ||
| const { data }: { data: { values: TBitbucketEnvironment[]; next: string } } = await request.get(environmentsUrl, { | ||
| headers | ||
| }); | ||
|
|
||
| if (data?.values.length > 0) { | ||
| environments.push(...data.values); | ||
| } | ||
|
|
||
| if (data.next) { | ||
| environmentsUrl = data.next; | ||
| } else { | ||
| hasNextPage = false; | ||
| } | ||
| iterationCount += 1; | ||
| } | ||
|
|
||
| return environments; | ||
| return paginateBitbucketRequest<TBitbucketEnvironment>( | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. environments don't support searching by a term, so it's the only endpoint we still need to run this logic. |
||
| `${IntegrationUrls.BITBUCKET_API_URL}/2.0/repositories/${encodeURIComponent(workspaceSlug)}/${encodeURIComponent(repositorySlug)}/environments?pagelen=${BITBUCKET_PAGE_SIZE}`, | ||
| headers | ||
| ); | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.