Skip to content
Merged
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
11 changes: 7 additions & 4 deletions design/github.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,13 @@ also wake a Conversation or run an Event automation.
draft that Junior held, Junior marks it ready, so GitHub asks its code
owners only after the requester has looked.
- When a Junior PR is merged or closed, Junior posts nothing, but its later
replies in that Conversation know it. When GitHub says that it can merge
and no reviewer requests changes, the requester gets a "Ready to merge"
Inbox item. Where GitHub requires no review, a PR with no approval gets
it too, and the item tells the requester to review it before they merge.
replies in that Conversation know it. When GitHub says that it can merge,
no reviewer requests changes, and the requester has write access to the
repo, the requester gets a "Ready to merge" Inbox item. A requester
without write access gets no merge ask, because a person with write
access merges the PR. Where GitHub requires no review, a PR with no
approval gets it too, and the item tells the requester to review it
before they merge.
When a review is requested and still pending, the PR asks for that review
instead, even where the repo allows merging without one.
- When GitHub fails the next-action read for a while (rate limit or
Expand Down
1 change: 1 addition & 0 deletions packages/junior-github/src/webhooks/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ export function createGitHubWebhookRoute(args: {
};
await syncGitHubPullRequestActions({
botEmail,
cache: args.cache,
codeChanges: args.codeChanges,
db: args.db,
deliveryId,
Expand Down
52 changes: 43 additions & 9 deletions packages/junior-github/src/webhooks/installation-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -428,21 +428,31 @@ const repositoryPermissionSchema = z.object({
const REPOSITORY_ROLE_TTL_MS = 10 * 60 * 1000;

/**
* Read one user's role on a repository, with a metadata-only token. GitHub
* returns "none" for accounts without access, such as most bots. Roles are
* cached for ten minutes.
* One user's access to a repository. `role` is GitHub's `role_name`, which
* includes maintain, triage, and custom roles. `permission` is the base
* role that it maps to: admin, write, read, or none.
*/
export async function loadRepositoryRole(
interface RepositoryPermission {
permission: string;
role: string;
}

/**
* Read one user's access to a repository, with a metadata-only token.
* GitHub returns "none" for accounts without access, such as most bots. It
* is cached for ten minutes.
*/
async function loadRepositoryPermission(
env: GitHubInstallationEnv,
cache: PluginCache,
target: { login: string; repositoryFullName: string },
): Promise<string> {
): Promise<RepositoryPermission> {
const { owner, name } = splitRepository(
target.repositoryFullName,
"repository role",
);
return await cache.getOrLoad(
`repository-role:${owner}/${name}:${target.login}`.toLowerCase(),
return await cache.getOrLoad<RepositoryPermission>(
`repository-permission:${owner}/${name}:${target.login}`.toLowerCase(),
async () => {
const token = await issueInstallationToken({
...env,
Expand All @@ -456,15 +466,39 @@ export async function loadRepositoryRole(
{ responses: env.responses, token: token.token },
),
);
// role_name includes maintain, triage, and custom roles; permission does not.
return {
value: response.role_name?.trim() || response.permission,
value: {
permission: response.permission,
role: response.role_name?.trim() || response.permission,
},
ttlMs: REPOSITORY_ROLE_TTL_MS,
};
},
);
}

/** Read one user's role on a repository, such as "maintain" or "none". */
export async function loadRepositoryRole(
env: GitHubInstallationEnv,
cache: PluginCache,
target: { login: string; repositoryFullName: string },
): Promise<string> {
return (await loadRepositoryPermission(env, cache, target)).role;
}

/**
* Whether one user can merge pull requests on a repository: their base role
* is write or admin. Maintain and custom roles map to one of these.
*/
export async function loadRepositoryMergeAccess(
env: GitHubInstallationEnv,
cache: PluginCache,
target: { login: string; repositoryFullName: string },
): Promise<boolean> {
const { permission } = await loadRepositoryPermission(env, cache, target);
return permission === "admin" || permission === "write";
}

const timestampSchema = z.iso.datetime({ offset: true });

// GitHub can return a null node for a deleted or hidden item, so the
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ export function endedReason(
export function closeReason(
state: GitHubPullRequestMergeState,
previous: GitHubPullRequestAction,
mergeAccess: boolean | undefined,
): CloseReason {
const ended = endedReason(state.state);
if (ended) return ended;
Expand All @@ -38,6 +39,12 @@ export function closeReason(
if (state.autoMerge) {
return { reason: "Auto-merge is on.", status: "dismissed" };
}
if (mergeAccess === false) {
return {
reason: "Only a person with write access can merge it.",
status: "dismissed",
};
}
return {
reason: "The pull request is no longer ready to merge.",
status: "dismissed",
Expand Down
45 changes: 33 additions & 12 deletions packages/junior-github/src/webhooks/pull-request-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
*
* The action derives from GitHub state. It is "merge" when the pull request
* is open, not a draft, auto-merge is off, GitHub's merge state is `clean`,
* no reviewer still requests changes, and GitHub requests no review. GitHub
* no reviewer still requests changes, GitHub requests no review, and the
* requester has write access to the repository. A requester without it
* gets no merge ask: a person with write access merges it. GitHub
* gives `blocked` until a required review approves, so a pull request with
* no approval is "merge" only where GitHub requires no review, and its item
* asks the requester to review it first. A pending review request comes
Expand Down Expand Up @@ -69,6 +71,7 @@
*/
import type {
ConversationInboxItemChange,
PluginCache,
PluginCodeChanges,
PluginConversationInboxItems,
PluginLogger,
Expand Down Expand Up @@ -127,6 +130,7 @@ import { GitHubGraphqlError } from "./graphql-request.js";
import {
loadGraphqlRateLimitReset,
loadPullRequestMergeState,
loadRepositoryMergeAccess,
loadReviewAgainReader,
requestPullRequestReviewers,
type GitHubInstallationEnv,
Expand Down Expand Up @@ -269,6 +273,8 @@ async function showAction(
action: GitHubPullRequestAction | undefined;
dedupeKey: string;
identityId: string;
/** Undefined when this sync did not read it. */
mergeAccess: boolean | undefined;
number: number;
previous: GitHubPullRequestAction | undefined;
reason: GitHubReviewAskReason | undefined;
Expand Down Expand Up @@ -302,7 +308,7 @@ async function showAction(
} else if (args.previous) {
await items.close({
dedupeKey: args.dedupeKey,
...closeReason(state, args.previous),
...closeReason(state, args.previous, args.mergeAccess),
});
}
}
Expand Down Expand Up @@ -460,6 +466,8 @@ interface PullRequestActionSyncContext {
*/
askAfterRequesterActed?: boolean | undefined;
botEmail: string | undefined;
/** Holds the requester's repository access, which decides a merge ask. */
cache: PluginCache;
codeChanges: Pick<PluginCodeChanges, "list">;
db: GitHubDb;
env: GitHubInstallationEnv;
Expand Down Expand Up @@ -533,16 +541,27 @@ async function syncOne(
requesterAt: activity.requesterAt,
requesterLogin,
});
const next = nextAction(
state,
{
actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt),
askedAgain: asked !== undefined && reason !== undefined,
feedback: requesterFeedback(state, activity),
login: requesterLogin,
},
previous,
);
const requester = {
actedLast: timeOf(activity.requesterAt) > timeOf(activity.askedAt),
askedAgain: asked !== undefined && reason !== undefined,
feedback: requesterFeedback(state, activity),
login: requesterLogin,
};
const decide = (mergeAccess: boolean) =>
nextAction(state, { ...requester, mergeAccess }, previous);
const withAccess = decide(true);
// Only a merge ask, new or saved, needs the requester's access, so most
// syncs read none. Junior knows a requester's access only through their
// linked GitHub login.
const mergeAccess =
withAccess?.action === "merge" || previous === "merge"
? requesterLogin !== undefined &&
(await loadRepositoryMergeAccess(args.env, args.cache, {
login: requesterLogin,
repositoryFullName: target.repositoryFullName,
}))
: undefined;
const next = mergeAccess === false ? decide(false) : withAccess;
if (
!askedRequester &&
requesterLogin &&
Expand Down Expand Up @@ -583,6 +602,7 @@ async function syncOne(
action: next.action,
dedupeKey,
identityId: opener.identityId,
mergeAccess,
number: target.number,
previous,
reason,
Expand Down Expand Up @@ -796,6 +816,7 @@ export function startedTaskSyncContext(
): PullRequestActionSyncContext {
return {
botEmail: options.botEmail,
cache: ctx.cache,
codeChanges: ctx.codeChanges,
db: gitHubDbSchema.parse(ctx.db),
env: { ...options.env, responses: ctx.state, tokens: new Map() },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ export function nextAction(
/** `requesterFeedback`: the requester waits for Junior's answer. */
feedback: boolean;
login: string | undefined;
/**
* GitHub lets the requester merge on the repository. Without it, a
* person with write access merges, so the requester gets no merge ask.
*/
mergeAccess: boolean;
},
saved: GitHubPullRequestAction | undefined,
): { action?: GitHubPullRequestAction } | undefined {
Expand All @@ -116,6 +121,7 @@ export function nextAction(
// review request comes first, even where GitHub requires no review. So
// does the requester's feedback, because Junior acts next.
const canMerge =
requester.mergeAccess &&
Comment thread
sentry-junior[bot] marked this conversation as resolved.
Resolved
!state.draft &&
!state.autoMerge &&
!state.reviewPending &&
Expand Down
23 changes: 21 additions & 2 deletions packages/junior-github/tests/pull-request-action-harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@ export interface GitHubState {
laggingFeedback?: string[];
/** GitHub rejects review requests, such as during an outage. */
rejectReviewRequests?: boolean;
/**
* Each user's base role on the repository, by login. A user who is not
* listed has write access, so they can merge.
*/
permissions?: Record<string, "admin" | "none" | "read" | "write">;
/** The checks of the head commit. */
checks?: Array<{ conclusion: string | null; name: string; status: string }>;
/** The checks that a ruleset of the base branch requires. */
Expand Down Expand Up @@ -436,6 +441,15 @@ export function mockGitHub(github: GitHubState, requests: string[]) {
return HttpResponse.json({ content, id: 1 }, { status: 201 });
},
),
http.get(
"https://api.github.com/repos/getsentry/junior/collaborators/:login/permission",
({ params }) => {
const login = String(params["login"]);
requests.push(`permission ${login}`);
const permission = github.permissions?.[login] ?? "write";
return HttpResponse.json({ permission, role_name: permission });
},
),
http.get(
"https://api.github.com/repos/getsentry/junior/rules/branches/main",
() => {
Expand Down Expand Up @@ -705,10 +719,12 @@ export function route(
};
},
};
// These webhooks use no Conversation dispatch or cache.
// These webhooks use no Conversation dispatch.
const unused = () => {
throw new Error("The next-action webhooks do not use this");
};
// The requester's repository access stays cached across webhooks.
const cached = new Map<string, unknown>();
const annotations: PluginConversationAnnotations = {
forConversation() {
return {
Expand Down Expand Up @@ -745,7 +761,10 @@ export function route(
async update() {},
delete: unused,
get: unused,
getOrLoad: unused,
async getOrLoad<T>(key: string, load: () => Promise<{ value: T }>) {
if (!cached.has(key)) cached.set(key, (await load()).value);
return cached.get(key) as T;
},
},
inboxItems,
state,
Expand Down
Loading
Loading