Public: anyone can read this; the crew can change it.

GET a repository's commits answers `{ items, next_cursor }`, and every test that reads it is updated #16929

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/5083-get-a-repository-s-commits-answers-items → main 0 commits fork 1 thread · 1 unresolved

  • Merged. torque/5083-get-a-repository-s-commits-answers-items was merged into main as 73f303b.

Review

Sign in to review this change.
13 files changed +66 −25
docs/features/list-limit.md +1 −1
@@ -43,7 +43,7 @@ Every GET route the contract gives a `limit`, read by `parseLimit` (directly, or
4343 - [x] `/api/v1/repos` (max 200, cursor)
4444 - [x] `/api/v1/repos/{owner}/{name}/app/pulls` (max 100)
4545 - [x] `/api/v1/repos/{owner}/{name}/branches` (max 200, cursor)
46 - [x] `/api/v1/repos/{owner}/{name}/commits` (max 100)
46 - [x] `/api/v1/repos/{owner}/{name}/commits` (max 100, cursor)
4747 - [x] `/api/v1/repos/{owner}/{name}/decisions` (max 100, cursor)
4848 - [x] `/api/v1/repos/{owner}/{name}/events` (max 200, cursor)
4949 - [x] `/api/v1/repos/{owner}/{name}/family` (max 200)
scripts/home-eval.ts +3 −2
@@ -40,8 +40,9 @@ async function truth(): Promise<Truth> {
4040 for (let i = 0; i < live.length; i += 8) {
4141 await Promise.all(
4242 live.slice(i, i + 8).map(async (full) => {
43 const log: { date: string }[] = await get(`/api/v1/repos/${full}/commits?limit=1`);
44 if (log[0] !== undefined && Date.now() - Date.parse(log[0].date) > 3 * DAY) quiet.push(full);
43 const log: { items: { date: string }[] } = await get(`/api/v1/repos/${full}/commits?limit=1`);
44 const last = log.items[0];
45 if (last !== undefined && Date.now() - Date.parse(last.date) > 3 * DAY) quiet.push(full);
4546 }),
4647 );
4748 }
src/contract/openapi/routes/getApiV1ReposOwnerNameCommits.ts +1 −1
@@ -1,3 +1,3 @@
11 import { REPO, type Route, limitTo } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: `${REPO}/commits`, summary: "List commits newest first from `ref` as a bare array", detail: "List commits newest first from `ref` (default: the default branch) as a bare array of { oid, parents, author, email, date, subject, body }; limit 1 to 100 (default 30); an unsafe ref is a 422 bad_ref; a private repository needs a token; the 200 carries a weak etag, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body until the ref moves", auth: false, role: "anonymous", alsoStatus: [304], query: { ref: "string", limit: limitTo(100) }, refuses: [404] };
3 export const route: Route = { method: "get", path: `${REPO}/commits`, summary: "List commits newest first from `ref` as `{ items, next_cursor }`", detail: "List commits newest first from `ref` (default: the default branch) as `{ items, next_cursor }`, items of { oid, parents, author, email, date, subject, body }; limit 1 to 100 (default 30); a cursor (the next_cursor of the page before, 40 to 64 hex) continues the log after that commit and `ref` is then ignored, so the cursor's own history is paged (a malformed cursor or one naming no commit is a 422 invalid_cursor); an unsafe ref is a 422 bad_ref; a private repository needs a token; the 200 carries a weak etag, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body until the ref moves", auth: false, role: "anonymous", alsoStatus: [304], query: { ref: "string", cursor: "string", limit: limitTo(100) }, refuses: [404] };
src/http/api.ts +14 −3
@@ -2026,14 +2026,25 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
20262026 if (!isSafeRef(ref)) return json({ error: "bad_ref" }, 422);
20272027 const limit = parseLimit(ctx.url.searchParams.get("limit"), 100, 30);
20282028 if (limit === undefined) return limitRefusal(100);
2029 // The cursor is the last oid of the page before: the log goes on after it.
2030 const cursor = ctx.url.searchParams.get("cursor");
2031 if (cursor !== null && !/^[0-9a-f]{40,64}$/.test(cursor))
2032 return cursorRefusal("cursor is the next_cursor of a page before");
20292033 const log = await timePhaseAsync(ctx.request, "git", () =>
2030 commitLog(dirOf(ctx, repo), ref, { limit }),
2034 commitLog(dirOf(ctx, repo), cursor ?? ref, { limit: limit + 1, skip: cursor === null ? 0 : 1 }),

The cursor replaces ref as the git start point, so ?ref=x&cursor=<oid on y> pages y while the etag is keyed on x. Either refuse an oid that is not an ancestor of ref, or document in the route detail that ref is ignored once a cursor is given.

20312035 );
2036 if (cursor !== null && !log.ok)
2037 return cursorRefusal("cursor names a commit that is gone: start again without it");
20322038 // The tag is of the exact bytes sent plus the ref and limit asked, so a moved tip
20332039 // misses, a push to another branch does not, and two queries never share a tag.
20342040 return timePhase(ctx.request, "render", () => {
2035 const text = JSON.stringify(log.ok ? log.value : []);
2036 const etag = weakEtag(`${ref}\n${limit}\n${text}`);
2041 const all = log.ok ? log.value : [];
2042 const items = all.slice(0, limit);
2043 const text = JSON.stringify({
2044 items,
2045 next_cursor: all.length > limit ? items[items.length - 1]!.oid : null,
2046 });
2047 const etag = weakEtag(`${ref}\n${limit}\n${cursor ?? ""}\n${text}`);
20372048 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
20382049 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
20392050 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
test/api-commit-timing.test.ts +1 −1
@@ -44,7 +44,7 @@ beforeAll(async () => {
4444 });
4545 if (!done.ok) throw new Error(JSON.stringify(done.error));
4646 const res = await fetch(`${servers.url}/api/v1/repos/alice/r/commits?ref=main`, { headers: { cookie } });
47 oid = ((await res.json()) as { oid: string }[])[0]!.oid;
47 oid = ((await res.json()) as { items: { oid: string }[] }).items[0]!.oid;
4848 });
4949
5050 afterAll(async () => {
test/api-commits-timing.test.ts +3 −3
@@ -63,14 +63,14 @@ test("the commits list names session, git, render in order", async () => {
6363 const got = await phases("/api/v1/repos/alice/r/commits");
6464 expect(got.status).toBe(200);
6565 expect(got.names).toEqual(["session", "git", "render"]);
66 expect(JSON.parse(got.body)[0].subject).toBe("change");
66 expect(JSON.parse(got.body).items[0].subject).toBe("change");
6767 });
6868
69 test("an unknown ref still names the three phases and answers []", async () => {
69 test("an unknown ref still names the three phases and answers an empty page", async () => {
7070 const got = await phases("/api/v1/repos/alice/r/commits?ref=nope");
7171 expect(got.status).toBe(200);
7272 expect(got.names).toEqual(["session", "git", "render"]);
73 expect(JSON.parse(got.body)).toEqual([]);
73 expect(JSON.parse(got.body)).toEqual({ items: [], next_cursor: null });
7474 });
7575
7676 test("a bad ref is a 422 bad_ref", async () => {
test/api-list-shape.test.ts −1
@@ -19,7 +19,6 @@ import { seedAdmin } from "./helpers/admin.ts";
1919
2020 /** Routes that answer a bare array today → the open issue that changes them. */
2121 const BARE: Record<string, string> = {
22 "/api/v1/repos/:owner/:name/commits": "#5083",
2322 "/api/v1/user/origins": "#4841",
2423 "/api/v1/user/origin-apps": "#4841",
2524 // The Gitea dialect a connecting forge reads is a bare array by definition (#8900).
test/commits-etag.test.ts +28 −2
@@ -61,13 +61,15 @@ afterAll(async () => {
6161 await rm(dataDir, { recursive: true, force: true });
6262 });
6363
64 test("the 200 carries a weak tag, private no-cache and vary, and the body stays a bare array", async () => {
64 test("the 200 carries a weak tag, private no-cache and vary, and the body is { items, next_cursor }", async () => {
6565 const res = await get();
6666 expect(res.status).toBe(200);
6767 expect(res.headers.get("etag")).toMatch(/^W\/"/);
6868 expect(res.headers.get("cache-control")).toBe("private, no-cache");
6969 expect(res.headers.get("vary")).toContain("authorization, cookie");
70 expect(Array.isArray(await res.json())).toBe(true);
70 const body = (await res.json()) as { items: unknown[]; next_cursor: string | null };
71 expect(Array.isArray(body.items)).toBe(true);
72 expect(body.next_cursor).toBeNull();
7173 });
7274
7375 test("a matching If-None-Match is a bodiless 304 with the same headers and the security floor", async () => {
@@ -110,3 +112,27 @@ test("bad_ref 422 and 404 carry no etag", async () => {
110112 expect(missing.status).toBe(404);
111113 expect(missing.headers.get("etag")).toBeNull();
112114 });
115
116 test("a cursor continues the log after the last oid of the page before", async () => {
117 await commit("three");
118 type Page = { items: { oid: string }[]; next_cursor: string | null };
119 const first = (await (await get(`${URL_}?limit=1`)).json()) as Page;
120 expect(first.items).toHaveLength(1);
121 expect(first.next_cursor).toBe(first.items[0]!.oid);
122 const second = (await (await get(`${URL_}?limit=1&cursor=${first.next_cursor}`)).json()) as Page;
123 expect(second.items).toHaveLength(1);
124 expect(second.items[0]!.oid).not.toBe(first.items[0]!.oid);
125 const all = (await (await get(`${URL_}?limit=100`)).json()) as Page;
126 expect(all.items[1]!.oid).toBe(second.items[0]!.oid);
127 expect(all.next_cursor).toBeNull();
128 expect((await get(`${URL_}?cursor=zz`)).status).toBe(422);
129 expect((await get(`${URL_}?cursor=${"0".repeat(40)}`)).status).toBe(422);
130 });
131
132 test("with a cursor, ref is ignored: the cursor's own history is paged", async () => {
133 type Page = { items: { oid: string }[]; next_cursor: string | null };
134 const first = (await (await get(`${URL_}?limit=1`)).json()) as Page;
135 const plain = (await (await get(`${URL_}?limit=1&cursor=${first.next_cursor}`)).json()) as Page;
136 const withRef = (await (await get(`${URL_}?ref=side&limit=1&cursor=${first.next_cursor}`)).json()) as Page;
137 expect(withRef).toEqual(plain);
138 });
test/origin-pull-state.test.ts +1 −1
@@ -152,7 +152,7 @@ describe("a pull proposed to an origin forge", () => {
152152 expect(getPull(mine.db, mirror().id, number)?.originUrl).toContain(`/bob/app/pulls/${number}`);
153153
154154 // The commit that arrived keeps its author.
155 const commits = (await (await bobApi("/api/v1/repos/bob/app/commits?ref=alice/main&limit=1")).json()) as { author: string; subject: string }[];
155 const commits = ((await (await bobApi("/api/v1/repos/bob/app/commits?ref=alice/main&limit=1")).json()) as { items: { author: string; subject: string }[] }).items;
156156 expect(commits[0]).toMatchObject({ author: "alice", subject: "my change" });
157157
158158 // Asking for the hook is off the request path: it lands shortly after.
test/parity.test.ts +1 −1
@@ -1101,7 +1101,7 @@ describe("parity: full control through actions and the API", () => {
11011101 expect((await call("GET", "/api/v1/repos/alice/pub/tags?cursor=a..b")).status).toBe(422);
11021102
11031103 const commits = await call("GET", "/api/v1/repos/alice/pub/commits");
1104 const oid = commits.list[0]!.oid as string;
1104 const oid = (commits.json.items as Json[])[0]!.oid as string;
11051105 const one = await call("GET", `/api/v1/repos/alice/pub/commits/${oid}`);
11061106 expect(one.status).toBe(200);
11071107 expect(one.json.oid).toBe(oid);
test/read-api.test.ts +3 −3
@@ -80,11 +80,11 @@ describe("read-back API (contents, branches, commits)", () => {
8080 });
8181
8282 test("commits walks history at a ref", async () => {
83 const commits = (await (
83 const commits = ((await (
8484 await api("/api/v1/repos/dev/lib/commits?ref=main")
8585 ).json()) as {
86 subject: string;
87 }[];
86 items: { subject: string }[];
87 }).items;
8888 expect(commits[0]?.subject).toBe("init");
8989 });
9090
test/view-source.test.ts +5 −3
@@ -142,9 +142,11 @@ describe("RepoSource: one repository, two places to read it from", () => {
142142 { path: "src/index.ts", content: SOURCE_FILE },
143143 ],
144144 });
145 const upstreamCommits = (await (
146 await fetch(`${originServers.url}/api/v1/repos/octo/widgets/commits`)
147 ).json()) as { oid: string; subject: string }[];
145 const upstreamCommits = (
146 (await (
147 await fetch(`${originServers.url}/api/v1/repos/octo/widgets/commits`)
148 ).json()) as { items: { oid: string; subject: string }[] }
149 ).items;
148150
149151 // The fake Forgejo API in front of it, describing the same repository —
150152 // the same files, the same log, so "equivalent" is a claim with teeth.
test/web-browse.test.ts +5 −3
@@ -130,9 +130,11 @@ describe("browsing an origin repository on the web", () => {
130130 { path: "src/index.ts", content: SOURCE_FILE },
131131 ],
132132 });
133 const upstream = (await (
134 await fetch(`${originServers.url}/api/v1/repos/octo/widgets/commits`)
135 ).json()) as { oid: string }[];
133 const upstream = (
134 (await (
135 await fetch(`${originServers.url}/api/v1/repos/octo/widgets/commits`)
136 ).json()) as { items: { oid: string }[] }
137 ).items;
136138 const tip = upstream[0]!.oid;
137139
138140 const state = newFakeState("forgejo", ORIGIN_LOGIN, ORIGIN_TOKEN);

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs