Skip to content
Closed
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
6 changes: 6 additions & 0 deletions .changeset/batch-github-graphql-queries.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@changesets/get-github-info": minor
"@changesets/changelog-github": minor
---

Batch GitHub GraphQL API requests to avoid "Timeout on validation of query" errors when there are many changesets. Also fixes DataLoader cache deduplication (was broken due to object reference equality) which caused redundant API lookups. Batch size defaults to 100 and is configurable via the `batchSize` config option or `CHANGESET_GITHUB_BATCH_SIZE` env var.
2 changes: 2 additions & 0 deletions packages/changelog-github/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ jest.mock(
links,
};
},
setBatchSize() {},
clearCache() {},
};
}
);
Expand Down
12 changes: 11 additions & 1 deletion packages/changelog-github/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { ChangelogFunctions } from "@changesets/types";
// @ts-ignore
import { config } from "dotenv";
import { getInfo, getInfoFromPullRequest } from "@changesets/get-github-info";
import {
getInfo,
getInfoFromPullRequest,
setBatchSize,
} from "@changesets/get-github-info";

config();

Expand Down Expand Up @@ -35,6 +39,9 @@ const changelogFunctions: ChangelogFunctions = {
'Please provide a repo to this changelog generator like this:\n"changelog": ["@changesets/changelog-github", { "repo": "org/repo" }]'
);
}
if (options.batchSize != null) {
setBatchSize(Number(options.batchSize));
}
if (dependenciesUpdated.length === 0) return "";

const changesetLink = `- Updated dependencies [${(
Expand Down Expand Up @@ -66,6 +73,9 @@ const changelogFunctions: ChangelogFunctions = {
'Please provide a repo to this changelog generator like this:\n"changelog": ["@changesets/changelog-github", { "repo": "org/repo" }]'
);
}
if (options.batchSize != null) {
setBatchSize(Number(options.batchSize));
}

let prFromSummary: number | undefined;
let commitFromSummary: string | undefined;
Expand Down
81 changes: 79 additions & 2 deletions packages/get-github-info/src/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getInfo, getInfoFromPullRequest } from ".";
import { getInfo, getInfoFromPullRequest, clearCache, setBatchSize } from ".";
import nock from "nock";
import prettier from "prettier";

Expand All @@ -11,6 +11,7 @@ beforeEach(() => {
});

afterEach(() => {
clearCache();
nock.cleanAll();
nock.enableNetConnect();
});
Expand Down Expand Up @@ -499,6 +500,82 @@ test("uses custom GITHUB_GRAPHQL_URL when set", async () => {
}
`);
} finally {
process.env.GITHUB_GRAPHQL_URL = originalGraphqlUrl;
if (originalGraphqlUrl === undefined) {
delete process.env.GITHUB_GRAPHQL_URL;
} else {
process.env.GITHUB_GRAPHQL_URL = originalGraphqlUrl;
}
}
});

test("setBatchSize throws on invalid values", () => {
expect(() => setBatchSize(0)).toThrow(RangeError);
expect(() => setBatchSize(-1)).toThrow(RangeError);
expect(() => setBatchSize(1.5)).toThrow(RangeError);
expect(() => setBatchSize(NaN)).toThrow(RangeError);
expect(() => setBatchSize(Infinity)).toThrow(RangeError);
});

test("setBatchSize accepts valid values", () => {
setBatchSize(1);
setBatchSize(50);
setBatchSize(100);
});

test("batches requests when batch size is smaller than request count", async () => {
setBatchSize(1);

function makeCommitData(commit: string, prNumber: number) {
return {
[`a${commit}`]: {
commitUrl: `https://github.com/emotion-js/emotion/commit/${commit}`,
associatedPullRequests: {
nodes: [
{
number: prNumber,
url: `https://github.com/emotion-js/emotion/pull/${prNumber}`,
mergedAt: "2019-11-07T06:43:58Z",
author: {
login: "Andarist",
url: "https://github.com/Andarist",
},
},
],
},
author: {
user: {
login: "Andarist",
url: "https://github.com/Andarist",
},
},
},
};
}

// With batch size 1 and 2 different commits, we expect 2 separate GraphQL calls
nock("https://api.github.com", {
reqheaders: {
Authorization: `Token ${process.env.GITHUB_TOKEN}`,
},
})
.post(apiPath)
.reply(
200,
JSON.stringify({ data: { a0: makeCommitData("a085003", 1613) } })
)
.post(apiPath)
.reply(
200,
JSON.stringify({ data: { a0: makeCommitData("b085004", 1614) } })
);

const [result1, result2] = await Promise.all([
getInfo({ commit: "a085003", repo: "emotion-js/emotion" }),
getInfo({ commit: "b085004", repo: "emotion-js/emotion" }),
]);

expect(result1.pull).toBe(1613);
expect(result1.user).toBe("Andarist");
expect(result2.pull).toBe(1614);
expect(result2.user).toBe("Andarist");
});
128 changes: 105 additions & 23 deletions packages/get-github-info/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,27 +77,44 @@ function makeQuery(repos: ReposWithCommitsAndPRsToFetch) {
`;
}

// why are we using dataloader?
// it provides use with two things
// 1. caching
// since getInfo will be called inside of changeset's getReleaseLine
// and there could be a lot of release lines for a single commit
// caching is important so we don't do a bunch of requests for the same commit
// 2. batching
// getReleaseLine will be called a large number of times but it'll be called at the same time
// so instead of doing a bunch of network requests, we can do a single one.
const GHDataLoader = new DataLoader(async (requests: RequestData[]) => {
const { GITHUB_GRAPHQL_URL, GITHUB_SERVER_URL, GITHUB_TOKEN } = readEnv();
if (!GITHUB_TOKEN) {
throw new Error(
`Please create a GitHub personal access token at ${GITHUB_SERVER_URL}/settings/tokens/new?scopes=read:user,repo:status&description=changesets-${new Date()
.toISOString()
.substring(
0,
10
)} with \`read:user\` and \`repo:status\` permissions and add it as the GITHUB_TOKEN environment variable`
);
const DEFAULT_BATCH_SIZE = 100;

