Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(github_pull_requests): store assignees, labels, and reviews on pull request rows (#7110)

dev-rba8f3aa83dfae
diff --git a/.sqlx/query-36b056b1d74f20890ead60b884ac428583a1608344356dbc7d2f6e50eede6102.json b/.sqlx/query-36b056b1d74f20890ead60b884ac428583a1608344356dbc7d2f6e50eede6102.json
new file mode 100644
index 0000000000..9dbc58dbbd
--- /dev/null
+++ b/.sqlx/query-36b056b1d74f20890ead60b884ac428583a1608344356dbc7d2f6e50eede6102.json
@@ -0,0 +1,30 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO github_pull_request (\n github_key,\n repository_id,\n number,\n owner,\n repo,\n title,\n status,\n draft,\n author_github_user_id,\n author_login,\n requested_reviewer_github_user_ids,\n participant_github_user_ids,\n github_updated_at,\n assignees,\n labels,\n reviews,\n review_decision\n )\n VALUES (\n $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13,\n $14::jsonb, $15::jsonb, $16::jsonb, $17\n )\n ON CONFLICT (github_key) DO UPDATE SET\n repository_id = COALESCE(EXCLUDED.repository_id, github_pull_request.repository_id),\n number = EXCLUDED.number,\n owner = EXCLUDED.owner,\n repo = EXCLUDED.repo,\n title = EXCLUDED.title,\n status = EXCLUDED.status,\n draft = EXCLUDED.draft,\n author_github_user_id = EXCLUDED.author_github_user_id,\n author_login = EXCLUDED.author_login,\n requested_reviewer_github_user_ids = EXCLUDED.requested_reviewer_github_user_ids,\n participant_github_user_ids = EXCLUDED.participant_github_user_ids,\n github_updated_at = EXCLUDED.github_updated_at,\n assignees = EXCLUDED.assignees,\n labels = EXCLUDED.labels,\n reviews = EXCLUDED.reviews,\n review_decision = EXCLUDED.review_decision,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int8",
+ "Int8",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Bool",
+ "Text",
+ "Text",
+ "TextArray",
+ "TextArray",
+ "Timestamptz",
+ "Jsonb",
+ "Jsonb",
+ "Jsonb",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "36b056b1d74f20890ead60b884ac428583a1608344356dbc7d2f6e50eede6102"
+}
diff --git a/.sqlx/query-45c058694137c5390aa599934b7d8fc3dcb5812605c1aa15a2787135be4997d9.json b/.sqlx/query-45c058694137c5390aa599934b7d8fc3dcb5812605c1aa15a2787135be4997d9.json
deleted file mode 100644
index a7e8cea936..0000000000
--- a/.sqlx/query-45c058694137c5390aa599934b7d8fc3dcb5812605c1aa15a2787135be4997d9.json
+++ /dev/null
@@ -1,26 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO github_pull_request (\n github_key,\n repository_id,\n number,\n owner,\n repo,\n title,\n status,\n draft,\n author_github_user_id,\n author_login,\n requested_reviewer_github_user_ids,\n participant_github_user_ids,\n github_updated_at\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)\n ON CONFLICT (github_key) DO UPDATE SET\n repository_id = COALESCE(EXCLUDED.repository_id, github_pull_request.repository_id),\n number = EXCLUDED.number,\n owner = EXCLUDED.owner,\n repo = EXCLUDED.repo,\n title = EXCLUDED.title,\n status = EXCLUDED.status,\n draft = EXCLUDED.draft,\n author_github_user_id = EXCLUDED.author_github_user_id,\n author_login = EXCLUDED.author_login,\n requested_reviewer_github_user_ids = EXCLUDED.requested_reviewer_github_user_ids,\n participant_github_user_ids = EXCLUDED.participant_github_user_ids,\n github_updated_at = EXCLUDED.github_updated_at,\n updated_at = NOW()\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "Int8",
- "Int8",
- "Text",
- "Text",
- "Text",
- "Text",
- "Bool",
- "Text",
- "Text",
- "TextArray",
- "TextArray",
- "Timestamptz"
- ]
- },
- "nullable": []
- },
- "hash": "45c058694137c5390aa599934b7d8fc3dcb5812605c1aa15a2787135be4997d9"
-}
diff --git a/.sqlx/query-683c65a8a703d8463efed57efc9fd06db7113ae4a015bd645c3482149443e3d4.json b/.sqlx/query-683c65a8a703d8463efed57efc9fd06db7113ae4a015bd645c3482149443e3d4.json
new file mode 100644
index 0000000000..b2fca67443
--- /dev/null
+++ b/.sqlx/query-683c65a8a703d8463efed57efc9fd06db7113ae4a015bd645c3482149443e3d4.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT 1 AS ignored FROM pg_advisory_xact_lock(1987213841)",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "ignored",
+ "type_info": "Int4"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "683c65a8a703d8463efed57efc9fd06db7113ae4a015bd645c3482149443e3d4"
+}
diff --git a/.sqlx/query-7a4f738dda70046cbfa4e15075519b3115c85886226c6d419d2dc77be84dce2b.json b/.sqlx/query-7a4f738dda70046cbfa4e15075519b3115c85886226c6d419d2dc77be84dce2b.json
new file mode 100644
index 0000000000..8c41252ada
--- /dev/null
+++ b/.sqlx/query-7a4f738dda70046cbfa4e15075519b3115c85886226c6d419d2dc77be84dce2b.json
@@ -0,0 +1,112 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT github_key, repository_id, number, owner, repo, title, status,\n draft, author_github_user_id, author_login,\n requested_reviewer_github_user_ids, participant_github_user_ids,\n github_updated_at, assignees, labels, reviews\n FROM github_pull_request WHERE github_key = $1 FOR UPDATE",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "github_key",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "repository_id",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 2,
+ "name": "number",
+ "type_info": "Int8"
+ },
+ {
+ "ordinal": 3,
+ "name": "owner",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "repo",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "title",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "status",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 7,
+ "name": "draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 8,
+ "name": "author_github_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 9,
+ "name": "author_login",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 10,
+ "name": "requested_reviewer_github_user_ids",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 11,
+ "name": "participant_github_user_ids",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 12,
+ "name": "github_updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 13,
+ "name": "assignees",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 14,
+ "name": "labels",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 15,
+ "name": "reviews",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ true,
+ false,
+ false,
+ false,
+ true,
+ true,
+ false,
+ true,
+ true,
+ false,
+ false,
+ true,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "7a4f738dda70046cbfa4e15075519b3115c85886226c6d419d2dc77be84dce2b"
+}
diff --git a/.sqlx/query-7e93321a1228780634c5fdc4189f4c66a9098d2860c6aa01ec58e22fd1ca06a7.json b/.sqlx/query-7e93321a1228780634c5fdc4189f4c66a9098d2860c6aa01ec58e22fd1ca06a7.json
new file mode 100644
index 0000000000..4244da7ffe
--- /dev/null
+++ b/.sqlx/query-7e93321a1228780634c5fdc4189f4c66a9098d2860c6aa01ec58e22fd1ca06a7.json
@@ -0,0 +1,40 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT title, draft, assignees, requested_reviewer_github_user_ids FROM github_pull_request WHERE github_key = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "title",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 2,
+ "name": "assignees",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "requested_reviewer_github_user_ids",
+ "type_info": "TextArray"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ true,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "7e93321a1228780634c5fdc4189f4c66a9098d2860c6aa01ec58e22fd1ca06a7"
+}
diff --git a/.sqlx/query-9e453315ff2ed288ca3b380e57c799da6c091ca5f836299f18266ca557030dba.json b/.sqlx/query-9e453315ff2ed288ca3b380e57c799da6c091ca5f836299f18266ca557030dba.json
new file mode 100644
index 0000000000..a867874256
--- /dev/null
+++ b/.sqlx/query-9e453315ff2ed288ca3b380e57c799da6c091ca5f836299f18266ca557030dba.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT draft, assignees, labels, requested_reviewer_github_user_ids, review_decision FROM github_pull_request WHERE github_key = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "assignees",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 2,
+ "name": "labels",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "requested_reviewer_github_user_ids",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 4,
+ "name": "review_decision",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "9e453315ff2ed288ca3b380e57c799da6c091ca5f836299f18266ca557030dba"
+}
diff --git a/.sqlx/query-c4945dec390eede39113f1c677cfd8a97272e7db948e506ed1c93505ec221f2f.json b/.sqlx/query-c4945dec390eede39113f1c677cfd8a97272e7db948e506ed1c93505ec221f2f.json
new file mode 100644
index 0000000000..dd40e406f1
--- /dev/null
+++ b/.sqlx/query-c4945dec390eede39113f1c677cfd8a97272e7db948e506ed1c93505ec221f2f.json
@@ -0,0 +1,58 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT draft, assignees, labels, requested_reviewer_github_user_ids, participant_github_user_ids, reviews, review_decision FROM github_pull_request WHERE github_key = $1",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "draft",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 1,
+ "name": "assignees",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 2,
+ "name": "labels",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 3,
+ "name": "requested_reviewer_github_user_ids",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 4,
+ "name": "participant_github_user_ids",
+ "type_info": "TextArray"
+ },
+ {
+ "ordinal": 5,
+ "name": "reviews",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 6,
+ "name": "review_decision",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "c4945dec390eede39113f1c677cfd8a97272e7db948e506ed1c93505ec221f2f"
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts
index 9d2d206f93..8313a49296 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts
@@ -5,14 +5,17 @@
* OpenAPI spec version: 0.1.0
*/
import type { EnrichedGithubPullRequestAdditions } from './enrichedGithubPullRequestAdditions';
+import type { EnrichedGithubPullRequestAssignees } from './enrichedGithubPullRequestAssignees';
import type { EnrichedGithubPullRequestAuthorId } from './enrichedGithubPullRequestAuthorId';
import type { EnrichedGithubPullRequestAuthorLogin } from './enrichedGithubPullRequestAuthorLogin';
import type { EnrichedGithubPullRequestChecks } from './enrichedGithubPullRequestChecks';
import type { EnrichedGithubPullRequestComments } from './enrichedGithubPullRequestComments';
import type { EnrichedGithubPullRequestDeletions } from './enrichedGithubPullRequestDeletions';
import type { EnrichedGithubPullRequestDescription } from './enrichedGithubPullRequestDescription';
+import type { EnrichedGithubPullRequestLabels } from './enrichedGithubPullRequestLabels';
import type { EnrichedGithubPullRequestName } from './enrichedGithubPullRequestName';
import type { EnrichedGithubPullRequestParticipantGithubUserIds } from './enrichedGithubPullRequestParticipantGithubUserIds';
+import type { EnrichedGithubPullRequestReviews } from './enrichedGithubPullRequestReviews';
import type { EnrichedGithubPullRequestStatus } from './enrichedGithubPullRequestStatus';
/**
@@ -24,6 +27,8 @@ export interface EnrichedGithubPullRequest {
* @minimum 0
*/
additions?: EnrichedGithubPullRequestAdditions;
+ /** The users assigned to the pull request, when known. */
+ assignees?: EnrichedGithubPullRequestAssignees;
/**
* The stable numeric GitHub user id for the pull request author, when available.
* @minimum 0
@@ -46,6 +51,8 @@ export interface EnrichedGithubPullRequest {
displayName: string;
/** The stored GitHub association key, in `owner/repo/pull/number` format. */
githubKey: string;
+ /** The pull request's labels, when known. */
+ labels?: EnrichedGithubPullRequestLabels;
/** The GitHub pull request title, when enrichment succeeds. */
name?: EnrichedGithubPullRequestName;
/**
@@ -61,6 +68,9 @@ union rather than replacing it (partial write paths must not drop known particip
participantGithubUserIds?: EnrichedGithubPullRequestParticipantGithubUserIds;
/** The GitHub repository name. */
repo: string;
+ /** Each reviewer's latest submitted review, when known. Stored metadata merges this per
+reviewer, so a write that knows one review keeps the others. */
+ reviews?: EnrichedGithubPullRequestReviews;
status?: EnrichedGithubPullRequestStatus;
/** The public GitHub URL for the pull request. */
url: string;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestAssignees.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestAssignees.ts
new file mode 100644
index 0000000000..0fa55e17eb
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestAssignees.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestUser } from './githubPullRequestUser';
+
+/**
+ * The users assigned to the pull request, when known.
+ */
+export type EnrichedGithubPullRequestAssignees = GithubPullRequestUser[] | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestLabels.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestLabels.ts
new file mode 100644
index 0000000000..9ce3219370
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestLabels.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestLabel } from './githubPullRequestLabel';
+
+/**
+ * The pull request's labels, when known.
+ */
+export type EnrichedGithubPullRequestLabels = GithubPullRequestLabel[] | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestReviews.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestReviews.ts
new file mode 100644
index 0000000000..4ab6967dfe
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestReviews.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestReview } from './githubPullRequestReview';
+
+/**
+ * Each reviewer's latest submitted review, when known. Stored metadata merges this per
+reviewer, so a write that knows one review keeps the others.
+ */
+export type EnrichedGithubPullRequestReviews = GithubPullRequestReview[] | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestLabel.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestLabel.ts
new file mode 100644
index 0000000000..cefb914ed3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestLabel.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestLabelColor } from './githubPullRequestLabelColor';
+
+/**
+ * A label on a GitHub pull request.
+ */
+export interface GithubPullRequestLabel {
+ /** The label color as six hex digits without a leading `#`, when known. */
+ color?: GithubPullRequestLabelColor;
+ /** The label name, unique within its repository regardless of case. */
+ name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestLabelColor.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestLabelColor.ts
new file mode 100644
index 0000000000..8170318564
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestLabelColor.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The label color as six hex digits without a leading `#`, when known.
+ */
+export type GithubPullRequestLabelColor = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReview.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReview.ts
new file mode 100644
index 0000000000..60bde39d94
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReview.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestReviewReviewerLogin } from './githubPullRequestReviewReviewerLogin';
+import type { GithubPullRequestReviewState } from './githubPullRequestReviewState';
+import type { GithubPullRequestReviewSubmittedAt } from './githubPullRequestReviewSubmittedAt';
+
+/**
+ * A reviewer's latest submitted review on a pull request.
+ */
+export interface GithubPullRequestReview {
+ /** The stable numeric GitHub user id of the reviewer, as a string. */
+ reviewerGithubUserId: string;
+ /** The reviewer's GitHub login, when known. */
+ reviewerLogin?: GithubPullRequestReviewReviewerLogin;
+ /** What the review said. */
+ state: GithubPullRequestReviewState;
+ /** When the review was submitted, when known. */
+ submittedAt?: GithubPullRequestReviewSubmittedAt;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewReviewerLogin.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewReviewerLogin.ts
new file mode 100644
index 0000000000..8507d6336e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewReviewerLogin.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The reviewer's GitHub login, when known.
+ */
+export type GithubPullRequestReviewReviewerLogin = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewState.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewState.ts
new file mode 100644
index 0000000000..84b4dbd7f6
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewState.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * What a reviewer's latest review on a pull request said.
+ */
+export type GithubPullRequestReviewState =
+ (typeof GithubPullRequestReviewState)[keyof typeof GithubPullRequestReviewState];
+
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+export const GithubPullRequestReviewState = {
+ approved: 'approved',
+ changes_requested: 'changes_requested',
+ commented: 'commented',
+ dismissed: 'dismissed',
+} as const;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewSubmittedAt.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewSubmittedAt.ts
new file mode 100644
index 0000000000..d7b350135e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestReviewSubmittedAt.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * When the review was submitted, when known.
+ */
+export type GithubPullRequestReviewSubmittedAt = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestUser.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestUser.ts
new file mode 100644
index 0000000000..ff1d949d13
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestUser.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { GithubPullRequestUserLogin } from './githubPullRequestUserLogin';
+
+/**
+ * A GitHub user named on a pull request, such as an assignee.
+ */
+export interface GithubPullRequestUser {
+ /** The stable numeric GitHub user id, as a string. */
+ githubUserId: string;
+ /** The user's GitHub login, when known. */
+ login?: GithubPullRequestUserLogin;
+}
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestUserLogin.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestUserLogin.ts
new file mode 100644
index 0000000000..9282c69095
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/githubPullRequestUserLogin.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The user's GitHub login, when known.
+ */
+export type GithubPullRequestUserLogin = string | null;
diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
index 93995c0342..fb54e45c72 100644
--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts
@@ -47,14 +47,17 @@ export * from './denyReason';
export * from './emptyResponse';
export * from './enrichedGithubPullRequest';
export * from './enrichedGithubPullRequestAdditions';
+export * from './enrichedGithubPullRequestAssignees';
export * from './enrichedGithubPullRequestAuthorId';
export * from './enrichedGithubPullRequestAuthorLogin';
export * from './enrichedGithubPullRequestChecks';
export * from './enrichedGithubPullRequestComments';
export * from './enrichedGithubPullRequestDeletions';
export * from './enrichedGithubPullRequestDescription';
+export * from './enrichedGithubPullRequestLabels';
export * from './enrichedGithubPullRequestName';
export * from './enrichedGithubPullRequestParticipantGithubUserIds';
+export * from './enrichedGithubPullRequestReviews';
export * from './enrichedGithubPullRequestStatus';
export * from './enrichGithubPullRequestsProxyRequest';
export * from './enrichGithubPullRequestsResponse';
@@ -88,8 +91,16 @@ export * from './githubPullRequestCommentPath';
export * from './githubPullRequestCommentPullRequestReviewId';
export * from './githubPullRequestCommentUpdatedAt';
export * from './githubPullRequestCommentUrl';
+export * from './githubPullRequestLabel';
+export * from './githubPullRequestLabelColor';
export * from './githubPullRequestRef';
+export * from './githubPullRequestReview';
+export * from './githubPullRequestReviewReviewerLogin';
+export * from './githubPullRequestReviewState';
+export * from './githubPullRequestReviewSubmittedAt';
export * from './githubPullRequestStatus';
+export * from './githubPullRequestUser';
+export * from './githubPullRequestUserLogin';
export * from './gmailLinkStatusResponse';
export * from './gtmInviteLink';
export * from './gtmInviteLinkConvertedAt';
diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.json
index 88b7cb59fe..236ff61c0c 100644
--- a/apps/web/src/lib/service-clients/service-auth/openapi.json
+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json
@@ -5171,6 +5171,13 @@
"description": "The number of added lines reported by GitHub, when enrichment succeeds.",
"minimum": 0
},
+ "assignees": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestUser"
+ },
+ "description": "The users assigned to the pull request, when known."
+ },
"authorId": {
"type": ["integer", "null"],
"format": "int64",
@@ -5213,6 +5220,13 @@
"type": "string",
"description": "The stored GitHub association key, in `owner/repo/pull/number` format."
},
+ "labels": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestLabel"
+ },
+ "description": "The pull request's labels, when known."
+ },
"name": {
"type": ["string", "null"],
"description": "The GitHub pull request title, when enrichment succeeds."
@@ -5238,6 +5252,13 @@
"type": "string",
"description": "The GitHub repository name."
},
+ "reviews": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestReview"
+ },
+ "description": "Each reviewer's latest submitted review, when known. Stored metadata merges this per\nreviewer, so a write that knows one review keeps the others."
+ },
"status": {
"oneOf": [
{
@@ -5545,6 +5566,21 @@
}
}
},
+ "GithubPullRequestLabel": {
+ "type": "object",
+ "description": "A label on a GitHub pull request.",
+ "required": ["name"],
+ "properties": {
+ "color": {
+ "type": ["string", "null"],
+ "description": "The label color as six hex digits without a leading `#`, when known."
+ },
+ "name": {
+ "type": "string",
+ "description": "The label name, unique within its repository regardless of case."
+ }
+ }
+ },
"GithubPullRequestRef": {
"type": "object",
"description": "A pull request reference that can be enriched with live GitHub data.",
@@ -5585,11 +5621,55 @@
}
}
},
+ "GithubPullRequestReview": {
+ "type": "object",
+ "description": "A reviewer's latest submitted review on a pull request.",
+ "required": ["reviewerGithubUserId", "state"],
+ "properties": {
+ "reviewerGithubUserId": {
+ "type": "string",
+ "description": "The stable numeric GitHub user id of the reviewer, as a string."
+ },
+ "reviewerLogin": {
+ "type": ["string", "null"],
+ "description": "The reviewer's GitHub login, when known."
+ },
+ "state": {
+ "$ref": "#/components/schemas/GithubPullRequestReviewState",
+ "description": "What the review said."
+ },
+ "submittedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the review was submitted, when known."
+ }
+ }
+ },
+ "GithubPullRequestReviewState": {
+ "type": "string",
+ "description": "What a reviewer's latest review on a pull request said.",
+ "enum": ["approved", "changes_requested", "commented", "dismissed"]
+ },
"GithubPullRequestStatus": {
"type": "string",
"description": "The normalized lifecycle status for a GitHub pull request.",
"enum": ["open", "closed", "merged"]
},
+ "GithubPullRequestUser": {
+ "type": "object",
+ "description": "A GitHub user named on a pull request, such as an assignee.",
+ "required": ["githubUserId"],
+ "properties": {
+ "githubUserId": {
+ "type": "string",
+ "description": "The stable numeric GitHub user id, as a string."
+ },
+ "login": {
+ "type": ["string", "null"],
+ "description": "The user's GitHub login, when known."
+ }
+ }
+ },
"GmailLinkStatusResponse": {
"type": "object",
"required": ["reauthentication_required"],
diff --git a/crates/github/src/domain/models.rs b/crates/github/src/domain/models.rs
index 1a97dae2bd..60e04aa9f1 100644
--- a/crates/github/src/domain/models.rs
+++ b/crates/github/src/domain/models.rs
@@ -18,7 +18,8 @@ pub use github_pull_requests::domain::models::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubKey,
GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestDetails,
- GithubPullRequestRef, GithubPullRequestStatus,
+ GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview,
+ GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, latest_reviews,
};
pub use installation_state::{
InstallationState, InstallationStateError, sign_installation_state, verify_installation_state,
diff --git a/crates/github/src/domain/service/link_test.rs b/crates/github/src/domain/service/link_test.rs
index f51e1ab4a9..c3fdd55558 100644
--- a/crates/github/src/domain/service/link_test.rs
+++ b/crates/github/src/domain/service/link_test.rs
@@ -10,7 +10,7 @@ use foreign_entity::domain::{
ports::{ForeignEntityListQuery, ForeignEntityService},
};
use github_pull_requests::domain::{
- models::GithubPullRequestRow, ports::GithubPullRequestRepository,
+ models::GithubPullRequestWrite, ports::GithubPullRequestRepository,
service::GithubPullRequestServiceImpl,
};
use macro_user_id::{
@@ -227,6 +227,9 @@ fn default_pull_request_details() -> GithubPullRequestDetails {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
}
}
@@ -621,7 +624,7 @@ impl GithubPullRequestRepository for NoPullRequestRows {
Ok(None)
}
- async fn upsert_row(&self, _row: &GithubPullRequestRow) -> Result<(), Self::Err> {
+ async fn upsert_row(&self, _row: &GithubPullRequestWrite) -> Result<(), Self::Err> {
Ok(())
}
diff --git a/crates/github/src/domain/service/sync.rs b/crates/github/src/domain/service/sync.rs
index b355400e1c..6e925b9688 100644
--- a/crates/github/src/domain/service/sync.rs
+++ b/crates/github/src/domain/service/sync.rs
@@ -15,9 +15,11 @@ use crate::domain::{
models::{
EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,
GithubInstallationAccessToken, GithubInstallationSetupAction, GithubKey,
- GithubPullRequestDetails, GithubPullRequestStatus, GithubWebhookEventType,
- InstallationState, MacroTaskId, ResolvedTeamTaskReference, TeamTaskReference,
- ValidatedGithubWebhookEvent, sign_installation_state, verify_installation_state,
+ GithubPullRequestDetails, GithubPullRequestLabel, GithubPullRequestReview,
+ GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser,
+ GithubWebhookEventType, InstallationState, MacroTaskId, ResolvedTeamTaskReference,
+ TeamTaskReference, ValidatedGithubWebhookEvent, latest_reviews, sign_installation_state,
+ verify_installation_state,
},
ports::{GithubSyncClient, GithubSyncRealtime, GithubSyncRepo, GithubSyncService},
};
@@ -283,6 +285,52 @@ impl<
.and_then(|value| value.as_str())
.and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
.map(|updated_at| updated_at.with_timezone(&chrono::Utc)),
+ assignees: pull_request
+ .and_then(|pr| pr.get("assignees"))
+ .and_then(|value| value.as_array())
+ .map(|users| users.iter().filter_map(Self::user_from_payload).collect()),
+ labels: pull_request
+ .and_then(|pr| pr.get("labels"))
+ .and_then(|value| value.as_array())
+ .map(|labels| labels.iter().filter_map(Self::label_from_payload).collect()),
+ reviews: Self::review_from_payload(event.payload.get("review"))
+ .map(|review| vec![review]),
+ })
+ }
+
+ fn user_from_payload(user: &serde_json::Value) -> Option<GithubPullRequestUser> {
+ Some(GithubPullRequestUser {
+ github_user_id: user.get("id")?.as_u64()?.to_string(),
+ login: user
+ .get("login")
+ .and_then(|value| value.as_str())
+ .map(str::to_string),
+ })
+ }
+
+ fn label_from_payload(label: &serde_json::Value) -> Option<GithubPullRequestLabel> {
+ Some(GithubPullRequestLabel {
+ name: label.get("name")?.as_str()?.to_string(),
+ color: label
+ .get("color")
+ .and_then(|value| value.as_str())
+ .map(str::to_string),
+ })
+ }
+
+ /// The review a `pull_request_review` event carries, as its reviewer's state.
+ fn review_from_payload(review: Option<&serde_json::Value>) -> Option<GithubPullRequestReview> {
+ let review = review?;
+ let reviewer = Self::user_from_payload(review.get("user")?)?;
+ Some(GithubPullRequestReview {
+ reviewer_github_user_id: reviewer.github_user_id,
+ reviewer_login: reviewer.login,
+ state: GithubPullRequestReviewState::from_github(review.get("state")?.as_str()?)?,
+ submitted_at: review
+ .get("submitted_at")
+ .and_then(|value| value.as_str())
+ .and_then(|value| chrono::DateTime::parse_from_rfc3339(value).ok())
+ .map(|submitted_at| submitted_at.with_timezone(&chrono::Utc)),
})
}
@@ -392,6 +440,17 @@ impl<
.requested_reviewer_github_user_ids
.or(fallback.requested_reviewer_github_user_ids),
github_updated_at: details.github_updated_at.or(fallback.github_updated_at),
+ assignees: details.assignees.or(fallback.assignees),
+ labels: details.labels.or(fallback.labels),
+ reviews: match (details.reviews, fallback.reviews) {
+ (None, None) => None,
+ (details, fallback) => Some(latest_reviews(
+ details
+ .into_iter()
+ .flatten()
+ .chain(fallback.into_iter().flatten()),
+ )),
+ },
}
}
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index c4fd19e1c0..2227ecfab0 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -34,7 +34,7 @@ use foreign_entity::domain::{
ports::{ForeignEntityListQuery, ForeignEntityService},
};
use github_pull_requests::domain::{
- models::GithubPullRequestRow, ports::GithubPullRequestRepository,
+ models::GithubPullRequestWrite, ports::GithubPullRequestRepository,
service::GithubPullRequestServiceImpl,
};
use macro_user_id::user_id::MacroUserIdStr;
@@ -1223,7 +1223,7 @@ impl GithubPullRequestRepository for NoPullRequestRows {
Ok(None)
}
- async fn upsert_row(&self, _row: &GithubPullRequestRow) -> Result<(), Self::Err> {
+ async fn upsert_row(&self, _row: &GithubPullRequestWrite) -> Result<(), Self::Err> {
Ok(())
}
@@ -1349,6 +1349,9 @@ fn expected_pull_request_metadata(
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
})
.unwrap()
}
@@ -1530,6 +1533,9 @@ fn backfilled_pull_request(title: &str) -> EnrichedGithubPullRequest {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
}
}
@@ -1557,6 +1563,9 @@ fn expected_pull_request_metadata_from_details(
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
})
.unwrap()
}
@@ -1617,6 +1626,9 @@ fn pull_request_details(
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
}
}
diff --git a/crates/github/src/outbound/pull_request_metadata.rs b/crates/github/src/outbound/pull_request_metadata.rs
index f87c50df84..57236e90df 100644
--- a/crates/github/src/outbound/pull_request_metadata.rs
+++ b/crates/github/src/outbound/pull_request_metadata.rs
@@ -9,7 +9,9 @@ use serde::de::DeserializeOwned;
use crate::domain::models::{
EnrichedGithubPullRequest, GithubKey, GithubPullRequestCheckRun, GithubPullRequestComment,
- GithubPullRequestDetails, GithubPullRequestStatus, GithubRepository,
+ GithubPullRequestDetails, GithubPullRequestLabel, GithubPullRequestReview,
+ GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GithubRepository,
+ latest_reviews,
};
const GITHUB_API_BASE_URL: &str = "https://api.github.com";
@@ -37,10 +39,13 @@ pub(crate) async fn fetch_pull_request_metadata(
.await;
let mut participant_ids = pull_request.participant_ids();
- let comments = discussion.map(|discussion| {
- participant_ids.extend(discussion.participant_ids);
- discussion.comments
- });
+ let (comments, reviews) = match discussion {
+ Some(discussion) => {
+ participant_ids.extend(discussion.participant_ids);
+ (Some(discussion.comments), Some(discussion.reviews))
+ }
+ None => (None, None),
+ };
// A failed comments fetch still yields the partial author/reviewer/assignee set; stored
// metadata merges participants as a union, so partial sets are safe.
let participant_github_user_ids =
@@ -68,6 +73,9 @@ pub(crate) async fn fetch_pull_request_metadata(
draft: pull_request.draft,
requested_reviewer_github_user_ids: Some(requested_reviewer_github_user_ids),
github_updated_at: pull_request.updated_at,
+ assignees: Some(pull_request_users(&pull_request.assignees)),
+ labels: Some(pull_request_labels(&pull_request.labels)),
+ reviews,
})
}
@@ -201,6 +209,8 @@ struct GithubOpenPullRequestResponse {
requested_reviewers: Vec<GithubUserResponse>,
#[serde(default)]
assignees: Vec<GithubUserResponse>,
+ #[serde(default)]
+ labels: Vec<GithubLabelResponse>,
}
#[derive(Debug, serde::Deserialize)]
@@ -223,6 +233,8 @@ struct GithubPullRequestResponse {
requested_reviewers: Vec<GithubUserResponse>,
#[serde(default)]
assignees: Vec<GithubUserResponse>,
+ #[serde(default)]
+ labels: Vec<GithubLabelResponse>,
}
impl GithubPullRequestResponse {
@@ -270,6 +282,35 @@ struct GithubRepositoryIdResponse {
id: u64,
}
+/// The users that have a stable numeric id, with their logins.
+fn pull_request_users(users: &[GithubUserResponse]) -> Vec<GithubPullRequestUser> {
+ users
+ .iter()
+ .filter_map(|user| {
+ Some(GithubPullRequestUser {
+ github_user_id: user.id?.to_string(),
+ login: user.login.clone(),
+ })
+ })
+ .collect()
+}
+
+fn pull_request_labels(labels: &[GithubLabelResponse]) -> Vec<GithubPullRequestLabel> {
+ labels
+ .iter()
+ .map(|label| GithubPullRequestLabel {
+ name: label.name.clone(),
+ color: label.color.clone(),
+ })
+ .collect()
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct GithubLabelResponse {
+ name: String,
+ color: Option<String>,
+}
+
/// The stable numeric ids, as strings, of the users that have one.
fn user_ids(users: &[GithubUserResponse]) -> Vec<String> {
users
@@ -307,6 +348,7 @@ struct GithubCommentResponse {
struct GithubReviewResponse {
id: u64,
body: Option<String>,
+ state: Option<String>,
user: Option<GithubUserResponse>,
author_association: Option<String>,
html_url: Option<String>,
@@ -364,6 +406,8 @@ async fn fetch_pull_request(
struct FetchedDiscussion {
comments: Vec<GithubPullRequestComment>,
participant_ids: BTreeSet<u64>,
+ /// Each reviewer's latest submitted review. Only the reviews fetch fills it.
+ reviews: Vec<GithubPullRequestReview>,
}
async fn fetch_comments(
@@ -384,6 +428,7 @@ async fn fetch_comments(
let reviews = fetch_reviews(client, access_token, owner, repo, number).await?;
discussion.comments.extend(reviews.comments);
discussion.participant_ids.extend(reviews.participant_ids);
+ discussion.reviews = reviews.reviews;
Some(discussion)
}
@@ -410,6 +455,7 @@ async fn fetch_issue_comments(
{
Ok(comments) => Some(FetchedDiscussion {
participant_ids: author_ids(&comments, |comment| comment.user.as_ref()),
+ reviews: Vec::new(),
comments: comments
.into_iter()
.map(|comment| comment.into_pull_request_comment("issue_comment"))
@@ -450,6 +496,7 @@ async fn fetch_review_comments(
{
Ok(comments) => Some(FetchedDiscussion {
participant_ids: author_ids(&comments, |comment| comment.user.as_ref()),
+ reviews: Vec::new(),
comments: comments
.into_iter()
.map(|comment| comment.into_pull_request_comment("review_comment"))
@@ -492,6 +539,7 @@ async fn fetch_reviews(
// from the comment list but their reviewers still count as participants.
Ok(reviews) => Some(FetchedDiscussion {
participant_ids: author_ids(&reviews, |review| review.user.as_ref()),
+ reviews: latest_reviews(reviews.iter().filter_map(GithubReviewResponse::review)),
comments: reviews
.into_iter()
.filter_map(GithubReviewResponse::into_pull_request_comment)
@@ -659,6 +707,9 @@ impl GithubOpenPullRequestResponse {
draft: self.draft,
requested_reviewer_github_user_ids: Some(user_ids(&self.requested_reviewers)),
github_updated_at: self.updated_at,
+ assignees: Some(pull_request_users(&self.assignees)),
+ labels: Some(pull_request_labels(&self.labels)),
+ reviews: None,
}
}
}
@@ -685,6 +736,17 @@ impl GithubCommentResponse {
}
impl GithubReviewResponse {
+ /// The review as its reviewer's state, when it was submitted by a user with an id.
+ fn review(&self) -> Option<GithubPullRequestReview> {
+ let user = self.user.as_ref()?;
+ Some(GithubPullRequestReview {
+ reviewer_github_user_id: user.id?.to_string(),
+ reviewer_login: user.login.clone(),
+ state: GithubPullRequestReviewState::from_github(self.state.as_deref()?)?,
+ submitted_at: self.submitted_at,
+ })
+ }
+
fn into_pull_request_comment(self) -> Option<GithubPullRequestComment> {
let body = self.body.unwrap_or_default();
diff --git a/crates/github_pull_requests/src/domain/models.rs b/crates/github_pull_requests/src/domain/models.rs
index 987bff635d..01b5afafe6 100644
--- a/crates/github_pull_requests/src/domain/models.rs
+++ b/crates/github_pull_requests/src/domain/models.rs
@@ -14,7 +14,9 @@ pub use pull_request::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestDetails,
- GithubPullRequestRef, GithubPullRequestStatus,
+ GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview,
+ GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestStatus,
+ GithubPullRequestUser, latest_reviews,
};
/// A pull request's latest data, for the record stored for one source.
@@ -78,6 +80,14 @@ pub struct GithubPullRequestRow {
pub participant_github_user_ids: Vec<String>,
/// When GitHub last updated the pull request.
pub github_updated_at: Option<DateTime<Utc>>,
+ /// The users assigned to the pull request.
+ pub assignees: Vec<GithubPullRequestUser>,
+ /// The pull request's labels.
+ pub labels: Vec<GithubPullRequestLabel>,
+ /// Each reviewer's latest submitted review.
+ pub reviews: Vec<GithubPullRequestReview>,
+ /// Where the review stands, derived from `reviews` and the outstanding review requests.
+ pub review_decision: Option<GithubPullRequestReviewDecision>,
}
impl GithubPullRequestRow {
@@ -100,15 +110,202 @@ impl GithubPullRequestRow {
draft: pull_request.draft.unwrap_or(false),
author_github_user_id: pull_request.author_id.map(|id| id.to_string()),
author_login: pull_request.author_login,
- requested_reviewer_github_user_ids: pull_request
- .requested_reviewer_github_user_ids
- .unwrap_or_default(),
participant_github_user_ids: pull_request
.participant_github_user_ids
.unwrap_or_default(),
github_updated_at: pull_request.github_updated_at,
+ assignees: pull_request.assignees.unwrap_or_default(),
+ labels: pull_request.labels.unwrap_or_default(),
+ review_decision: GithubPullRequestReviewDecision::derive(
+ pull_request.reviews.as_deref().unwrap_or_default(),
+ pull_request
+ .requested_reviewer_github_user_ids
+ .as_deref()
+ .unwrap_or_default(),
+ ),
+ reviews: pull_request.reviews.unwrap_or_default(),
+ requested_reviewer_github_user_ids: pull_request
+ .requested_reviewer_github_user_ids
+ .unwrap_or_default(),
+ })
+ }
+}
+
+/// Sparse typed-column update. `None` means the source did not supply that field.
+#[derive(Debug, Clone, PartialEq)]
+pub struct GithubPullRequestWrite {
+ /// Source-derived row used only when the shared typed row is missing.
+ pub initial_row: Option<GithubPullRequestRow>,
+ /// The association key.
+ pub github_key: String,
+ /// Numeric repository id, if supplied.
+ pub repository_id: Option<i64>,
+ /// Pull request number.
+ pub number: i64,
+ /// Repository owner.
+ pub owner: String,
+ /// Repository name.
+ pub repo: String,
+ /// Title, if supplied.
+ pub title: Option<String>,
+ /// Status, if supplied.
+ pub status: Option<GithubPullRequestStatus>,
+ /// Draft flag, if supplied.
+ pub draft: Option<bool>,
+ /// Author id, if supplied.
+ pub author_github_user_id: Option<String>,
+ /// Author login, if supplied.
+ pub author_login: Option<String>,
+ /// Review requests, if supplied.
+ pub requested_reviewer_github_user_ids: Option<Vec<String>>,
+ /// Participants, if supplied.
+ pub participant_github_user_ids: Option<Vec<String>>,
+ /// GitHub update time, if supplied.
+ pub github_updated_at: Option<DateTime<Utc>>,
+ /// Assignees, if supplied.
+ pub assignees: Option<Vec<GithubPullRequestUser>>,
+ /// Labels, if supplied.
+ pub labels: Option<Vec<GithubPullRequestLabel>>,
+ /// Reviews, if supplied.
+ pub reviews: Option<Vec<GithubPullRequestReview>>,
+}
+
+impl GithubPullRequestWrite {
+ /// Read a sparse update from record metadata.
+ pub fn from_metadata(metadata: &serde_json::Value) -> Option<Self> {
+ let pull_request: EnrichedGithubPullRequest =
+ serde_json::from_value(metadata.clone()).ok()?;
+ Self::from_enriched(&pull_request)
+ }
+
+ /// Retain which fields enrichment supplied, rather than projecting a complete row.
+ pub fn from_enriched(pull_request: &EnrichedGithubPullRequest) -> Option<Self> {
+ Some(Self {
+ initial_row: None,
+ github_key: pull_request.github_key.clone(),
+ repository_id: pull_request
+ .repository_id
+ .and_then(|id| i64::try_from(id).ok()),
+ number: i64::try_from(pull_request.number).ok()?,
+ owner: pull_request.owner.clone(),
+ repo: pull_request.repo.clone(),
+ title: pull_request.name.clone(),
+ status: pull_request.status,
+ draft: pull_request.draft,
+ author_github_user_id: pull_request.author_id.map(|id| id.to_string()),
+ author_login: pull_request.author_login.clone(),
+ requested_reviewer_github_user_ids: pull_request
+ .requested_reviewer_github_user_ids
+ .clone(),
+ participant_github_user_ids: pull_request.participant_github_user_ids.clone(),
+ github_updated_at: pull_request.github_updated_at,
+ assignees: pull_request.assignees.clone(),
+ labels: pull_request.labels.clone(),
+ reviews: pull_request.reviews.clone(),
})
}
+
+ /// Merge into a complete row. Supplied collections replace assignees, labels and requests;
+ /// participants accumulate, and reviews retain each reviewer's latest decision.
+ pub fn merge(&self, existing: Option<GithubPullRequestRow>) -> GithubPullRequestRow {
+ let mut row = existing
+ .or_else(|| {
+ self.initial_row
+ .as_ref()
+ .filter(|row| row.github_key == self.github_key && row.number == self.number)
+ .cloned()
+ })
+ .unwrap_or_else(|| GithubPullRequestRow {
+ github_key: self.github_key.clone(),
+ repository_id: None,
+ number: self.number,
+ owner: self.owner.clone(),
+ repo: self.repo.clone(),
+ title: None,
+ status: None,
+ draft: false,
+ author_github_user_id: None,
+ author_login: None,
+ requested_reviewer_github_user_ids: Vec::new(),
+ participant_github_user_ids: Vec::new(),
+ github_updated_at: None,
+ assignees: Vec::new(),
+ labels: Vec::new(),
+ reviews: Vec::new(),
+ review_decision: None,
+ });
+ row.repository_id = self.repository_id.or(row.repository_id);
+ row.number = self.number;
+ row.owner = self.owner.clone();
+ row.repo = self.repo.clone();
+ row.title = self.title.clone().or(row.title);
+ row.status = self.status.or(row.status);
+ row.draft = self.draft.unwrap_or(row.draft);
+ row.author_github_user_id = self
+ .author_github_user_id
+ .clone()
+ .or(row.author_github_user_id);
+ row.author_login = self.author_login.clone().or(row.author_login);
+ row.github_updated_at = self.github_updated_at.or(row.github_updated_at);
+ if let Some(requests) = &self.requested_reviewer_github_user_ids {
+ row.requested_reviewer_github_user_ids = requests.clone();
+ }
+ if let Some(assignees) = &self.assignees {
+ row.assignees = assignees.clone();
+ }
+ if let Some(labels) = &self.labels {
+ row.labels = labels.clone();
+ }
+ row.participant_github_user_ids = row
+ .participant_github_user_ids
+ .into_iter()
+ .chain(self.participant_github_user_ids.clone().unwrap_or_default())
+ .collect::<std::collections::BTreeSet<_>>()
+ .into_iter()
+ .collect();
+ row.reviews = latest_reviews(
+ row.reviews
+ .into_iter()
+ .chain(self.reviews.clone().unwrap_or_default()),
+ );
+ row.review_decision = GithubPullRequestReviewDecision::derive(
+ &row.reviews,
+ &row.requested_reviewer_github_user_ids,
+ );
+ row
+ }
+}
+
+impl From<&GithubPullRequestRow> for GithubPullRequestWrite {
+ fn from(row: &GithubPullRequestRow) -> Self {
+ Self {
+ initial_row: None,
+ github_key: row.github_key.clone(),
+ repository_id: row.repository_id,
+ number: row.number,
+ owner: row.owner.clone(),
+ repo: row.repo.clone(),
+ title: row.title.clone(),
+ status: row.status,
+ draft: Some(row.draft),
+ author_github_user_id: row.author_github_user_id.clone(),
+ author_login: row.author_login.clone(),
+ requested_reviewer_github_user_ids: Some(
+ row.requested_reviewer_github_user_ids.clone(),
+ ),
+ participant_github_user_ids: Some(row.participant_github_user_ids.clone()),
+ github_updated_at: row.github_updated_at,
+ assignees: Some(row.assignees.clone()),
+ labels: Some(row.labels.clone()),
+ reviews: Some(row.reviews.clone()),
+ }
+ }
+}
+
+impl From<GithubPullRequestRow> for GithubPullRequestWrite {
+ fn from(row: GithubPullRequestRow) -> Self {
+ Self::from(&row)
+ }
}
/// Repositories and authors among the GitHub pull requests a caller can see, each with the
diff --git a/crates/github_pull_requests/src/domain/models/pull_request.rs b/crates/github_pull_requests/src/domain/models/pull_request.rs
index 06ddd2af7a..64e2faf04c 100644
--- a/crates/github_pull_requests/src/domain/models/pull_request.rs
+++ b/crates/github_pull_requests/src/domain/models/pull_request.rs
@@ -156,6 +156,151 @@ pub struct GithubPullRequestCheckRun {
pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
}
+/// A GitHub user named on a pull request, such as an assignee.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestUser {
+ /// The stable numeric GitHub user id, as a string.
+ pub github_user_id: String,
+ /// The user's GitHub login, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub login: Option<String>,
+}
+
+/// A label on a GitHub pull request.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestLabel {
+ /// The label name, unique within its repository regardless of case.
+ pub name: String,
+ /// The label color as six hex digits without a leading `#`, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub color: Option<String>,
+}
+
+/// What a reviewer's latest review on a pull request said.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum GithubPullRequestReviewState {
+ /// The reviewer approved the changes.
+ Approved,
+ /// The reviewer asked for changes.
+ ChangesRequested,
+ /// The reviewer commented without approving or asking for changes.
+ Commented,
+ /// The reviewer's review was dismissed.
+ Dismissed,
+}
+
+impl GithubPullRequestReviewState {
+ /// The state GitHub reports for a submitted review, such as `APPROVED`. `None` for a pending
+ /// review, which only its author can see.
+ pub fn from_github(state: &str) -> Option<Self> {
+ match state.to_ascii_uppercase().as_str() {
+ "APPROVED" => Some(Self::Approved),
+ "CHANGES_REQUESTED" => Some(Self::ChangesRequested),
+ "COMMENTED" => Some(Self::Commented),
+ "DISMISSED" => Some(Self::Dismissed),
+ _ => None,
+ }
+ }
+}
+
+/// A reviewer's latest submitted review on a pull request.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "camelCase")]
+pub struct GithubPullRequestReview {
+ /// The stable numeric GitHub user id of the reviewer, as a string.
+ pub reviewer_github_user_id: String,
+ /// The reviewer's GitHub login, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reviewer_login: Option<String>,
+ /// What the review said.
+ pub state: GithubPullRequestReviewState,
+ /// When the review was submitted, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub submitted_at: Option<chrono::DateTime<chrono::Utc>>,
+}
+
+impl GithubPullRequestReview {
+ /// Whether this review replaces `current` as its reviewer's latest. An approval, change
+ /// request, or dismissal always outranks a comment, regardless of input order or submission
+ /// time. Otherwise the later submission wins, a review with no submission time loses to one
+ /// with a time, and a tie goes to this review.
+ fn supersedes(&self, current: &Self) -> bool {
+ match (
+ self.state == GithubPullRequestReviewState::Commented,
+ current.state == GithubPullRequestReviewState::Commented,
+ ) {
+ (true, false) => false,
+ (false, true) => true,
+ _ => self.submitted_at >= current.submitted_at,
+ }
+ }
+}
+
+/// Each reviewer's latest review among `reviews`, taken in order, ordered by reviewer id.
+pub fn latest_reviews(
+ reviews: impl IntoIterator<Item = GithubPullRequestReview>,
+) -> Vec<GithubPullRequestReview> {
+ let mut latest: std::collections::BTreeMap<String, GithubPullRequestReview> =
+ std::collections::BTreeMap::new();
+ for review in reviews {
+ let replaces = latest
+ .get(&review.reviewer_github_user_id)
+ .is_none_or(|current| review.supersedes(current));
+ if replaces {
+ latest.insert(review.reviewer_github_user_id.clone(), review);
+ }
+ }
+ latest.into_values().collect()
+}
+
+/// Where a pull request's review stands, from its reviewers' latest reviews.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+#[serde(rename_all = "snake_case")]
+pub enum GithubPullRequestReviewDecision {
+ /// A reviewer's latest review approves and none asks for changes.
+ Approved,
+ /// A reviewer's latest review asks for changes.
+ ChangesRequested,
+ /// Reviews are requested and none has approved or asked for changes yet.
+ ReviewRequired,
+}
+
+impl GithubPullRequestReviewDecision {
+ /// Derive the decision from each reviewer's latest review and the outstanding review
+ /// requests. Unlike GitHub's own decision it does not know how many approvals branch
+ /// protection requires.
+ pub fn derive(
+ reviews: &[GithubPullRequestReview],
+ requested_reviewer_github_user_ids: &[String],
+ ) -> Option<Self> {
+ let states = || reviews.iter().map(|review| review.state);
+ if states().any(|state| state == GithubPullRequestReviewState::ChangesRequested) {
+ return Some(Self::ChangesRequested);
+ }
+ if states().any(|state| state == GithubPullRequestReviewState::Approved) {
+ return Some(Self::Approved);
+ }
+ (!requested_reviewer_github_user_ids.is_empty()).then_some(Self::ReviewRequired)
+ }
+
+ /// The decision as stored in the `github_pull_request.review_decision` column.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Approved => "approved",
+ Self::ChangesRequested => "changes_requested",
+ Self::ReviewRequired => "review_required",
+ }
+ }
+}
+
/// GitHub API pull request details used to enrich a pull request reference.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
@@ -221,6 +366,27 @@ pub struct GithubPullRequestDetails {
#[cfg_attr(feature = "schema", schema(ignore))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub github_updated_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// The users assigned to the pull request, when available.
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "deserialize_optional_array"
+ )]
+ pub assignees: Option<Vec<GithubPullRequestUser>>,
+ /// The pull request's labels, when available.
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "deserialize_optional_array"
+ )]
+ pub labels: Option<Vec<GithubPullRequestLabel>>,
+ /// Each reviewer's latest submitted review, when enrichment includes reviews.
+ #[serde(
+ default,
+ skip_serializing_if = "Option::is_none",
+ deserialize_with = "deserialize_optional_array"
+ )]
+ pub reviews: Option<Vec<GithubPullRequestReview>>,
}
impl GithubPullRequestDetails {
@@ -292,6 +458,16 @@ pub struct EnrichedGithubPullRequest {
#[cfg_attr(feature = "schema", schema(ignore))]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub github_updated_at: Option<chrono::DateTime<chrono::Utc>>,
+ /// The users assigned to the pull request, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub assignees: Option<Vec<GithubPullRequestUser>>,
+ /// The pull request's labels, when known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub labels: Option<Vec<GithubPullRequestLabel>>,
+ /// Each reviewer's latest submitted review, when known. Stored metadata merges this per
+ /// reviewer, so a write that knows one review keeps the others.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub reviews: Option<Vec<GithubPullRequestReview>>,
}
impl EnrichedGithubPullRequest {
@@ -318,6 +494,9 @@ impl EnrichedGithubPullRequest {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
}
}
@@ -349,6 +528,9 @@ impl EnrichedGithubPullRequest {
draft: details.draft,
requested_reviewer_github_user_ids: details.requested_reviewer_github_user_ids,
github_updated_at: details.github_updated_at,
+ assignees: details.assignees,
+ labels: details.labels,
+ reviews: details.reviews,
}
}
@@ -357,8 +539,9 @@ impl EnrichedGithubPullRequest {
/// Partial refreshes may omit `comments` or `checks`. When an omitted field exists as an array in
/// `existing_metadata`, the existing array is copied forward so richer metadata is not discarded.
/// The same applies to `authorLogin`, `authorId`, `description`, `repositoryId`, `draft`,
- /// `requestedReviewerGithubUserIds`, and `githubUpdatedAt`, which fallback write paths (such
- /// as comment webhooks without a `pull_request` payload) omit.
+ /// `requestedReviewerGithubUserIds`, `githubUpdatedAt`, `assignees`, and `labels`, which
+ /// fallback write paths (such as comment webhooks without a `pull_request` payload) omit.
+ /// `reviews` merges per reviewer, keeping each reviewer's most recently submitted review.
pub fn foreign_entity_metadata(
&self,
existing_metadata: Option<&serde_json::Value>,
@@ -391,6 +574,8 @@ impl EnrichedGithubPullRequest {
"draft",
"requestedReviewerGithubUserIds",
"githubUpdatedAt",
+ "assignees",
+ "labels",
] {
if metadata_object.contains_key(field) {
continue;
@@ -403,6 +588,15 @@ impl EnrichedGithubPullRequest {
}
}
+ const REVIEWS_FIELD: &str = "reviews";
+ let reviews = merge_reviews(
+ existing_object.get(REVIEWS_FIELD),
+ metadata_object.get(REVIEWS_FIELD),
+ );
+ if !reviews.is_empty() {
+ metadata_object.insert(REVIEWS_FIELD.to_string(), serde_json::to_value(reviews)?);
+ }
+
// Participants are unioned rather than carried forward or replaced: write paths produce
// partial sets (a webhook fallback knows the author/reviewers/assignees but not the
// commenters), so replacing would drop participants a richer earlier write discovered.
@@ -434,6 +628,19 @@ impl EnrichedGithubPullRequest {
}
}
+/// Each reviewer's latest review across the stored and then the incoming metadata.
+fn merge_reviews(
+ existing: Option<&serde_json::Value>,
+ incoming: Option<&serde_json::Value>,
+) -> Vec<GithubPullRequestReview> {
+ let parse = |value: Option<&serde_json::Value>| -> Vec<GithubPullRequestReview> {
+ value
+ .and_then(|value| serde_json::from_value(value.clone()).ok())
+ .unwrap_or_default()
+ };
+ latest_reviews(parse(existing).into_iter().chain(parse(incoming)))
+}
+
/// Request body for the authenticated pull request enrichment proxy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
diff --git a/crates/github_pull_requests/src/domain/models/test.rs b/crates/github_pull_requests/src/domain/models/test.rs
index 447dc19f1d..03aec5c541 100644
--- a/crates/github_pull_requests/src/domain/models/test.rs
+++ b/crates/github_pull_requests/src/domain/models/test.rs
@@ -38,6 +38,9 @@ fn pull_request_details(
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
}
}
@@ -173,6 +176,9 @@ fn pull_request_response_serializes_with_camel_case_fields() {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
}],
};
@@ -306,6 +312,9 @@ fn pull_request_enrichment_copies_details_fields() {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
};
let enriched = EnrichedGithubPullRequest::from_details(reference.clone(), details);
@@ -361,6 +370,9 @@ fn pull_request_foreign_entity_metadata_serializes_enriched_pull_request() {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
};
let enriched = EnrichedGithubPullRequest::from_details(reference, details);
@@ -486,6 +498,9 @@ fn pull_request_foreign_entity_metadata_keeps_fresh_arrays() {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
};
let enriched = EnrichedGithubPullRequest::from_details(pull_request_reference(), details);
let existing_metadata = serde_json::json!({
@@ -596,3 +611,368 @@ fn pull_request_foreign_entity_metadata_carries_existing_participants_forward()
Some(&serde_json::json!(["7"]))
);
}
+
+fn review(
+ reviewer: &str,
+ state: GithubPullRequestReviewState,
+ minute: u32,
+) -> GithubPullRequestReview {
+ GithubPullRequestReview {
+ reviewer_github_user_id: reviewer.to_string(),
+ reviewer_login: None,
+ state,
+ submitted_at: Some(
+ chrono::DateTime::parse_from_rfc3339(&format!("2026-09-26T12:{minute:02}:00Z"))
+ .unwrap()
+ .with_timezone(&chrono::Utc),
+ ),
+ }
+}
+
+#[test]
+fn decisions_outrank_comments_in_both_orders() {
+ use GithubPullRequestReviewState::{Approved, ChangesRequested, Commented, Dismissed};
+
+ for state in [Approved, ChangesRequested, Dismissed] {
+ for (decision_minute, comment_minute) in [(1, 2), (2, 1)] {
+ let decision = review("8", state, decision_minute);
+ let comment = review("8", Commented, comment_minute);
+ for reviews in [
+ [decision.clone(), comment.clone()],
+ [comment.clone(), decision.clone()],
+ ] {
+ assert_eq!(latest_reviews(reviews), vec![decision.clone()]);
+ }
+ }
+ }
+}
+
+#[test]
+fn decisions_outrank_comments_with_missing_timestamps() {
+ use GithubPullRequestReviewState::{Approved, ChangesRequested, Commented, Dismissed};
+
+ for state in [Approved, ChangesRequested, Dismissed] {
+ for (decision_missing_time, comment_missing_time) in
+ [(true, false), (false, true), (true, true)]
+ {
+ let mut decision = review("8", state, 1);
+ let mut comment = review("8", Commented, 2);
+ if decision_missing_time {
+ decision.submitted_at = None;
+ }
+ if comment_missing_time {
+ comment.submitted_at = None;
+ }
+ for reviews in [
+ [decision.clone(), comment.clone()],
+ [comment.clone(), decision.clone()],
+ ] {
+ assert_eq!(latest_reviews(reviews), vec![decision.clone()]);
+ }
+ }
+ }
+}
+
+#[test]
+fn decisions_keep_timestamp_ordering_in_both_orders() {
+ use GithubPullRequestReviewState::{Approved, ChangesRequested, Dismissed};
+
+ for (earlier, later) in [
+ (Approved, ChangesRequested),
+ (ChangesRequested, Dismissed),
+ (Dismissed, Approved),
+ ] {
+ let earlier = review("8", earlier, 1);
+ let later = review("8", later, 2);
+ for reviews in [
+ [earlier.clone(), later.clone()],
+ [later.clone(), earlier.clone()],
+ ] {
+ assert_eq!(latest_reviews(reviews), vec![later.clone()]);
+ }
+ }
+}
+
+#[test]
+fn timed_decisions_outrank_untimed_decisions_in_both_orders() {
+ use GithubPullRequestReviewState::{Approved, ChangesRequested, Dismissed};
+
+ for (untimed, timed) in [
+ (Approved, ChangesRequested),
+ (ChangesRequested, Dismissed),
+ (Dismissed, Approved),
+ ] {
+ let mut untimed = review("8", untimed, 1);
+ untimed.submitted_at = None;
+ let timed = review("8", timed, 2);
+ for reviews in [
+ [untimed.clone(), timed.clone()],
+ [timed.clone(), untimed.clone()],
+ ] {
+ assert_eq!(latest_reviews(reviews), vec![timed.clone()]);
+ }
+ }
+}
+
+#[test]
+fn a_later_comment_does_not_replace_an_approval() {
+ let latest = latest_reviews([
+ review("8", GithubPullRequestReviewState::Approved, 1),
+ review("8", GithubPullRequestReviewState::Commented, 2),
+ review("9", GithubPullRequestReviewState::Commented, 1),
+ review("9", GithubPullRequestReviewState::ChangesRequested, 2),
+ ]);
+
+ assert_eq!(
+ latest.iter().map(|review| review.state).collect::<Vec<_>>(),
+ vec![
+ GithubPullRequestReviewState::Approved,
+ GithubPullRequestReviewState::ChangesRequested,
+ ]
+ );
+}
+
+#[test]
+fn a_dismissal_replaces_an_approval() {
+ let latest = latest_reviews([
+ review("8", GithubPullRequestReviewState::Approved, 1),
+ review("8", GithubPullRequestReviewState::Dismissed, 1),
+ ]);
+
+ assert_eq!(latest[0].state, GithubPullRequestReviewState::Dismissed);
+}
+
+#[test]
+fn review_decision_prefers_changes_requested_then_approval_then_requests() {
+ use GithubPullRequestReviewState::{Approved, ChangesRequested, Commented};
+ let requested = vec!["10".to_string()];
+
+ assert_eq!(
+ GithubPullRequestReviewDecision::derive(
+ &[review("8", Approved, 1), review("9", ChangesRequested, 1)],
+ &requested
+ ),
+ Some(GithubPullRequestReviewDecision::ChangesRequested)
+ );
+ assert_eq!(
+ GithubPullRequestReviewDecision::derive(&[review("8", Approved, 1)], &requested),
+ Some(GithubPullRequestReviewDecision::Approved)
+ );
+ assert_eq!(
+ GithubPullRequestReviewDecision::derive(&[review("8", Commented, 1)], &requested),
+ Some(GithubPullRequestReviewDecision::ReviewRequired)
+ );
+ assert_eq!(
+ GithubPullRequestReviewDecision::derive(&[review("8", Commented, 1)], &[]),
+ None
+ );
+}
+
+#[test]
+fn stored_reviews_merge_per_reviewer() {
+ let mut existing = EnrichedGithubPullRequest::from_reference(pull_request_reference());
+ existing.reviews = Some(vec![
+ review("8", GithubPullRequestReviewState::Approved, 1),
+ review("9", GithubPullRequestReviewState::Commented, 1),
+ ]);
+ let existing = existing.foreign_entity_metadata(None).unwrap();
+ let mut incoming = EnrichedGithubPullRequest::from_reference(pull_request_reference());
+ incoming.reviews = Some(vec![review(
+ "9",
+ GithubPullRequestReviewState::ChangesRequested,
+ 2,
+ )]);
+
+ let merged = incoming.foreign_entity_metadata(Some(&existing)).unwrap();
+ let row = GithubPullRequestRow::from_metadata(&merged).unwrap();
+
+ assert_eq!(
+ row.reviews
+ .iter()
+ .map(|review| (review.reviewer_github_user_id.as_str(), review.state))
+ .collect::<Vec<_>>(),
+ vec![
+ ("8", GithubPullRequestReviewState::Approved),
+ ("9", GithubPullRequestReviewState::ChangesRequested),
+ ]
+ );
+ assert_eq!(
+ row.review_decision,
+ Some(GithubPullRequestReviewDecision::ChangesRequested)
+ );
+}
+
+#[test]
+fn stored_comments_do_not_hide_incoming_review_decisions() {
+ use GithubPullRequestReviewState::{Approved, ChangesRequested, Commented, Dismissed};
+
+ for (state, expected_decision) in [
+ (Approved, Some(GithubPullRequestReviewDecision::Approved)),
+ (
+ ChangesRequested,
+ Some(GithubPullRequestReviewDecision::ChangesRequested),
+ ),
+ (Dismissed, None),
+ ] {
+ let decision = review("8", state, 1);
+ let comment = review("8", Commented, 2);
+ for (stored, incoming) in [
+ (comment.clone(), decision.clone()),
+ (decision.clone(), comment.clone()),
+ ] {
+ let mut existing = EnrichedGithubPullRequest::from_reference(pull_request_reference());
+ existing.reviews = Some(vec![stored]);
+ let existing = existing.foreign_entity_metadata(None).unwrap();
+ let mut updated = EnrichedGithubPullRequest::from_reference(pull_request_reference());
+ updated.reviews = Some(vec![incoming]);
+
+ let metadata = updated.foreign_entity_metadata(Some(&existing)).unwrap();
+ let row = GithubPullRequestRow::from_metadata(&metadata).unwrap();
+
+ assert_eq!(row.reviews, vec![decision.clone()]);
+ assert_eq!(row.review_decision, expected_decision);
+ }
+ }
+}
+
+#[test]
+fn sparse_typed_updates_keep_omissions_and_replace_supplied_empty_values() {
+ use super::GithubPullRequestWrite;
+ let original = GithubPullRequestRow {
+ draft: true,
+ assignees: vec![GithubPullRequestUser {
+ github_user_id: "7".into(),
+ login: None,
+ }],
+ labels: vec![GithubPullRequestLabel {
+ name: "bug".into(),
+ color: None,
+ }],
+ reviews: vec![GithubPullRequestReview {
+ reviewer_github_user_id: "8".into(),
+ reviewer_login: None,
+ state: GithubPullRequestReviewState::Approved,
+ submitted_at: None,
+ }],
+ ..GithubPullRequestRow::from_metadata(&serde_json::json!({
+ "githubKey":"macro/app/pull/7", "owner":"macro", "repo":"app", "number":7,
+ "url":"https://github.com/macro/app/pull/7", "displayName":"PR",
+ "requestedReviewerGithubUserIds":["8"], "participantGithubUserIds":["7"]
+ }))
+ .unwrap()
+ };
+ let sparse = GithubPullRequestWrite::from_metadata(&serde_json::json!({
+ "githubKey":"macro/app/pull/7", "owner":"macro", "repo":"app", "number":7,
+ "url":"https://github.com/macro/app/pull/7", "displayName":"PR", "status":"closed",
+ "participantGithubUserIds":["9"],
+ "reviews":[{"reviewerGithubUserId":"8", "state":"commented"}]
+ }))
+ .unwrap();
+ let merged = sparse.merge(Some(original));
+ assert!(merged.draft);
+ assert_eq!(merged.assignees.len(), 1);
+ assert_eq!(merged.labels.len(), 1);
+ assert_eq!(merged.participant_github_user_ids, vec!["7", "9"]);
+ assert_eq!(
+ merged.reviews[0].state,
+ GithubPullRequestReviewState::Approved
+ );
+ assert_eq!(
+ merged.review_decision,
+ Some(GithubPullRequestReviewDecision::Approved)
+ );
+ let supplied = GithubPullRequestWrite {
+ draft: Some(false),
+ assignees: Some(vec![]),
+ labels: Some(vec![]),
+ requested_reviewer_github_user_ids: Some(vec![]),
+ ..sparse
+ };
+ let merged = supplied.merge(Some(merged));
+ assert!(!merged.draft);
+ assert!(merged.assignees.is_empty());
+ assert!(merged.labels.is_empty());
+ assert!(merged.requested_reviewer_github_user_ids.is_empty());
+ assert_eq!(
+ merged.review_decision,
+ Some(GithubPullRequestReviewDecision::Approved)
+ );
+}
+
+#[test]
+fn existing_typed_row_ignores_the_entire_fallback() {
+ use super::GithubPullRequestWrite;
+ let base = GithubPullRequestWrite::from_metadata(&serde_json::json!({
+ "githubKey":"macro/app/pull/7", "owner":"macro", "repo":"app", "number":7,
+ "url":"https://github.com/macro/app/pull/7", "displayName":"PR",
+ "title":"existing", "participantGithubUserIds":["7"],
+ "reviews":[{"reviewerGithubUserId":"8", "state":"approved"}]
+ }))
+ .unwrap();
+ let existing = GithubPullRequestWrite {
+ title: Some("existing".into()),
+ ..base.clone()
+ }
+ .merge(None);
+ let fallback = GithubPullRequestWrite {
+ title: Some("fallback".into()),
+ status: Some(GithubPullRequestStatus::Closed),
+ participant_github_user_ids: Some(vec!["9".into()]),
+ reviews: Some(vec![review(
+ "10",
+ GithubPullRequestReviewState::ChangesRequested,
+ 1,
+ )]),
+ ..base.clone()
+ }
+ .merge(None);
+ let incoming = GithubPullRequestWrite {
+ title: None,
+ status: None,
+ participant_github_user_ids: None,
+ reviews: None,
+ initial_row: Some(fallback),
+ ..base
+ };
+ let merged = incoming.merge(Some(existing.clone()));
+ assert_eq!(merged, existing);
+ assert_eq!(merged.participant_github_user_ids, vec!["7"]);
+ assert_eq!(merged.reviews.len(), 1);
+ assert_eq!(
+ merged.review_decision,
+ Some(GithubPullRequestReviewDecision::Approved)
+ );
+}
+
+#[test]
+fn mismatched_fallback_key_or_number_is_rejected() {
+ use super::GithubPullRequestWrite;
+ let write = GithubPullRequestWrite::from_metadata(&serde_json::json!({
+ "githubKey":"macro/app/pull/7", "owner":"macro", "repo":"app", "number":7,
+ "url":"https://github.com/macro/app/pull/7", "displayName":"PR"
+ }))
+ .unwrap();
+ let fallback = GithubPullRequestWrite {
+ title: Some("wrong row".into()),
+ ..write.clone()
+ }
+ .merge(None);
+ for invalid in [
+ GithubPullRequestRow {
+ github_key: "other/app/pull/7".into(),
+ ..fallback.clone()
+ },
+ GithubPullRequestRow {
+ number: 8,
+ ..fallback.clone()
+ },
+ ] {
+ let merged = GithubPullRequestWrite {
+ initial_row: Some(invalid),
+ ..write.clone()
+ }
+ .merge(None);
+ assert_eq!(merged, write.merge(None));
+ assert_eq!(merged.title, None);
+ }
+}
diff --git a/crates/github_pull_requests/src/domain/ports.rs b/crates/github_pull_requests/src/domain/ports.rs
index 55b869ce97..92e29e0eb4 100644
--- a/crates/github_pull_requests/src/domain/ports.rs
+++ b/crates/github_pull_requests/src/domain/ports.rs
@@ -12,7 +12,7 @@ use macro_user_id::user_id::MacroUserIdStr;
use super::models::{
EnrichedGithubPullRequest, GithubPullRequestError, GithubPullRequestFacets,
- GithubPullRequestRow, GithubRepositoryIdentity, UpsertGithubPullRequest,
+ GithubPullRequestWrite, GithubRepositoryIdentity, UpsertGithubPullRequest,
UpsertedGithubPullRequest,
};
@@ -62,11 +62,11 @@ pub trait GithubPullRequestRepository: Send + Sync + 'static {
number: i64,
) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
- /// Store a pull request's typed columns. A row without a repository id keeps the one it
- /// has.
+ /// Atomically merge supplied typed columns with the shared row. Omitted fields retain
+ /// stored values. Concurrent creation and updates for the same key serialize before reading.
fn upsert_row(
&self,
- row: &GithubPullRequestRow,
+ row: &GithubPullRequestWrite,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
/// Move the row stored under `from` to `to`. When `to` already has a row, the row under
diff --git a/crates/github_pull_requests/src/domain/service.rs b/crates/github_pull_requests/src/domain/service.rs
index 15c90c613b..26898bae1f 100644
--- a/crates/github_pull_requests/src/domain/service.rs
+++ b/crates/github_pull_requests/src/domain/service.rs
@@ -15,8 +15,8 @@ use super::{
models::{
EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
GithubPullRequestError, GithubPullRequestFacets, GithubPullRequestRow,
- GithubPullRequestStatus, GithubRepositoryIdentity, UpsertGithubPullRequest,
- UpsertedGithubPullRequest,
+ GithubPullRequestStatus, GithubPullRequestWrite, GithubRepositoryIdentity,
+ UpsertGithubPullRequest, UpsertedGithubPullRequest,
},
ports::{
GithubPullRequestFacetRepository, GithubPullRequestFacetService,
@@ -114,16 +114,18 @@ impl<F: ForeignEntityService, R: GithubPullRequestRepository> GithubPullRequestS
.map_err(repository_error)
}
- /// Write a pull request's typed columns from a record's metadata. Rows are derived data, so
+ /// Write supplied typed columns without collapsing omitted fields. Rows are derived data, so
/// a failure is logged rather than failing the write of the record itself.
- async fn store_row(&self, metadata: &serde_json::Value, repository_id: Option<i64>) -> bool {
- let Some(mut row) = GithubPullRequestRow::from_metadata(metadata) else {
+ async fn store_row(
+ &self,
+ pull_request: &EnrichedGithubPullRequest,
+ records: &[ForeignEntity],
+ ) -> bool {
+ let Some(mut row) = GithubPullRequestWrite::from_enriched(pull_request) else {
tracing::warn!("pull request metadata has no typed columns");
return false;
};
- if repository_id.is_some() {
- row.repository_id = repository_id;
- }
+ row.initial_row = initialization_row(records, &row.github_key, row.number);
match self.repo.upsert_row(&row).await {
Ok(()) => true,
@@ -157,7 +159,7 @@ impl<F: ForeignEntityService, R: GithubPullRequestRepository> GithubPullRequestS
} = upsert;
self.follow_rename(&pull_request).await?;
- let records = self.stored_records(&pull_request.github_key).await?;
+ let mut records = self.stored_records(&pull_request.github_key).await?;
let existing = records.iter().find(|record| {
record.stored_for_id == stored_for.id
&& record.stored_for_auth_entity == stored_for.auth_entity
@@ -195,7 +197,8 @@ impl<F: ForeignEntityService, R: GithubPullRequestRepository> GithubPullRequestS
.await?
}
};
- self.store_row(&foreign_entity.metadata, None).await;
+ records.push(foreign_entity.clone());
+ self.store_row(&pull_request, &records).await;
Ok(UpsertedGithubPullRequest {
foreign_entity,
@@ -215,8 +218,9 @@ impl<F: ForeignEntityService, R: GithubPullRequestRepository> GithubPullRequestS
) -> Result<Vec<ForeignEntity>, GithubPullRequestError> {
let mut refreshed = Vec::new();
let mut first_error = None;
- for record in self.stored_records(&pull_request.github_key).await? {
- match self.refresh_record(pull_request, &record).await {
+ let mut records = self.stored_records(&pull_request.github_key).await?;
+ for record in &records {
+ match self.refresh_record(pull_request, record).await {
Ok(record) => refreshed.push(record),
Err(error) => {
tracing::error!(
@@ -233,8 +237,11 @@ impl<F: ForeignEntityService, R: GithubPullRequestRepository> GithubPullRequestS
if let Some(error) = first_error {
return Err(error);
}
- if let Some(latest) = refreshed.iter().max_by_key(|record| record.updated_at) {
- self.store_row(&latest.metadata, None).await;
+ if !refreshed.is_empty() {
+ // Sparse serialization can clear optional source scalars. Keep the pre-refresh
+ // records as initialization-only evidence; an existing typed row ignores them.
+ records.extend(refreshed.iter().cloned());
+ self.store_row(pull_request, &records).await;
}
Ok(refreshed)
}
@@ -264,8 +271,17 @@ where
.await
.map_err(repository_error)?;
for metadata in &pull_requests {
- if self.store_row(metadata, Some(repository_id)).await {
- indexed += 1;
+ let Some(mut row) = GithubPullRequestWrite::from_metadata(metadata) else {
+ tracing::warn!("pull request metadata has no typed columns");
+ continue;
+ };
+ row.repository_id = Some(repository_id);
+ match self.repo.upsert_row(&row).await {
+ Ok(()) => indexed += 1,
+ Err(error) => tracing::error!(
+ error=?error, github_key=%row.github_key,
+ "failed to store pull request row"
+ ),
}
}
}
@@ -338,6 +354,22 @@ where
}
}
+/// Fold sparse source metadata in a stable order, retaining fields omitted by later sources.
+fn initialization_row(
+ records: &[ForeignEntity],
+ github_key: &str,
+ number: i64,
+) -> Option<GithubPullRequestRow> {
+ let mut records = records.iter().collect::<Vec<_>>();
+ records.sort_by_key(|record| (record.updated_at, record.id));
+ records
+ .into_iter()
+ .filter(|record| record.foreign_entity_id == github_key)
+ .filter_map(|record| GithubPullRequestWrite::from_metadata(&record.metadata))
+ .filter(|write| write.github_key == github_key && write.number == number)
+ .fold(None, |row, write| Some(write.merge(row)))
+}
+
fn repository_error(error: impl Into<anyhow::Error>) -> GithubPullRequestError {
GithubPullRequestError::Repository(error.into())
}
diff --git a/crates/github_pull_requests/src/domain/service/test.rs b/crates/github_pull_requests/src/domain/service/test.rs
index 5df7a7cf43..7a6e3e52a7 100644
--- a/crates/github_pull_requests/src/domain/service/test.rs
+++ b/crates/github_pull_requests/src/domain/service/test.rs
@@ -1,3 +1,5 @@
+mod initialization;
+mod refresh;
use std::convert::Infallible;
use std::sync::{Arc, Mutex};
@@ -21,8 +23,9 @@ use super::GithubPullRequestServiceImpl;
use crate::domain::{
models::{
EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
- GithubPullRequestError, GithubPullRequestFacets, GithubPullRequestRow,
- GithubPullRequestStatus, GithubRepositoryIdentity, UpsertGithubPullRequest,
+ GithubPullRequestError, GithubPullRequestFacets, GithubPullRequestReviewDecision,
+ GithubPullRequestRow, GithubPullRequestStatus, GithubPullRequestWrite,
+ GithubRepositoryIdentity, UpsertGithubPullRequest,
},
ports::{
GithubPullRequestFacetRepository, GithubPullRequestFacetService,
@@ -209,20 +212,15 @@ impl GithubPullRequestRepository for StubPullRequestRows {
.map(|row| row.github_key))
}
- async fn upsert_row(&self, row: &GithubPullRequestRow) -> Result<(), Self::Err> {
+ async fn upsert_row(&self, row: &GithubPullRequestWrite) -> Result<(), Self::Err> {
let mut rows = self.rows.lock().unwrap();
- match rows
+ if let Some(existing) = rows
.iter_mut()
.find(|existing| existing.github_key == row.github_key)
{
- Some(existing) => {
- let repository_id = row.repository_id.or(existing.repository_id);
- *existing = GithubPullRequestRow {
- repository_id,
- ..row.clone()
- };
- }
- None => rows.push(row.clone()),
+ *existing = row.merge(Some(existing.clone()));
+ } else {
+ rows.push(row.merge(None));
}
Ok(())
}
@@ -326,6 +324,9 @@ fn pull_request(status: GithubPullRequestStatus) -> EnrichedGithubPullRequest {
draft: None,
requested_reviewer_github_user_ids: None,
github_updated_at: None,
+ assignees: None,
+ labels: None,
+ reviews: None,
}
}
@@ -599,6 +600,10 @@ async fn upsert_writes_the_row_from_the_merged_metadata() {
requested_reviewer_github_user_ids: vec!["8".to_string()],
participant_github_user_ids: vec!["42".to_string()],
github_updated_at: None,
+ assignees: Vec::new(),
+ labels: Vec::new(),
+ reviews: Vec::new(),
+ review_decision: Some(GithubPullRequestReviewDecision::ReviewRequired),
}]
);
}
@@ -870,3 +875,45 @@ async fn facets_reject_a_receipt_for_anything_but_a_team() {
assert!(matches!(result, Err(GithubPullRequestError::BadRequest(_))));
assert!(rows.facet_requests.lock().unwrap().is_empty());
}
+
+#[tokio::test]
+async fn index_rebuild_keeps_richer_shared_row_when_latest_record_is_sparse() {
+ let rows = StubPullRequestRows::default();
+ let rich = serde_json::json!({
+ "githubKey": GITHUB_KEY, "owner": "macro", "repo": "app", "number": 7,
+ "url": "https://github.com/macro/app/pull/7", "displayName": "PR",
+ "draft": true, "assignees": [{"githubUserId":"7"}], "labels": [{"name":"bug"}],
+ "requestedReviewerGithubUserIds": ["8"], "participantGithubUserIds": ["7"]
+ });
+ rows.rows
+ .lock()
+ .unwrap()
+ .push(GithubPullRequestRow::from_metadata(&rich).unwrap());
+ rows.stored.lock().unwrap().push((
+ "macro".into(),
+ "app".into(),
+ serde_json::json!({
+ "githubKey": GITHUB_KEY, "owner": "macro", "repo": "app", "number": 7,
+ "url": "https://github.com/macro/app/pull/7", "displayName": "PR",
+ "status": "closed"
+ }),
+ ));
+ let service = service(&StubForeignEntityService::default(), &rows);
+ assert_eq!(
+ service
+ .index_repositories(&[GithubRepositoryIdentity {
+ id: 99,
+ owner: "macro".into(),
+ name: "app".into(),
+ }])
+ .await
+ .unwrap(),
+ 1
+ );
+ let result = rows.rows();
+ assert!(result[0].draft);
+ assert_eq!(result[0].assignees.len(), 1);
+ assert_eq!(result[0].labels.len(), 1);
+ assert_eq!(result[0].requested_reviewer_github_user_ids, vec!["8"]);
+ assert_eq!(result[0].status, Some(GithubPullRequestStatus::Closed));
+}
diff --git a/crates/github_pull_requests/src/domain/service/test/initialization.rs b/crates/github_pull_requests/src/domain/service/test/initialization.rs
new file mode 100644
index 0000000000..c4b2466c63
--- /dev/null
+++ b/crates/github_pull_requests/src/domain/service/test/initialization.rs
@@ -0,0 +1,125 @@
+use super::*;
+use crate::domain::models::{
+ GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewState,
+};
+
+fn rich_source() -> serde_json::Value {
+ EnrichedGithubPullRequest {
+ repository_id: Some(99),
+ author_id: Some(7),
+ author_login: Some("author".into()),
+ draft: Some(true),
+ labels: Some(vec![GithubPullRequestLabel {
+ name: "important".into(),
+ color: None,
+ }]),
+ participant_github_user_ids: Some(vec!["7".into()]),
+ reviews: Some(vec![GithubPullRequestReview {
+ reviewer_github_user_id: "8".into(),
+ reviewer_login: None,
+ state: GithubPullRequestReviewState::Approved,
+ submitted_at: Some(Utc::now()),
+ }]),
+ ..pull_request(GithubPullRequestStatus::Open)
+ }
+ .foreign_entity_metadata(None)
+ .unwrap()
+}
+
+fn sparse_source() -> serde_json::Value {
+ EnrichedGithubPullRequest {
+ name: None,
+ participant_github_user_ids: Some(vec!["9".into()]),
+ ..pull_request(GithubPullRequestStatus::Open)
+ }
+ .foreign_entity_metadata(None)
+ .unwrap()
+}
+
+fn assert_rich_fields(row: &GithubPullRequestRow, title: Option<&str>) {
+ assert_eq!(row.repository_id, Some(99));
+ assert_eq!(row.title.as_deref(), title);
+ assert_eq!(row.author_github_user_id.as_deref(), Some("7"));
+ assert_eq!(row.author_login.as_deref(), Some("author"));
+ assert!(row.draft);
+ assert_eq!(row.labels[0].name, "important");
+ assert_eq!(row.participant_github_user_ids, vec!["42", "7", "9"]);
+ assert_eq!(row.reviews[0].state, GithubPullRequestReviewState::Approved);
+ assert_eq!(
+ row.review_decision,
+ Some(GithubPullRequestReviewDecision::Approved)
+ );
+}
+
+#[tokio::test]
+async fn upsert_recovers_a_missing_row_from_all_loaded_sources() {
+ let mut rich = stored_record(&team(), rich_source());
+ rich.updated_at -= chrono::Duration::hours(2);
+ let mut sparse = stored_record(&user(), sparse_source());
+ sparse.updated_at -= chrono::Duration::hours(1);
+ // The later sparse source must not discard the earlier source's richer fields.
+ let foreign_entities = StubForeignEntityService::with_records(vec![sparse, rich]);
+ let rows = StubPullRequestRows::default();
+ service(&foreign_entities, &rows)
+ .upsert_pull_request(UpsertGithubPullRequest {
+ pull_request: EnrichedGithubPullRequest {
+ name: None,
+ participant_github_user_ids: Some(vec!["42".into()]),
+ ..pull_request(GithubPullRequestStatus::Closed)
+ },
+ stored_for: user(),
+ })
+ .await
+ .unwrap();
+ let stored = rows.rows();
+ assert_eq!(stored.len(), 1);
+ assert_rich_fields(&stored[0], Some("Add pull request storage"));
+ assert_eq!(stored[0].status, Some(GithubPullRequestStatus::Closed));
+}
+
+#[tokio::test]
+async fn successful_refresh_recovers_a_missing_row_from_every_source() {
+ let rich = stored_record(&team(), rich_source());
+ let sparse = stored_record(&user(), sparse_source());
+ let foreign_entities = StubForeignEntityService::with_records(vec![rich, sparse]);
+ let rows = StubPullRequestRows::default();
+ let refreshed = service(&foreign_entities, &rows)
+ .refresh_pull_request(&EnrichedGithubPullRequest {
+ name: None,
+ participant_github_user_ids: Some(vec!["42".into()]),
+ ..pull_request(GithubPullRequestStatus::Closed)
+ })
+ .await
+ .unwrap();
+ assert_eq!(refreshed.len(), 2);
+ let stored = rows.rows();
+ assert_eq!(stored.len(), 1);
+ assert_rich_fields(&stored[0], Some("Add pull request storage"));
+ assert_eq!(stored[0].status, Some(GithubPullRequestStatus::Closed));
+}
+
+#[test]
+fn initialization_filters_key_and_number_and_orders_sources() {
+ let mut older = stored_record(&team(), rich_source());
+ older.updated_at -= chrono::Duration::hours(2);
+ let mut newer = stored_record(&user(), sparse_source());
+ newer.updated_at -= chrono::Duration::hours(1);
+ newer.metadata["labels"] = serde_json::json!([]);
+ let mut wrong_record_key = stored_record(&user(), rich_source());
+ wrong_record_key.foreign_entity_id = "wrong/app/pull/7".into();
+ let mut wrong_metadata_key = stored_record(&user(), rich_source());
+ wrong_metadata_key.metadata["githubKey"] = serde_json::json!("wrong/app/pull/7");
+ let mut wrong_number = stored_record(&user(), rich_source());
+ wrong_number.metadata["number"] = serde_json::json!(8);
+ let records = [
+ newer,
+ wrong_record_key,
+ wrong_metadata_key,
+ wrong_number,
+ older,
+ ];
+ let row = super::super::initialization_row(&records, GITHUB_KEY, 7).unwrap();
+ assert_eq!(row.title.as_deref(), Some("Add pull request storage"));
+ assert!(row.labels.is_empty());
+ assert_eq!(row.participant_github_user_ids, vec!["7", "9"]);
+}
diff --git a/crates/github_pull_requests/src/domain/service/test/refresh.rs b/crates/github_pull_requests/src/domain/service/test/refresh.rs
new file mode 100644
index 0000000000..e82064d81e
--- /dev/null
+++ b/crates/github_pull_requests/src/domain/service/test/refresh.rs
@@ -0,0 +1,80 @@
+use super::*;
+use crate::domain::models::{GithubPullRequestReview, GithubPullRequestReviewState};
+
+#[tokio::test]
+async fn partial_refresh_preserves_approval_from_the_failed_record() {
+ for failed_record_first in [true, false] {
+ let approved = EnrichedGithubPullRequest {
+ reviews: Some(vec![GithubPullRequestReview {
+ reviewer_github_user_id: "8".to_string(),
+ reviewer_login: None,
+ state: GithubPullRequestReviewState::Approved,
+ submitted_at: Some(Utc::now()),
+ }]),
+ ..pull_request(GithubPullRequestStatus::Open)
+ }
+ .foreign_entity_metadata(None)
+ .unwrap();
+ let original_row = GithubPullRequestRow::from_metadata(&approved).unwrap();
+ assert_eq!(
+ original_row.review_decision,
+ Some(GithubPullRequestReviewDecision::Approved)
+ );
+ let failed = stored_record(&team(), approved);
+ let successful = stored_record(&user(), serde_json::json!({ "status": "open" }));
+ let records = if failed_record_first {
+ vec![failed.clone(), successful.clone()]
+ } else {
+ vec![successful.clone(), failed.clone()]
+ };
+ let foreign_entities = StubForeignEntityService::with_records(records);
+ foreign_entities.state.lock().unwrap().failing_patches = vec![failed.id];
+ let rows = StubPullRequestRows::default();
+ rows.rows.lock().unwrap().push(original_row.clone());
+ let service = service(&foreign_entities, &rows);
+
+ assert!(
+ service
+ .refresh_pull_request(&pull_request(GithubPullRequestStatus::Closed))
+ .await
+ .is_err()
+ );
+
+ assert_eq!(foreign_entities.patches().len(), 2);
+ let updated = foreign_entities
+ .records()
+ .into_iter()
+ .find(|record| record.id == successful.id)
+ .unwrap();
+ assert_eq!(updated.metadata["status"], "closed");
+ assert_eq!(rows.rows(), vec![original_row]);
+ }
+}
+
+#[tokio::test]
+async fn partial_refresh_defers_a_new_typed_row_until_retry_succeeds() {
+ let failed = stored_record(&team(), serde_json::json!({ "status": "open" }));
+ let successful = stored_record(&user(), serde_json::json!({ "status": "open" }));
+ let foreign_entities = StubForeignEntityService::with_records(vec![failed.clone(), successful]);
+ foreign_entities.state.lock().unwrap().failing_patches = vec![failed.id];
+ let rows = StubPullRequestRows::default();
+ let service = service(&foreign_entities, &rows);
+ let update = pull_request(GithubPullRequestStatus::Closed);
+
+ assert!(service.refresh_pull_request(&update).await.is_err());
+ assert!(rows.rows().is_empty());
+ assert_eq!(foreign_entities.patches().len(), 2);
+
+ foreign_entities
+ .state
+ .lock()
+ .unwrap()
+ .failing_patches
+ .clear();
+ assert_eq!(
+ service.refresh_pull_request(&update).await.unwrap().len(),
+ 2
+ );
+ assert_eq!(rows.rows().len(), 1);
+ assert_eq!(rows.rows()[0].status, Some(GithubPullRequestStatus::Closed));
+}
diff --git a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs
index 793ce7e1be..15b13d857d 100644
--- a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs
+++ b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs
@@ -8,7 +8,10 @@ mod test;
use sqlx::PgPool;
-use crate::domain::{models::GithubPullRequestRow, ports::GithubPullRequestRepository};
+use crate::domain::{
+ models::{GithubPullRequestRow, GithubPullRequestStatus, GithubPullRequestWrite},
+ ports::GithubPullRequestRepository,
+};
/// Stores pull request rows in the `github_pull_request` table.
#[derive(Clone)]
@@ -45,8 +48,78 @@ impl GithubPullRequestRepository for PgGithubPullRequestRepo {
.await
}
- #[tracing::instrument(err, skip(self, row), fields(github_key = %row.github_key))]
- async fn upsert_row(&self, row: &GithubPullRequestRow) -> Result<(), Self::Err> {
+ #[tracing::instrument(err, skip(self, update), fields(github_key = %update.github_key))]
+ async fn upsert_row(&self, update: &GithubPullRequestWrite) -> Result<(), Self::Err> {
+ let mut tx = self.pool.begin().await?;
+ // Lock the key before reading, including when no row exists yet.
+ sqlx::query!(
+ "SELECT pg_advisory_xact_lock(hashtextextended($1, 0))",
+ update.github_key
+ )
+ .execute(&mut *tx)
+ .await?;
+ let stored = sqlx::query!(
+ r#"SELECT github_key, repository_id, number, owner, repo, title, status,
+ draft, author_github_user_id, author_login,
+ requested_reviewer_github_user_ids, participant_github_user_ids,
+ github_updated_at, assignees, labels, reviews
+ FROM github_pull_request WHERE github_key = $1 FOR UPDATE"#,
+ update.github_key,
+ )
+ .fetch_optional(&mut *tx)
+ .await?;
+ let decode = |value: serde_json::Value| {
+ serde_json::from_value(value).map_err(|error| sqlx::Error::Decode(error.into()))
+ };
+ let existing = stored
+ .map(|stored| -> Result<GithubPullRequestRow, sqlx::Error> {
+ let status = stored
+ .status
+ .map(|status| {
+ serde_json::from_value::<GithubPullRequestStatus>(
+ serde_json::Value::String(status),
+ )
+ .map_err(|error| sqlx::Error::Decode(error.into()))
+ })
+ .transpose()?;
+ let reviews: Vec<crate::domain::models::GithubPullRequestReview> =
+ decode(stored.reviews)?;
+ let requested_reviewer_github_user_ids = stored.requested_reviewer_github_user_ids;
+ let review_decision =
+ crate::domain::models::GithubPullRequestReviewDecision::derive(
+ &reviews,
+ &requested_reviewer_github_user_ids,
+ );
+ Ok(GithubPullRequestRow {
+ github_key: stored.github_key,
+ repository_id: stored.repository_id,
+ number: stored.number,
+ owner: stored.owner,
+ repo: stored.repo,
+ title: stored.title,
+ status,
+ draft: stored.draft,
+ author_github_user_id: stored.author_github_user_id,
+ author_login: stored.author_login,
+ requested_reviewer_github_user_ids,
+ participant_github_user_ids: stored.participant_github_user_ids,
+ github_updated_at: stored.github_updated_at,
+ assignees: serde_json::from_value(stored.assignees)
+ .map_err(|error| sqlx::Error::Decode(error.into()))?,
+ labels: serde_json::from_value(stored.labels)
+ .map_err(|error| sqlx::Error::Decode(error.into()))?,
+ reviews,
+ review_decision,
+ })
+ })
+ .transpose()?;
+ let row = update.merge(existing);
+ let json = |value: serde_json::Result<serde_json::Value>| {
+ value.map_err(|error| sqlx::Error::Encode(error.into()))
+ };
+ let assignees = json(serde_json::to_value(&row.assignees))?;
+ let labels = json(serde_json::to_value(&row.labels))?;
+ let reviews = json(serde_json::to_value(&row.reviews))?;
sqlx::query!(
r#"
INSERT INTO github_pull_request (
@@ -62,9 +135,16 @@ impl GithubPullRequestRepository for PgGithubPullRequestRepo {
author_login,
requested_reviewer_github_user_ids,
participant_github_user_ids,
- github_updated_at
+ github_updated_at,
+ assignees,
+ labels,
+ reviews,
+ review_decision
+ )
+ VALUES (
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13,
+ $14::jsonb, $15::jsonb, $16::jsonb, $17
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
ON CONFLICT (github_key) DO UPDATE SET
repository_id = COALESCE(EXCLUDED.repository_id, github_pull_request.repository_id),
number = EXCLUDED.number,
@@ -78,6 +158,10 @@ impl GithubPullRequestRepository for PgGithubPullRequestRepo {
requested_reviewer_github_user_ids = EXCLUDED.requested_reviewer_github_user_ids,
participant_github_user_ids = EXCLUDED.participant_github_user_ids,
github_updated_at = EXCLUDED.github_updated_at,
+ assignees = EXCLUDED.assignees,
+ labels = EXCLUDED.labels,
+ reviews = EXCLUDED.reviews,
+ review_decision = EXCLUDED.review_decision,
updated_at = NOW()
"#,
row.github_key,
@@ -93,10 +177,15 @@ impl GithubPullRequestRepository for PgGithubPullRequestRepo {
&row.requested_reviewer_github_user_ids,
&row.participant_github_user_ids,
row.github_updated_at,
+ assignees,
+ labels,
+ reviews,
+ row.review_decision.map(|decision| decision.as_str()),
)
- .execute(&self.pool)
+ .execute(&mut *tx)
.await?;
+ tx.commit().await?;
Ok(())
}
diff --git a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/facets/test.rs b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/facets/test.rs
index 66b9425818..8547cf498b 100644
--- a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/facets/test.rs
+++ b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/facets/test.rs
@@ -53,6 +53,10 @@ fn row(github_key: &str, repository_id: Option<i64>, number: i64) -> GithubPullR
requested_reviewer_github_user_ids: Vec::new(),
participant_github_user_ids: Vec::new(),
github_updated_at: None,
+ assignees: Vec::new(),
+ labels: Vec::new(),
+ reviews: Vec::new(),
+ review_decision: None,
}
}
@@ -62,27 +66,33 @@ async fn facets_count_each_visible_pull_request_once_by_repository_and_author(po
store_for(&pool, "macro/app/pull/7", USER, "user").await;
store_for(&pool, "macro/app/pull/7", TEAM, "team").await;
- repo.upsert_row(&row("macro/app/pull/7", Some(99), 7))
+ repo.upsert_row(&(&row("macro/app/pull/7", Some(99), 7)).into())
.await
.unwrap();
store_for(&pool, "macro/renamed/pull/8", TEAM, "team").await;
- repo.upsert_row(&GithubPullRequestRow {
- repo: "renamed".to_string(),
- author_github_user_id: Some("7".to_string()),
- author_login: None,
- github_updated_at: Some(chrono::Utc::now()),
- ..row("macro/renamed/pull/8", Some(99), 8)
- })
+ repo.upsert_row(
+ &(&GithubPullRequestRow {
+ repo: "renamed".to_string(),
+ author_github_user_id: Some("7".to_string()),
+ author_login: None,
+ github_updated_at: Some(chrono::Utc::now()),
+ ..row("macro/renamed/pull/8", Some(99), 8)
+ })
+ .into(),
+ )
.await
.unwrap();
store_for(&pool, "macro/app/pull/9", USER, "user").await;
- repo.upsert_row(&GithubPullRequestRow {
- author_github_user_id: None,
- author_login: None,
- ..row("macro/app/pull/9", None, 9)
- })
+ repo.upsert_row(
+ &(&GithubPullRequestRow {
+ author_github_user_id: None,
+ author_login: None,
+ ..row("macro/app/pull/9", None, 9)
+ })
+ .into(),
+ )
.await
.unwrap();
@@ -93,7 +103,7 @@ async fn facets_count_each_visible_pull_request_once_by_repository_and_author(po
"user",
)
.await;
- repo.upsert_row(&row("macro/other/pull/1", Some(100), 1))
+ repo.upsert_row(&(&row("macro/other/pull/1", Some(100), 1)).into())
.await
.unwrap();
@@ -170,7 +180,7 @@ async fn facet_names_follow_sync_time_instead_of_pull_request_update_time(pool:
.unwrap()
.with_timezone(&chrono::Utc),
);
- repo.upsert_row(&pull_request).await.unwrap();
+ repo.upsert_row(&(&pull_request).into()).await.unwrap();
set_synced_at(&pool, key, synced_at).await;
}
diff --git a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/test.rs b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/test.rs
index e53a9e57b1..f19529f455 100644
--- a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/test.rs
+++ b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/test.rs
@@ -3,7 +3,11 @@ use sqlx::PgPool;
use super::PgGithubPullRequestRepo;
use crate::domain::{
- models::{GithubPullRequestRow, GithubPullRequestStatus},
+ models::{
+ GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision,
+ GithubPullRequestReviewState, GithubPullRequestRow, GithubPullRequestStatus,
+ GithubPullRequestUser,
+ },
ports::GithubPullRequestRepository,
};
@@ -39,6 +43,10 @@ fn row(github_key: &str, repository_id: Option<i64>) -> GithubPullRequestRow {
requested_reviewer_github_user_ids: vec!["8".to_string()],
participant_github_user_ids: vec!["8".to_string(), "42".to_string()],
github_updated_at: None,
+ assignees: Vec::new(),
+ labels: Vec::new(),
+ reviews: Vec::new(),
+ review_decision: None,
}
}
@@ -46,7 +54,7 @@ fn row(github_key: &str, repository_id: Option<i64>) -> GithubPullRequestRow {
async fn upsert_stores_a_row_found_by_repository_and_number(pool: PgPool) {
let repo = PgGithubPullRequestRepo::new(pool.clone());
- repo.upsert_row(&row("macro/app/pull/7", Some(99)))
+ repo.upsert_row(&(&row("macro/app/pull/7", Some(99)).into()))
.await
.expect("upsert should succeed");
@@ -61,7 +69,7 @@ async fn upsert_stores_a_row_found_by_repository_and_number(pool: PgPool) {
async fn upsert_without_a_repository_id_keeps_the_one_the_row_has(pool: PgPool) {
let repo = PgGithubPullRequestRepo::new(pool.clone());
- repo.upsert_row(&row("macro/app/pull/7", None))
+ repo.upsert_row(&(&row("macro/app/pull/7", None)).into())
.await
.expect("upsert should succeed");
assert_eq!(
@@ -69,13 +77,16 @@ async fn upsert_without_a_repository_id_keeps_the_one_the_row_has(pool: PgPool)
Some((None, "app".to_string(), Some("open".to_string())))
);
- repo.upsert_row(&row("macro/app/pull/7", Some(99)))
+ repo.upsert_row(&(&row("macro/app/pull/7", Some(99)).into()))
.await
.expect("upsert should succeed");
- repo.upsert_row(&GithubPullRequestRow {
- status: Some(GithubPullRequestStatus::Merged),
- ..row("macro/app/pull/7", None)
- })
+ repo.upsert_row(
+ &(&GithubPullRequestRow {
+ status: Some(GithubPullRequestStatus::Merged),
+ ..row("macro/app/pull/7", None)
+ })
+ .into(),
+ )
.await
.expect("upsert should succeed");
@@ -88,7 +99,7 @@ async fn upsert_without_a_repository_id_keeps_the_one_the_row_has(pool: PgPool)
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn rename_moves_the_row_or_drops_it_when_the_new_key_has_one(pool: PgPool) {
let repo = PgGithubPullRequestRepo::new(pool.clone());
- repo.upsert_row(&row("macro/app/pull/7", Some(99)))
+ repo.upsert_row(&(&row("macro/app/pull/7", Some(99)).into()))
.await
.unwrap();
@@ -101,16 +112,22 @@ async fn rename_moves_the_row_or_drops_it_when_the_new_key_has_one(pool: PgPool)
Some("macro/renamed/pull/7".to_string())
);
- repo.upsert_row(&GithubPullRequestRow {
- number: 8,
- ..row("macro/app/pull/8", Some(99))
- })
+ repo.upsert_row(
+ &(&GithubPullRequestRow {
+ number: 8,
+ ..row("macro/app/pull/8", Some(99))
+ })
+ .into(),
+ )
.await
.unwrap();
- repo.upsert_row(&GithubPullRequestRow {
- number: 9,
- ..row("macro/renamed/pull/8", None)
- })
+ repo.upsert_row(
+ &(&GithubPullRequestRow {
+ number: 9,
+ ..row("macro/renamed/pull/8", None)
+ })
+ .into(),
+ )
.await
.unwrap();
repo.rename_row("macro/app/pull/8", "macro/renamed/pull/8")
@@ -120,3 +137,158 @@ async fn rename_moves_the_row_or_drops_it_when_the_new_key_has_one(pool: PgPool)
assert_eq!(stored_row(&pool, "macro/app/pull/8").await, None);
assert!(stored_row(&pool, "macro/renamed/pull/8").await.is_some());
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn upsert_stores_assignees_labels_and_reviews(pool: PgPool) {
+ let repo = PgGithubPullRequestRepo::new(pool.clone());
+
+ repo.upsert_row(
+ &(&GithubPullRequestRow {
+ assignees: vec![GithubPullRequestUser {
+ github_user_id: "7".to_string(),
+ login: Some("hubot".to_string()),
+ }],
+ labels: vec![GithubPullRequestLabel {
+ name: "bug".to_string(),
+ color: Some("d73a4a".to_string()),
+ }],
+ reviews: vec![GithubPullRequestReview {
+ reviewer_github_user_id: "8".to_string(),
+ reviewer_login: Some("monalisa".to_string()),
+ state: GithubPullRequestReviewState::Approved,
+ submitted_at: None,
+ }],
+ review_decision: Some(GithubPullRequestReviewDecision::Approved),
+ ..row("macro/app/pull/7", Some(99))
+ })
+ .into(),
+ )
+ .await
+ .expect("upsert should succeed");
+
+ let stored: (serde_json::Value, serde_json::Value, serde_json::Value, Option<String>) =
+ sqlx::query_as(
+ "SELECT assignees, labels, reviews, review_decision FROM github_pull_request WHERE github_key = $1",
+ )
+ .bind("macro/app/pull/7")
+ .fetch_one(&pool)
+ .await
+ .expect("row lookup should succeed");
+
+ assert_eq!(
+ stored.0,
+ serde_json::json!([{ "githubUserId": "7", "login": "hubot" }])
+ );
+ assert_eq!(
+ stored.1,
+ serde_json::json!([{ "name": "bug", "color": "d73a4a" }])
+ );
+ assert_eq!(
+ stored.2,
+ serde_json::json!([{
+ "reviewerGithubUserId": "8",
+ "reviewerLogin": "monalisa",
+ "state": "approved"
+ }])
+ );
+ assert_eq!(stored.3.as_deref(), Some("approved"));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn concurrent_sparse_writes_merge_on_missing_row(pool: PgPool) {
+ let repo = PgGithubPullRequestRepo::new(pool.clone());
+ let base = row("macro/app/pull/7", Some(99));
+ let title = crate::domain::models::GithubPullRequestWrite {
+ title: Some("independent title".into()),
+ ..(&base).into()
+ };
+ let mut title = title;
+ title.draft = None;
+ title.assignees = None;
+ title.labels = None;
+ title.requested_reviewer_github_user_ids = None;
+ title.participant_github_user_ids = None;
+ title.reviews = None;
+ let mut other = crate::domain::models::GithubPullRequestWrite::from(&base);
+ other.title = None;
+ other.status = None;
+ other.draft = Some(true);
+ other.assignees = Some(vec![GithubPullRequestUser {
+ github_user_id: "7".into(),
+ login: None,
+ }]);
+ let (first, second) = tokio::join!(repo.upsert_row(&title), repo.upsert_row(&other));
+ first.unwrap();
+ second.unwrap();
+ let stored = sqlx::query!(
+ "SELECT title, draft, assignees, requested_reviewer_github_user_ids FROM github_pull_request WHERE github_key = $1",
+ base.github_key,
+ ).fetch_one(&pool).await.unwrap();
+ assert_eq!(stored.title.as_deref(), Some("independent title"));
+ assert!(stored.draft);
+ assert_eq!(stored.assignees.as_array().unwrap().len(), 1);
+ assert_eq!(stored.requested_reviewer_github_user_ids, vec!["8"]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn sparse_update_preserves_rich_row_and_supplied_empty_collections_replace_it(pool: PgPool) {
+ let repo = PgGithubPullRequestRepo::new(pool.clone());
+ let mut original = row("macro/app/pull/7", Some(99));
+ original.draft = true;
+ original.assignees = vec![GithubPullRequestUser {
+ github_user_id: "7".into(),
+ login: None,
+ }];
+ original.labels = vec![GithubPullRequestLabel {
+ name: "bug".into(),
+ color: None,
+ }];
+ original.reviews = vec![GithubPullRequestReview {
+ reviewer_github_user_id: "8".into(),
+ reviewer_login: None,
+ state: GithubPullRequestReviewState::Approved,
+ submitted_at: None,
+ }];
+ repo.upsert_row(&(&original).into()).await.unwrap();
+ let sparse = crate::domain::models::GithubPullRequestWrite::from_metadata(&serde_json::json!({
+ "githubKey":"macro/app/pull/7", "owner":"macro", "repo":"app", "number":7,
+ "url":"https://github.com/macro/app/pull/7", "displayName":"PR", "status":"closed",
+ "participantGithubUserIds":["9"],
+ "reviews":[{"reviewerGithubUserId":"8", "state":"commented"}]
+ }))
+ .unwrap();
+ repo.upsert_row(&sparse).await.unwrap();
+ let stored = sqlx::query!(
+ "SELECT draft, assignees, labels, requested_reviewer_github_user_ids, participant_github_user_ids, reviews, review_decision FROM github_pull_request WHERE github_key = $1",
+ original.github_key,
+ ).fetch_one(&pool).await.unwrap();
+ assert!(stored.draft);
+ assert_eq!(stored.assignees.as_array().unwrap().len(), 1);
+ assert_eq!(stored.labels.as_array().unwrap().len(), 1);
+ assert_eq!(stored.requested_reviewer_github_user_ids, vec!["8"]);
+ assert!(
+ stored
+ .participant_github_user_ids
+ .contains(&"9".to_string())
+ );
+ assert_eq!(stored.reviews[0]["state"], "approved");
+ assert_eq!(stored.review_decision.as_deref(), Some("approved"));
+ repo.upsert_row(&crate::domain::models::GithubPullRequestWrite {
+ draft: Some(false),
+ assignees: Some(vec![]),
+ labels: Some(vec![]),
+ requested_reviewer_github_user_ids: Some(vec![]),
+ ..sparse
+ })
+ .await
+ .unwrap();
+ let stored = sqlx::query!(
+ "SELECT draft, assignees, labels, requested_reviewer_github_user_ids, review_decision FROM github_pull_request WHERE github_key = $1",
+ original.github_key,
+ ).fetch_one(&pool).await.unwrap();
+ assert!(!stored.draft);
+ assert_eq!(stored.assignees, serde_json::json!([]));
+ assert_eq!(stored.labels, serde_json::json!([]));
+ assert!(stored.requested_reviewer_github_user_ids.is_empty());
+ assert_eq!(stored.review_decision.as_deref(), Some("approved"));
+}
diff --git a/crates/macro_db_client/migrations/20260927021558_github_pull_request_assignees_labels_reviews.sql b/crates/macro_db_client/migrations/20260927021558_github_pull_request_assignees_labels_reviews.sql
new file mode 100644
index 0000000000..2a72f329f0
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260927021558_github_pull_request_assignees_labels_reviews.sql
@@ -0,0 +1,17 @@
+-- Assignees, labels, and reviews for GitHub pull requests, so they can be filtered and faceted
+-- like the other typed columns. Written by the github_pull_requests crate from the records'
+-- metadata; rows written before these columns keep the defaults until their next write.
+ALTER TABLE github_pull_request
+ -- [{"githubUserId": "42", "login": "octocat"}]
+ ADD COLUMN assignees JSONB NOT NULL DEFAULT '[]',
+ -- [{"name": "bug", "color": "d73a4a"}]
+ ADD COLUMN labels JSONB NOT NULL DEFAULT '[]',
+ -- Each reviewer's latest submitted review:
+ -- [{"reviewerGithubUserId": "42", "reviewerLogin": "octocat", "state": "approved"}]
+ ADD COLUMN reviews JSONB NOT NULL DEFAULT '[]',
+ -- Derived from the reviews and the outstanding review requests.
+ ADD COLUMN review_decision TEXT
+ CHECK (review_decision IN ('approved', 'changes_requested', 'review_required'));
+
+CREATE INDEX idx_github_pull_request_assignees ON github_pull_request USING GIN (assignees);
+CREATE INDEX idx_github_pull_request_labels ON github_pull_request USING GIN (labels);
diff --git a/packages/sdk/generated/auth/index.ts b/packages/sdk/generated/auth/index.ts
index c9550f32aa..de8f20da7d 100644
--- a/packages/sdk/generated/auth/index.ts
+++ b/packages/sdk/generated/auth/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestRef, GithubPullRequestStatus, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
+export type { AbGroup, AiBillingErrorBody, AppleLoginData, AppleLoginError, AppleLoginErrors, AppleLoginRequest, AppleLoginResponse, AppleLoginResponses, CancelCodexLoginData, CancelCodexLoginResponse, CancelCodexLoginResponses, ChangePlanData, ChangePlanError, ChangePlanErrors, ChangePlanRequest, ChangePlanResponse, ChangePlanResponse2, ChangePlanResponses, CheckGithubLinkStatusData, CheckGithubLinkStatusError, CheckGithubLinkStatusErrors, CheckGithubLinkStatusResponse, CheckGithubLinkStatusResponses, CheckGmailLinkStatusData, CheckGmailLinkStatusError, CheckGmailLinkStatusErrors, CheckGmailLinkStatusResponse, CheckGmailLinkStatusResponses, CheckoutSessionMetadata, ClientOptions, CodexConfigRequest, CodexConnectionStatus, CodexEnvironment, CodexEnvironmentRepository, CodexLoginPoll, CodexLoginStart, CodexLoginState, ConfigureCodexData, ConfigureCodexResponse, ConfigureCodexResponses, CreateAccountMergeRequest, CreateAiCreditCheckoutData, CreateAiCreditCheckoutError, CreateAiCreditCheckoutErrors, CreateAiCreditCheckoutResponse, CreateAiCreditCheckoutResponses, CreateCheckoutSessionV2Data, CreateCheckoutSessionV2Error, CreateCheckoutSessionV2Errors, CreateCheckoutSessionV2Request, CreateCheckoutSessionV2Response, CreateCheckoutSessionV2Responses, CreateGtmInviteLinkData, CreateGtmInviteLinkError, CreateGtmInviteLinkErrors, CreateGtmInviteLinkRequest, CreateGtmInviteLinkResponse, CreateGtmInviteLinkResponses, CreateInProgressLinkData, CreateInProgressLinkError, CreateInProgressLinkErrors, CreateInProgressLinkResponse, CreateInProgressLinkResponse2, CreateInProgressLinkResponses, CreateMergeRequestData, CreateMergeRequestError, CreateMergeRequestErrors, CreateMergeRequestResponse, CreateMergeRequestResponses, CreatePortalSessionData, CreatePortalSessionError, CreatePortalSessionErrors, CreatePortalSessionRequest, CreatePortalSessionResponse, CreatePortalSessionResponses, CreateTeamData, CreateTeamError, CreateTeamErrors, CreateTeamRequest, CreateTeamResponse, CreateTeamResponses, CreateUserData, CreateUserError, CreateUserErrors, CreateUserRequest, CreateUserResponse, CreateUserResponses, CreditCheckoutRequestBody, CreditCheckoutResponse, CursorApiKeyStatus, CursorModelOption, CursorModelsResponse, DeleteCursorApiKeyData, DeleteCursorApiKeyError, DeleteCursorApiKeyErrors, DeleteCursorApiKeyResponse, DeleteCursorApiKeyResponses, DeleteGithubLinkData, DeleteGithubLinkError, DeleteGithubLinkErrors, DeleteGithubLinkResponse, DeleteGithubLinkResponses, DeleteTeamData, DeleteTeamError, DeleteTeamErrors, DeleteTeamInviteHandlerData, DeleteTeamInviteHandlerError, DeleteTeamInviteHandlerErrors, DeleteTeamInviteHandlerResponses, DeleteTeamResponses, DeleteUserData, DeleteUserError, DeleteUserErrors, DeleteUserResponse, DeleteUserResponses, DenyReason, DisconnectCodexData, DisconnectCodexResponse, DisconnectCodexResponses, EmptyResponse, EnrichedGithubPullRequest, EnrichGithubPullRequestsData, EnrichGithubPullRequestsError, EnrichGithubPullRequestsErrors, EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, EnrichGithubPullRequestsResponse2, EnrichGithubPullRequestsResponses, ErrorResponse, GenerateEmailLinkData, GenerateEmailLinkError, GenerateEmailLinkErrors, GenerateEmailLinkRequest, GenerateEmailLinkResponse, GenerateEmailLinkResponses, GenericSuccessResponse, GetAiBillingPlansData, GetAiBillingPlansResponse, GetAiBillingPlansResponses, GetAiBillingSummaryData, GetAiBillingSummaryError, GetAiBillingSummaryErrors, GetAiBillingSummaryResponse, GetAiBillingSummaryResponses, GetCodexConnectionData, GetCodexConnectionResponse, GetCodexConnectionResponses, GetCursorApiKeyData, GetCursorApiKeyError, GetCursorApiKeyErrors, GetCursorApiKeyResponse, GetCursorApiKeyResponses, GetGtmInviteOfferData, GetGtmInviteOfferError, GetGtmInviteOfferErrors, GetGtmInviteOfferResponse, GetGtmInviteOfferResponses, GetLegacyUserPermissionsData, GetLegacyUserPermissionsError, GetLegacyUserPermissionsErrors, GetLegacyUserPermissionsResponse, GetLegacyUserPermissionsResponse2, GetLegacyUserPermissionsResponses, GetNamesWithEmailRequestBody, GetPermissionsData, GetPermissionsError, GetPermissionsErrors, GetPermissionsResponse, GetPermissionsResponses, GetProfilePicturesRequestBody, GetReferralCodeData, GetReferralCodeError, GetReferralCodeErrors, GetReferralCodeResponse, GetReferralCodeResponses, GetTeamData, GetTeamError, GetTeamErrors, GetTeamInvitesData, GetTeamInvitesError, GetTeamInvitesErrors, GetTeamInvitesResponse, GetTeamInvitesResponses, GetTeamResponse, GetTeamResponses, GetUserInfo, GetUserInfoData, GetUserInfoError, GetUserInfoErrors, GetUserInfoResponse, GetUserInfoResponses, GetUserInvitesData, GetUserInvitesError, GetUserInvitesErrors, GetUserInvitesResponse, GetUserInvitesResponses, GetUserLinkExistsData, GetUserLinkExistsError, GetUserLinkExistsErrors, GetUserLinkExistsResponse, GetUserLinkExistsResponses, GetUserNameData, GetUserNameError, GetUserNameErrors, GetUserNameResponse, GetUserNameResponses, GetUserNamesData, GetUserNamesError, GetUserNamesErrors, GetUserNamesResponse, GetUserNamesResponses, GetUserNamesWithEmailData, GetUserNamesWithEmailError, GetUserNamesWithEmailErrors, GetUserNamesWithEmailResponse, GetUserNamesWithEmailResponses, GetUserOrganizationData, GetUserOrganizationError, GetUserOrganizationErrors, GetUserOrganizationResponse, GetUserOrganizationResponses, GetUserPermissionsData, GetUserPermissionsError, GetUserPermissionsErrors, GetUserPermissionsResponse, GetUserPermissionsResponses, GetUserQuotaData, GetUserQuotaError, GetUserQuotaErrors, GetUserQuotaResponse, GetUserQuotaResponses, GetUserTeamsData, GetUserTeamsError, GetUserTeamsErrors, GetUserTeamsResponse, GetUserTeamsResponses, GithubLinkStatusResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestLabel, GithubPullRequestRef, GithubPullRequestReview, GithubPullRequestReviewState, GithubPullRequestStatus, GithubPullRequestUser, GmailLinkStatusResponse, GtmInviteLink, GtmInviteLinkList, GtmInviteLinkStatus, GtmInviteOffer, GtmInviteOfferStatus, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, InitGithubLinkData, InitGithubLinkError, InitGithubLinkErrors, InitGithubLinkResponse, InitGithubLinkResponse2, InitGithubLinkResponses, InitGmailLinkData, InitGmailLinkError, InitGmailLinkErrors, InitGmailLinkResponse, InitGmailLinkResponse2, InitGmailLinkResponses, InitOutlookLinkData, InitOutlookLinkError, InitOutlookLinkErrors, InitOutlookLinkResponse, InitOutlookLinkResponse2, InitOutlookLinkResponses, InviteEntry, InviteToTeamData, InviteToTeamError, InviteToTeamErrors, InviteToTeamRequest, InviteToTeamResponses, JoinTeamData, JoinTeamError, JoinTeamErrors, JoinTeamResponses, LinkShare, ListCodexEnvironmentsData, ListCodexEnvironmentsResponse, ListCodexEnvironmentsResponses, ListCursorModelsData, ListCursorModelsError, ListCursorModelsErrors, ListCursorModelsResponse, ListCursorModelsResponses, ListGtmInviteLinksData, ListGtmInviteLinksError, ListGtmInviteLinksErrors, ListGtmInviteLinksResponse, ListGtmInviteLinksResponses, LogoutData, LogoutResponse, LogoutResponses, MacroApiTokenData, MacroApiTokenError, MacroApiTokenErrors, MacroApiTokenResponse, MacroApiTokenResponse2, MacroApiTokenResponses, Oauth2CallbackData, Oauth2CallbackError, Oauth2CallbackErrors, Oauth2CallbackResponses, OauthRedirectData, OauthRedirectError, OauthRedirectErrors, OauthRedirectResponses, PasswordlessCallbackData, PasswordlessCallbackError, PasswordlessCallbackErrors, PasswordlessCallbackResponse, PasswordlessCallbackResponses, PasswordlessLoginData, PasswordlessLoginError, PasswordlessLoginErrors, PasswordlessLoginResponse, PasswordlessLoginResponses, PasswordlessRequest, PasswordlessStartedResponse, PasswordLoginData, PasswordLoginError, PasswordLoginErrors, PasswordLoginResponse, PasswordLoginResponses, PasswordRequest, PatchTeamCrmSettingsData, PatchTeamCrmSettingsError, PatchTeamCrmSettingsErrors, PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamCrmSettingsResponse2, PatchTeamCrmSettingsResponses, PatchTeamData, PatchTeamError, PatchTeamErrors, PatchTeamMemberPlanData, PatchTeamMemberPlanError, PatchTeamMemberPlanErrors, PatchTeamMemberPlanRequest, PatchTeamMemberPlanResponse, PatchTeamMemberPlanResponses, PatchTeamRequest, PatchTeamResponses, PatchTeamUserRole, PatchUserGroupData, PatchUserGroupError, PatchUserGroupErrors, PatchUserGroupRequest, PatchUserGroupResponse, PatchUserGroupResponses, PatchUserOnboardingData, PatchUserOnboardingError, PatchUserOnboardingErrors, PatchUserOnboardingRequest, PatchUserOnboardingResponse, PatchUserOnboardingResponses, PatchUserTutorialData, PatchUserTutorialError, PatchUserTutorialErrors, PatchUserTutorialRequest, PatchUserTutorialResponse, PatchUserTutorialResponses, Permission, PlanCatalogEntry, PlanCatalogResponse, PlanTier, PollCodexLoginData, PollCodexLoginResponse, PollCodexLoginResponses, PostGetNamesRequestBody, PostProfilePicturesData, PostProfilePicturesError, PostProfilePicturesErrors, PostProfilePicturesResponse, PostProfilePicturesResponses, ProfilePictureQueryParams, ProfilePictures, PublicGtmInviteLink, PutCursorApiKeyData, PutCursorApiKeyError, PutCursorApiKeyErrors, PutCursorApiKeyRequest, PutCursorApiKeyResponse, PutCursorApiKeyResponses, PutCursorDefaultModelData, PutCursorDefaultModelError, PutCursorDefaultModelErrors, PutCursorDefaultModelRequest, PutCursorDefaultModelResponse, PutCursorDefaultModelResponses, PutProfilePictureData, PutProfilePictureError, PutProfilePictureErrors, PutProfilePictureResponse, PutProfilePictureResponses, PutUserNameData, PutUserNameError, PutUserNameErrors, PutUserNameQueryParams, PutUserNameResponse, PutUserNameResponses, RedeemGtmInviteLinkData, RedeemGtmInviteLinkError, RedeemGtmInviteLinkErrors, RedeemGtmInviteLinkRequest, RedeemGtmInviteLinkResponse, RedeemGtmInviteLinkResponses, RefreshData, RefreshError, RefreshErrors, RefreshResponse, RefreshResponses, RejectInvitationData, RejectInvitationError, RejectInvitationErrors, RejectInvitationResponses, RemoveUserFromTeamData, RemoveUserFromTeamError, RemoveUserFromTeamErrors, RemoveUserFromTeamResponses, ResendFusionauthVerifyUserEmailData, ResendFusionauthVerifyUserEmailError, ResendFusionauthVerifyUserEmailErrors, ResendFusionauthVerifyUserEmailRequest, ResendFusionauthVerifyUserEmailResponse, ResendFusionauthVerifyUserEmailResponses, ResolveGtmInviteLinkData, ResolveGtmInviteLinkError, ResolveGtmInviteLinkErrors, ResolveGtmInviteLinkResponse, ResolveGtmInviteLinkResponses, RevokeGtmInviteLinkData, RevokeGtmInviteLinkError, RevokeGtmInviteLinkErrors, RevokeGtmInviteLinkResponse, RevokeGtmInviteLinkResponses, SeatPlan, SendInviteBody, SendMobileWelcomeEmailData, SendMobileWelcomeEmailError, SendMobileWelcomeEmailErrors, SendMobileWelcomeEmailRequest, SendMobileWelcomeEmailResponse, SendMobileWelcomeEmailResponse2, SendMobileWelcomeEmailResponses, SendReferralCodeData, SendReferralCodeError, SendReferralCodeErrors, SendReferralCodeResponse, SendReferralCodeResponses, SessionCreationData, SessionCreationError, SessionCreationErrors, SessionCreationResponse, SessionCreationResponses, SessionLoginData, SessionLoginError, SessionLoginErrors, SessionLoginResponse, SessionLoginResponses, SsoLoginData, SsoLoginError, SsoLoginErrors, SsoLoginResponses, SsoRequiredResponse, StartCodexLoginData, StartCodexLoginResponse, StartCodexLoginResponses, StripeSessionResponse, Team, TeamInviteDetails, TeamInvitesResponse, TeamMember, TeamPlan, TeamRole, TeamWithMembers, ToggleAutoJoinDomainResponse, ToggleNonAdminInvitesResponse, ToggleTeamAutoJoinDomainData, ToggleTeamAutoJoinDomainError, ToggleTeamAutoJoinDomainErrors, ToggleTeamAutoJoinDomainResponse, ToggleTeamAutoJoinDomainResponses, ToggleTeamNonAdminInvitesData, ToggleTeamNonAdminInvitesError, ToggleTeamNonAdminInvitesErrors, ToggleTeamNonAdminInvitesResponse, ToggleTeamNonAdminInvitesResponses, UpdateAiBillingOverageData, UpdateAiBillingOverageError, UpdateAiBillingOverageErrors, UpdateAiBillingOverageResponse, UpdateAiBillingOverageResponses, UpdateOverageRequest, UsageSnapshot, UserLinkResponse, UserName, UserNames, UserOrganizationResponse, UserProfilePicture, UserQuota, UserTokensResponse, VerifyEmailLinkData, VerifyEmailLinkError, VerifyEmailLinkErrors, VerifyEmailLinkResponse, VerifyEmailLinkResponses, VerifyFusionauthUserEmailData, VerifyFusionauthUserEmailError, VerifyFusionauthUserEmailErrors, VerifyFusionauthUserEmailResponse, VerifyFusionauthUserEmailResponses, VerifyMergeRequestData, VerifyMergeRequestError, VerifyMergeRequestErrors, VerifyMergeRequestResponse, VerifyMergeRequestResponses } from './types.gen';
diff --git a/packages/sdk/generated/auth/types.gen.ts b/packages/sdk/generated/auth/types.gen.ts
index 6650173cca..706d3ab7a5 100644
--- a/packages/sdk/generated/auth/types.gen.ts
+++ b/packages/sdk/generated/auth/types.gen.ts
@@ -395,6 +395,10 @@ export type EnrichedGithubPullRequest = {
* The number of added lines reported by GitHub, when enrichment succeeds.
*/
additions?: number | null;
+ /**
+ * The users assigned to the pull request, when known.
+ */
+ assignees?: Array<GithubPullRequestUser> | null;
/**
* The stable numeric GitHub user id for the pull request author, when available.
*/
@@ -427,6 +431,10 @@ export type EnrichedGithubPullRequest = {
* The stored GitHub association key, in `owner/repo/pull/number` format.
*/
githubKey: string;
+ /**
+ * The pull request's labels, when known.
+ */
+ labels?: Array<GithubPullRequestLabel> | null;
/**
* The GitHub pull request title, when enrichment succeeds.
*/
@@ -449,6 +457,11 @@ export type EnrichedGithubPullRequest = {
* The GitHub repository name.
*/
repo: string;
+ /**
+ * Each reviewer's latest submitted review, when known. Stored metadata merges this per
+ * reviewer, so a write that knows one review keeps the others.
+ */
+ reviews?: Array<GithubPullRequestReview> | null;
status?: null | GithubPullRequestStatus;
/**
* The public GitHub URL for the pull request.
@@ -669,6 +682,20 @@ export type GithubPullRequestComment = {
url?: string | null;
};
+/**
+ * A label on a GitHub pull request.
+ */
+export type GithubPullRequestLabel = {
+ /**
+ * The label color as six hex digits without a leading `#`, when known.
+ */
+ color?: string | null;
+ /**
+ * The label name, unique within its repository regardless of case.
+ */
+ name: string;
+};
+
/**
* A pull request reference that can be enriched with live GitHub data.
*/
@@ -699,11 +726,52 @@ export type GithubPullRequestRef = {
url: string;
};
+/**
+ * A reviewer's latest submitted review on a pull request.
+ */
+export type GithubPullRequestReview = {
+ /**
+ * The stable numeric GitHub user id of the reviewer, as a string.
+ */
+ reviewerGithubUserId: string;
+ /**
+ * The reviewer's GitHub login, when known.
+ */
+ reviewerLogin?: string | null;
+ /**
+ * What the review said.
+ */
+ state: GithubPullRequestReviewState;
+ /**
+ * When the review was submitted, when known.
+ */
+ submittedAt?: string | null;
+};
+
+/**
+ * What a reviewer's latest review on a pull request said.
+ */
+export type GithubPullRequestReviewState = 'approved' | 'changes_requested' | 'commented' | 'dismissed';
+
/**
* The normalized lifecycle status for a GitHub pull request.
*/
export type GithubPullRequestStatus = 'open' | 'closed' | 'merged';
+/**
+ * A GitHub user named on a pull request, such as an assignee.
+ */
+export type GithubPullRequestUser = {
+ /**
+ * The stable numeric GitHub user id, as a string.
+ */
+ githubUserId: string;
+ /**
+ * The user's GitHub login, when known.
+ */
+ login?: string | null;
+};
+
export type GmailLinkStatusResponse = {
/**
* Whether the user must reauthenticate their Gmail link.
diff --git a/packages/sdk/specs/auth.json b/packages/sdk/specs/auth.json
index 88b7cb59fe..236ff61c0c 100644
--- a/packages/sdk/specs/auth.json
+++ b/packages/sdk/specs/auth.json
@@ -5171,6 +5171,13 @@
"description": "The number of added lines reported by GitHub, when enrichment succeeds.",
"minimum": 0
},
+ "assignees": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestUser"
+ },
+ "description": "The users assigned to the pull request, when known."
+ },
"authorId": {
"type": ["integer", "null"],
"format": "int64",
@@ -5213,6 +5220,13 @@
"type": "string",
"description": "The stored GitHub association key, in `owner/repo/pull/number` format."
},
+ "labels": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestLabel"
+ },
+ "description": "The pull request's labels, when known."
+ },
"name": {
"type": ["string", "null"],
"description": "The GitHub pull request title, when enrichment succeeds."
@@ -5238,6 +5252,13 @@
"type": "string",
"description": "The GitHub repository name."
},
+ "reviews": {
+ "type": ["array", "null"],
+ "items": {
+ "$ref": "#/components/schemas/GithubPullRequestReview"
+ },
+ "description": "Each reviewer's latest submitted review, when known. Stored metadata merges this per\nreviewer, so a write that knows one review keeps the others."
+ },
"status": {
"oneOf": [
{
@@ -5545,6 +5566,21 @@
}
}
},
+ "GithubPullRequestLabel": {
+ "type": "object",
+ "description": "A label on a GitHub pull request.",
+ "required": ["name"],
+ "properties": {
+ "color": {
+ "type": ["string", "null"],
+ "description": "The label color as six hex digits without a leading `#`, when known."
+ },
+ "name": {
+ "type": "string",
+ "description": "The label name, unique within its repository regardless of case."
+ }
+ }
+ },
"GithubPullRequestRef": {
"type": "object",
"description": "A pull request reference that can be enriched with live GitHub data.",
@@ -5585,11 +5621,55 @@
}
}
},
+ "GithubPullRequestReview": {
+ "type": "object",
+ "description": "A reviewer's latest submitted review on a pull request.",
+ "required": ["reviewerGithubUserId", "state"],
+ "properties": {
+ "reviewerGithubUserId": {
+ "type": "string",
+ "description": "The stable numeric GitHub user id of the reviewer, as a string."
+ },
+ "reviewerLogin": {
+ "type": ["string", "null"],
+ "description": "The reviewer's GitHub login, when known."
+ },
+ "state": {
+ "$ref": "#/components/schemas/GithubPullRequestReviewState",
+ "description": "What the review said."
+ },
+ "submittedAt": {
+ "type": ["string", "null"],
+ "format": "date-time",
+ "description": "When the review was submitted, when known."
+ }
+ }
+ },
+ "GithubPullRequestReviewState": {
+ "type": "string",
+ "description": "What a reviewer's latest review on a pull request said.",
+ "enum": ["approved", "changes_requested", "commented", "dismissed"]
+ },
"GithubPullRequestStatus": {
"type": "string",
"description": "The normalized lifecycle status for a GitHub pull request.",
"enum": ["open", "closed", "merged"]
},
+ "GithubPullRequestUser": {
+ "type": "object",
+ "description": "A GitHub user named on a pull request, such as an assignee.",
+ "required": ["githubUserId"],
+ "properties": {
+ "githubUserId": {
+ "type": "string",
+ "description": "The stable numeric GitHub user id, as a string."
+ },
+ "login": {
+ "type": ["string", "null"],
+ "description": "The user's GitHub login, when known."
+ }
+ }
+ },
"GmailLinkStatusResponse": {
"type": "object",
"required": ["reauthentication_required"],