Skip to content

Commit 6d031ad

Browse files
committed
✨ Add opt-in GitHub search pagination (#815)
1 parent 27870e1 commit 6d031ad

10 files changed

Lines changed: 411 additions & 59 deletions

File tree

‎packages/git/src/composition/components.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,15 @@ To read another page, repeat the search with an explicit `page` and the same
332332
<GitHub.Search query="is:pr is:open label:bug" sort="created" page={2} perPage={20} as="pageTwo" />
333333
```
334334

335+
Set `paginate={true}` to follow GitHub's next-page links. `page` selects the
336+
starting page and `perPage` applies to each request. The binding is an
337+
ordered array of GitHub response objects, even when only one page is available.
338+
339+
```mdx
340+
<GitHub.Search query="is:pr is:open label:bug" sort="created" paginate={true} as="pages" />
341+
<Query value={pages} yq="[.[].items[].html_url]" as="pullRequestUrls" />
342+
```
343+
335344
## IssueTracker
336345

337346
Selects the issue tracker its content works with.

‎packages/git/src/composition/components/GitHubSearch.ts‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,17 @@ export type SearchRequest = JsonObject & {
1717
order?: string;
1818
page: number;
1919
perPage: number;
20+
paginate?: true;
2021
};
2122

23+
export type SearchResult = JsonObject | JsonObject[];
24+
2225
interface GitHubSearchApi {
23-
search(repository: RepositorySelection, request: SearchRequest): Operation<JsonObject>;
26+
search(repository: RepositorySelection, request: SearchRequest): Operation<SearchResult>;
2427
}
2528

2629
export const GitHubSearch = createApi<GitHubSearchApi>("executablemd.git.github.search", {
27-
*search(): Operation<JsonObject> {
30+
*search(): Operation<SearchResult> {
2831
throw new GitOperationAdmissionError(
2932
SEARCH_ELEMENT,
3033
"this host has no GitHub search provider.",
@@ -97,8 +100,8 @@ function admitQuery(query: string): SearchRequest["kind"] {
97100
return selected === "is:issue" ? "issue" : "pr";
98101
}
99102

100-
function* search(props: Record<string, Json>): Operation<JsonObject> {
101-
const { query, sort, order, page = 1, perPage = 20 } = props;
103+
function* search(props: Record<string, Json>): Operation<SearchResult> {
104+
const { query, sort, order, page = 1, perPage = 20, paginate } = props;
102105
if (typeof query !== "string" || typeof page !== "number" || typeof perPage !== "number") {
103106
throw new GitOperationAdmissionError(SEARCH_ELEMENT, "the search arguments are invalid.");
104107
}
@@ -121,6 +124,7 @@ function* search(props: Record<string, Json>): Operation<JsonObject> {
121124
kind,
122125
page,
123126
perPage,
127+
...(paginate === true ? { paginate } : {}),
124128
...(typeof sort === "string"
125129
? { sort, order: typeof order === "string" ? order : "desc" }
126130
: {}),
@@ -138,11 +142,18 @@ export const githubSearchRegistration: ComponentRegistration = {
138142
order: { enum: ["asc", "desc"] },
139143
page: { type: "integer", minimum: 1, maximum: SEARCH_CEILING },
140144
perPage: { type: "integer", minimum: 1, maximum: 100 },
145+
paginate: {
146+
type: "boolean",
147+
description:
148+
"Follow GitHub's next page links starting at page and bind an ordered array of page bodies.",
149+
},
141150
},
142151
required: ["query"],
143152
additionalProperties: false,
144153
},
145-
returns: { type: "object" },
154+
returns: {
155+
oneOf: [{ type: "object" }, { type: "array", minItems: 1, items: { type: "object" } }],
156+
},
146157
fn: formDispatcher({
147158
forms: "self-closing",
148159
fn: search,
@@ -152,7 +163,7 @@ export const githubSearchRegistration: ComponentRegistration = {
152163
...documented({
153164
description:
154165
"Search the selected GitHub repository with GitHub's issue and pull-request query syntax.",
155-
as: "Required. Binds the original GitHub response JSON.",
166+
as: "Required. Binds one original GitHub response object, or an ordered array of response objects with paginate enabled.",
156167
context: null,
157168
}),
158169
};

‎packages/git/src/composition/pull-request-read-execution.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,7 @@
2727
*/
2828

2929
import { type Api, createApi } from "@effectionx/context-api";
30-
import type { JsonObject } from "@executablemd/core";
31-
import type { SearchRequest } from "./components/GitHubSearch.ts";
30+
import type { SearchRequest, SearchResult } from "./components/GitHubSearch.ts";
3231
import { scoped, type Operation } from "effection";
3332
import type {
3433
PullRequestReadRequestKind,
@@ -53,9 +52,9 @@ export interface PullRequestReadExecutionApi {
5352
search(
5453
repository: string,
5554
request: SearchRequest,
56-
transport: () => Operation<JsonObject>,
57-
validate: (value: unknown) => JsonObject,
58-
): Operation<JsonObject>;
55+
transport: () => Operation<SearchResult>,
56+
validate: (value: unknown) => SearchResult,
57+
): Operation<SearchResult>;
5958

6059
/**
6160
* Perform one admitted read under this profile's lifecycle.

‎packages/git/src/deno/composition/github-host.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,7 @@ export function denoGitHubAccess(
145145
method: request.method,
146146
headers: { ...request.headers },
147147
body: request.body,
148+
redirect: request.redirect,
148149
signal: controller.signal,
149150
}),
150151
);

‎packages/git/src/deno/composition/github-search.ts‎

Lines changed: 94 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,21 @@ import type { JsonObject } from "@executablemd/core";
33
import type { Operation } from "effection";
44
import {
55
GitHubSearch,
6+
SEARCH_CEILING,
67
SEARCH_ELEMENT,
78
type SearchRequest,
9+
type SearchResult,
810
} from "../../composition/components/GitHubSearch.ts";
911
import { PullRequestReadError } from "../../composition/errors.ts";
1012
import { PullRequestReadExecution } from "../../composition/pull-request-read-execution.ts";
1113
import type { RepositorySelection } from "../../composition/selection.ts";
1214
import {
1315
authorizedHeaders,
1416
GITHUB_API,
17+
type GitHubAccess,
18+
type GitHubHttpResponse,
1519
type GitHubSource,
20+
nextPage,
1621
parseGitHubRepository,
1722
readJson,
1823
} from "./github.ts";
@@ -40,7 +45,7 @@ export function useGitHubSearch(
4045
): Operation<void> {
4146
const resolved = gitHubPullRequestReadResolver(options);
4247
return GitHubSearch.around({
43-
*search([selection, request]): Operation<JsonObject> {
48+
*search([selection, request]): Operation<SearchResult> {
4449
const origin = yield* locator(selection);
4550
const repository = origin === undefined ? undefined : parseGitHubRepository(origin);
4651
if (repository === undefined) {
@@ -52,30 +57,25 @@ export function useGitHubSearch(
5257
if (!configuration?.allowed || !pullRequestAllowed(configuration.allowed, url)) {
5358
throw unavailable("this host has not authorized search in the selected Repository.");
5459
}
55-
const validate = (value: unknown) =>
56-
validateSearchPage(
57-
value,
58-
request,
59-
name,
60-
options.access?.endpoint ?? configuration.endpoint ?? GITHUB_API,
61-
);
60+
const apiBase = options.access?.endpoint ?? configuration.endpoint ?? GITHUB_API;
61+
const validate = (value: unknown, page: number) =>
62+
validateSearchPage(value, request, page, name, apiBase);
6263
return yield* PullRequestReadExecution.operations.search(
6364
url,
6465
request,
65-
() => readSearchPage(() => resolved.transport(configuration), name, request, validate),
66-
validate,
66+
() => readSearch(() => resolved.transport(configuration), name, request, validate),
67+
(value) => validateSearchResult(value, request, validate),
6768
);
6869
},
6970
});
7071
}
7172

72-
function* readSearchPage(
73+
function* readSearch(
7374
source: () => GitHubSource,
7475
repository: string,
7576
request: SearchRequest,
76-
validate: (value: unknown) => JsonObject,
77-
): Operation<JsonObject> {
78-
const endpoint = "/search/issues";
77+
validate: (value: unknown, page: number) => JsonObject,
78+
): Operation<SearchResult> {
7979
const parameters = new URLSearchParams({
8080
q: `repo:${repository} ${request.query}`,
8181
page: String(request.page),
@@ -86,32 +86,99 @@ function* readSearchPage(
8686
parameters.set("order", request.order);
8787
}
8888

89-
let response;
89+
let access: GitHubAccess;
90+
let headers: Record<string, string> | undefined;
9091
try {
91-
const access = yield* source().open();
92-
const headers = yield* authorizedHeaders(access, false);
93-
if (headers !== undefined) {
92+
access = yield* source().open();
93+
headers = yield* authorizedHeaders(access, false);
94+
} catch {
95+
throw unavailable("GitHub search could not authenticate or complete the request.");
96+
}
97+
if (headers === undefined) {
98+
throw unavailable("GitHub search requires a credential.");
99+
}
100+
101+
const first = new URL(`${access.endpoint}/search/issues?${parameters}`);
102+
let url = first.href;
103+
const pages: JsonObject[] = [];
104+
const last = lastAccessiblePage(request);
105+
for (let page = request.page; page <= last; page += 1) {
106+
let response: GitHubHttpResponse;
107+
try {
94108
response = yield* access.send({
95109
method: "GET",
96-
url: `${access.endpoint}${endpoint}?${parameters}`,
110+
url,
97111
headers,
112+
...(request.paginate ? { redirect: "error" } : {}),
98113
});
114+
} catch {
115+
throw unavailable("GitHub search could not complete the request.");
99116
}
100-
} catch {
101-
throw unavailable("GitHub search could not authenticate or complete the request.");
117+
if (response.status !== 200) {
118+
throw unavailable("GitHub did not return a search page.");
119+
}
120+
const value = validate(readJson(response.body), page);
121+
if (!request.paginate) {
122+
return value;
123+
}
124+
pages.push(value);
125+
if (page === last) {
126+
break;
127+
}
128+
const walk = nextPage(response.link, access.endpoint);
129+
if (walk.kind === "complete") {
130+
break;
131+
}
132+
if (walk.kind === "unfollowable" || !sameSearch(walk.url, first, page + 1)) {
133+
throw invalid();
134+
}
135+
url = walk.url;
102136
}
103-
if (response === undefined) {
104-
throw unavailable("GitHub search requires a credential.");
137+
return pages;
138+
}
139+
140+
function lastAccessiblePage(request: SearchRequest): number {
141+
return Math.ceil(SEARCH_CEILING / request.perPage);
142+
}
143+
144+
function sameSearch(link: string, first: URL, page: number): boolean {
145+
const next = new URL(link);
146+
const expected = new URLSearchParams(first.searchParams);
147+
expected.set("page", String(page));
148+
expected.sort();
149+
next.searchParams.sort();
150+
return (
151+
next.origin === first.origin &&
152+
next.pathname === first.pathname &&
153+
next.username === "" &&
154+
next.password === "" &&
155+
next.hash === "" &&
156+
next.searchParams.toString() === expected.toString()
157+
);
158+
}
159+
160+
function validateSearchResult(
161+
value: unknown,
162+
request: SearchRequest,
163+
validate: (value: unknown, page: number) => JsonObject,
164+
): SearchResult {
165+
if (!request.paginate) {
166+
return validate(value, request.page);
105167
}
106-
if (response.status !== 200) {
107-
throw unavailable("GitHub did not return a search page.");
168+
if (
169+
!Array.isArray(value) ||
170+
value.length === 0 ||
171+
value.length > lastAccessiblePage(request) - request.page + 1
172+
) {
173+
throw invalid();
108174
}
109-
return validate(readJson(response.body));
175+
return value.map((page, index) => validate(page, request.page + index));
110176
}
111177

112178
function validateSearchPage(
113179
received: unknown,
114180
request: SearchRequest,
181+
page: number,
115182
repository: string,
116183
apiBase: string,
117184
): JsonObject {
@@ -125,7 +192,7 @@ function validateSearchPage(
125192
throw invalid();
126193
}
127194
const { total_count: total, incomplete_results: incomplete, items } = value;
128-
const start = (request.page - 1) * request.perPage;
195+
const start = (page - 1) * request.perPage;
129196
const expectedRepository = `${apiBase}/repos/${repository}`.toLowerCase();
130197
const publicRepository = `${GITHUB_API}/repos/${repository}`.toLowerCase();
131198
if (

‎packages/git/src/deno/composition/github.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ export interface GitHubHttpRequest {
7171
readonly url: string;
7272
readonly headers: Readonly<Record<string, string>>;
7373
readonly body?: string;
74+
readonly redirect?: "error";
7475
}
7576

7677
/** One answer, as this adapter reads it. */

‎packages/git/src/deno/composition/pull-request-operations.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
*/
4444

4545
import { getExpansion, sourceDescription, type JsonObject } from "@executablemd/core";
46+
import type { SearchResult } from "../../composition/components/GitHubSearch.ts";
4647
import { createDurableOperation } from "@executablemd/durable-streams";
4748
import { scoped, type Operation } from "effection";
4849
import { PullRequestAPI } from "../../composition/pull-request-api.ts";
@@ -77,7 +78,7 @@ export { PULL_REQUEST_READ } from "./pull-request-read-retention.ts";
7778
export function useRetainedPullRequestReads(): Operation<void> {
7879
return PullRequestReadExecution.around(
7980
{
80-
*search([repository, request, transport, validate]): Operation<JsonObject> {
81+
*search([repository, request, transport, validate]): Operation<SearchResult> {
8182
const run = yield* getWorkflowRun();
8283
const expansion = yield* getExpansion();
8384
const configuration = gitOperationFingerprint([
@@ -87,6 +88,7 @@ export function useRetainedPullRequestReads(): Operation<void> {
8788
request.order ?? null,
8889
String(request.page),
8990
String(request.perPage),
91+
...(request.paginate ? ["paginate"] : []),
9092
]);
9193
const stored = yield* scoped(function* () {
9294
return yield createDurableOperation(

0 commit comments

Comments
 (0)