Skip to content
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

feat: properly handle task limits #67

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
7 changes: 4 additions & 3 deletions src/handlers/shared/start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,15 +156,16 @@ async function fetchUserIds(context: Context, username: string[]) {
}

async function handleTaskLimitChecks(username: string, context: Context, logger: Context["logger"], sender: string) {
const openedPullRequests = await getAvailableOpenedPullRequests(context, username);
const { approved, changes } = await getAvailableOpenedPullRequests(context, username);
const assignedIssues = await getAssignedIssues(context, username);
const { limit } = await getUserRoleAndTaskLimit(context, username);
const adjustedAssignedIssues = assignedIssues.length - approved.length + changes.length;

// check for max and enforce max
if (Math.abs(assignedIssues.length - openedPullRequests.length) >= limit) {
if (Math.abs(adjustedAssignedIssues) >= limit) {
logger.error(username === sender ? "You have reached your max task limit" : `${username} has reached their max task limit`, {
assignedIssues: assignedIssues.length,
openedPullRequests: openedPullRequests.length,
openedPullRequests: adjustedAssignedIssues,
limit,
});

Expand Down
12 changes: 12 additions & 0 deletions src/types/payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,18 @@ export type TimelineEvents = RestEndpointMethodTypes["issues"]["listEventsForTim
export type Assignee = Issue["assignee"];
export type GitHubIssueSearch = RestEndpointMethodTypes["search"]["issuesAndPullRequests"]["response"]["data"];

export type PullRequestConversationsResponse = {
repository: {
pullRequest: {
reviewThreads: {
nodes: {
isResolved: boolean;
}[];
};
};
};
};

export type Sender = { login: string; id: number };

export const ISSUE_TYPE = {
Expand Down
101 changes: 91 additions & 10 deletions src/utils/issue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { RestEndpointMethodTypes } from "@octokit/rest";
import { Endpoints } from "@octokit/types";
import ms from "ms";
import { Context } from "../types/context";
import { GitHubIssueSearch, Review } from "../types/payload";
import { GitHubIssueSearch, PullRequestConversationsResponse, Review } from "../types/payload";
import { getLinkedPullRequests, GetLinkedResults } from "./get-linked-prs";
import { getAllPullRequestsFallback, getAssignedIssuesFallback } from "./get-pull-requests-fallback";

Expand Down Expand Up @@ -176,7 +176,7 @@ export async function addAssignees(context: Context, issueNo: number, assignees:
async function getAllPullRequests(context: Context, state: Endpoints["GET /repos/{owner}/{repo}/pulls"]["parameters"]["state"] = "open", username: string) {
const { payload } = context;
const query: RestEndpointMethodTypes["search"]["issuesAndPullRequests"]["parameters"] = {
q: `org:${payload.repository.owner.login} author:${username} state:${state}`,
q: `org:${payload.repository.owner.login} author:${username} state:${state} is:pr`,
per_page: 100,
order: "desc",
sort: "created",
Expand Down Expand Up @@ -224,6 +224,53 @@ export async function getAllPullRequestReviews(context: Context, pullNumber: num
}
}

async function getReviewRequestsTimeline(context: Context, pullNumber: number, owner: string, repo: string) {
try {
const events = await context.octokit.paginate(context.octokit.rest.issues.listEventsForTimeline, {
owner,
repo,
issue_number: pullNumber,
per_page: 100,
});
return events
.filter(
(
event
): event is {
created_at: string | number | Date;
event: string;
} => typeof event.event === "string"
)
.filter((event) => event.event === "review_requested" || event.event === "review_request_removed");
} catch (error) {
console.error("Error fetching review request timeline events:", error);
return [];
}
}

async function getPullRequestConversations(context: Context, owner: string, repo: string, pullNumber: number) {
const query = `
query($owner: String!, $repo: String!, $pullNumber: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pullNumber) {
reviewThreads(first: 100) {
nodes {
isResolved
}
}
}
}
}
`;

const params = { owner, repo, pullNumber };
const result: PullRequestConversationsResponse = await context.octokit.graphql(query, {
...params,
});

return result.repository.pullRequest.reviewThreads.nodes;
}

export function getOwnerRepoFromHtmlUrl(url: string) {
const parts = url.split("/");
if (parts.length < 5) {
Expand All @@ -237,29 +284,63 @@ export function getOwnerRepoFromHtmlUrl(url: string) {

export async function getAvailableOpenedPullRequests(context: Context, username: string) {
const { reviewDelayTolerance } = context.config;
if (!reviewDelayTolerance) return [];
if (!reviewDelayTolerance) return { approved: [], changes: [] };

const openedPullRequests = await getOpenedPullRequestsForUser(context, username);
jordan-ae marked this conversation as resolved.
Show resolved Hide resolved
const result: (typeof openedPullRequests)[number][] = [];
const approved = [] as unknown[];
const changes = [] as unknown[];

for (let i = 0; openedPullRequests && i < openedPullRequests.length; i++) {
const openedPullRequest = openedPullRequests[i];
if (!openedPullRequest) continue;
const { owner, repo } = getOwnerRepoFromHtmlUrl(openedPullRequest.html_url);
const reviews = await getAllPullRequestReviews(context, openedPullRequest.number, owner, repo);

if (reviews.length > 0) {
const approvedReviews = reviews.find((review) => review.state === "APPROVED");
if (approvedReviews) {
result.push(openedPullRequest);
// Determine the latest review state
const latestReview = reviews[reviews.length - 1];
const latestReviewState = latestReview?.state;

// Check if all conversations have been reviewed
const conversations = await getPullRequestConversations(context, owner, repo, openedPullRequest.number);
const isResolved = conversations.every((thread: { isResolved: unknown }) => thread.isResolved);

if (latestReviewState === "APPROVED") {
approved.push(openedPullRequest);
continue;
}

if (isResolved) {
approved.push(openedPullRequest);
continue;
}

if (latestReviewState === "CHANGES_REQUESTED") {
changes.push(openedPullRequest);

// Track the time of the last "CHANGES_REQUESTED"s
const lastChangesRequestedTime = latestReview.submitted_at ? new Date(latestReview.submitted_at).getTime() : null;

// Fetch timeline or comments to check if reviewer has been re-requested
const reviewRequests = await getReviewRequestsTimeline(context, openedPullRequest.number, owner, repo);

// Find if any review request was made after the last changes requested
const isReviewRequestedAfterChanges = lastChangesRequestedTime
? reviewRequests.some((request) => new Date(request.created_at).getTime() > lastChangesRequestedTime)
: false;

if (isReviewRequestedAfterChanges) {
jordan-ae marked this conversation as resolved.
Show resolved Hide resolved
approved.push(openedPullRequest);
changes.pop();
continue;
}
}

if (reviews.length === 0 && new Date().getTime() - new Date(openedPullRequest.created_at).getTime() >= getTimeValue(reviewDelayTolerance)) {
result.push(openedPullRequest);
approved.push(openedPullRequest);
}
}
return result;

return { approved, changes };
}

export function getTimeValue(timeString: string): number {
Expand Down
Loading