let configuredBatchSize: number | undefined;

function isValidBatchSize(value: number): boolean {
return Number.isFinite(value) && Number.isInteger(value) && value > 0;
}

/**
* Set the batch size for GitHub GraphQL API requests.
* This controls how many commits/PRs are looked up in a single query.
* Can also be set via the CHANGESET_GITHUB_BATCH_SIZE environment variable.
*/
export function setBatchSize(size: number) {
if (!isValidBatchSize(size)) {
throw new RangeError("Batch size must be a finite integer greater than 0");
}
configuredBatchSize = size;
}

function getBatchSize(): number {
if (configuredBatchSize !== undefined) {
return configuredBatchSize;
}
const envVal = process.env.CHANGESET_GITHUB_BATCH_SIZE;
if (envVal) {
const parsed = parseInt(envVal, 10);
if (isValidBatchSize(parsed)) {
return parsed;
}
}
return DEFAULT_BATCH_SIZE;
}

async function fetchBatch(
requests: readonly RequestData[],
env: { GITHUB_GRAPHQL_URL: string; GITHUB_TOKEN: string }
): Promise<any[]> {
let repos: ReposWithCommitsAndPRsToFetch = {};
requests.forEach(({ repo, ...data }) => {
if (repos[repo] === undefined) {
Expand All @@ -108,10 +125,10 @@ const GHDataLoader = new DataLoader(async (requests: RequestData[]) => {

let fetchResponse;
try {
fetchResponse = await fetch(GITHUB_GRAPHQL_URL, {
fetchResponse = await fetch(env.GITHUB_GRAPHQL_URL, {
method: "POST",
headers: {
Authorization: `Token ${GITHUB_TOKEN}`,
Authorization: `Token ${env.GITHUB_TOKEN}`,
},
body: JSON.stringify({ query: makeQuery(repos) }),
});
Expand Down Expand Up @@ -172,7 +189,72 @@ const GHDataLoader = new DataLoader(async (requests: RequestData[]) => {
data.kind === "pull" ? data.pull : data.commit
]
);
});
}

// why are we using dataloader?
// it provides us with two things
// 1. caching
// since getInfo will be called inside of changeset's getReleaseLine
// and there could be a lot of release lines for a single commit
// caching is important so we don't do a bunch of requests for the same commit
// 2. batching
// getReleaseLine will be called a large number of times but it'll be called at the same time
// so instead of doing a bunch of network requests, we can do a single one.
const GHDataLoader = new DataLoader<RequestData, any>(
async (requests: readonly RequestData[]) => {
const { GITHUB_GRAPHQL_URL, GITHUB_SERVER_URL, GITHUB_TOKEN } = readEnv();
if (!GITHUB_TOKEN) {
throw new Error(
`Please create a GitHub personal access token at ${GITHUB_SERVER_URL}/settings/tokens/new?scopes=read:user,repo:status&description=changesets-${new Date()
.toISOString()
.substring(
0,
10
)} with \`read:user\` and \`repo:status\` permissions and add it as the GITHUB_TOKEN environment variable`
);
}

const batchSize = getBatchSize();
const totalBatches = Math.ceil(requests.length / batchSize);
const results: any[] = new Array(requests.length);

if (totalBatches > 1) {
console.error(
`Fetching GitHub info for ${requests.length} items in ${totalBatches} batches (batch size: ${batchSize})`
);
}

// Process requests in batches to avoid GitHub GraphQL API timeouts
// on query validation when there are many commits to look up
for (let offset = 0; offset < requests.length; offset += batchSize) {
const batchNum = Math.floor(offset / batchSize) + 1;
if (totalBatches > 1) {
console.error(`Fetching batch ${batchNum}/${totalBatches}...`);
}
Comment thread
TooTallNate marked this conversation as resolved.
Resolved
const batch = requests.slice(offset, offset + batchSize);
const batchResults = await fetchBatch(batch, {
GITHUB_GRAPHQL_URL,
GITHUB_TOKEN,
});
for (let i = 0; i < batchResults.length; i++) {
results[offset + i] = batchResults[i];
}
}

return results;
},
{
cacheKeyFn: (request: RequestData) =>
request.kind === "commit"
? `commit:${request.repo}:${request.commit}`
: `pull:${request.repo}:${request.pull}`,
}
);
Comment thread
TooTallNate marked this conversation as resolved.
Resolved

// exported for testing – lets callers reset the DataLoader's result cache
export function clearCache() {
GHDataLoader.clearAll();
}

export async function getInfo(request: {
commit: string;
Expand Down
Loading