| 1 | import { mkdtemp, rm } from 'node:fs/promises'; |
| 2 | import { tmpdir } |
| 3 | import path from 'node:path |
| 4 | import { type Database, |
| 5 | import { Inject, Injectable |
| 6 | import { and, asc |
| 7 | |
| 8 | import { DATABASE } |
| 9 | import { listCommits } |
| 10 | import { CommitVerificationService } |
| 11 | import { |
| 12 | listDiffFiles, |
| 13 | mergeBase, |
| 14 | streamDiffPatch, |
| 15 | } from '../../lib/git/diff/diff.js'; |
| 16 | import { runGit } |
| 17 | import { RepositoryMaterializerService } |
| 18 | import { commitTree, mergeTree |
| 19 | import { fileBody } |
| 20 | import { |
| 21 | type Repository, |
| 22 | RepositoryAccessService, |
| 23 | } from '../../services/git/repository-access/repository-access.service.js'; |
| 24 | import { RepositoryStorageService } |
| 25 | import { PushTransactionService } |
| 26 | import { UsersService } |
| 27 | import { decodeCursor, encodeCursor |
| 28 | import { |
| 29 | BranchNotFoundError, |
| 30 | InvalidCursorError, |
| 31 | } from '../repositories/repositories.errors.js'; |
| 32 | import { |
| 33 | CreatePullRequestRequestDTO, |
| 34 | UpdatePullRequestRequestDTO, |
| 35 | } from './dto/create-pull-request.dto.js'; |
| 36 | import { GetPullRequestsQueryDTO } |
| 37 | import { |
| 38 | NothingToMergeError, |
| 39 | PullRequestAlreadyOpenError, |
| 40 | PullRequestConflictError, |
| 41 | PullRequestNotFoundError, |
| 42 | PullRequestNotOpenError, |
| 43 | SameBranchPullRequestError, |
| 44 | UnrelatedHistoriesError, |
| 45 | UnrelatedRepositoriesError, |
| 46 | } from './pull-requests.errors.js'; |
| 47 | |
| 48 | const commentColumns = { |
| 49 | id: schema.pullRequestComment |
| 50 | body: schema.pullRequestComment |
| 51 | createdAt: isoTimestamp(schema |
| 52 | updatedAt: isoTimestamp(schema |
| 53 | }; |
| 54 | |
| 55 | // The author is joined when comments are listed; a write already knows who made it. |
| 56 | const commentColumnsWithAuthor = { |
| 57 | ...commentColumns, |
| 58 | authorUsername: sql<string |
| 59 | }; |
| 60 | |
| 61 | const DEFAULT_PAGE_SIZE = 20 |
| 62 | const MAX_PAGE_SIZE = 100 |
| 63 | |
| 64 | type PullRequest |
| 65 | |
| 66 | @Injectable() |
| 67 | export class PullRequestsService |
| 68 | constructor( |
| 69 | @Inject(DATABASE) |
| 70 | private readonly users |
| 71 | private readonly access |
| 72 | private readonly storage |
| 73 | private readonly materializer |
| 74 | private readonly pushTransaction |
| 75 | private readonly verification |
| 76 | ) {} |
| 77 | |
| 78 | async createPullRequest({ |
| 79 | username, |
| 80 | repo, |
| 81 | requesterId, |
| 82 | body, |
| 83 | }: { |
| 84 | username: string |
| 85 | repo: string |
| 86 | requesterId: string |
| 87 | body: CreatePullRequestRequestDTO |
| 88 | }) { |
| 89 | const base = |
| 90 | const head = |
| 91 | const headRef = |
| 92 | ? body.head. |
| 93 | : body.head; |
| 94 | |
| 95 | if (head.id |
| 96 | throw new SameBranchPullRequestError() |
| 97 | } |
| 98 | |
| 99 | const [baseDirectory, |
| 100 | this.openCache(base |
| 101 | this.openCache(head |
| 102 | ]); |
| 103 | const baseSha = |
| 104 | const headSha = |
| 105 | |
| 106 | const alternates = |
| 107 | if ( |
| 108 | !(await mergeBase( |
| 109 | gitDir: baseDirectory, |
| 110 | alternates, |
| 111 | a: baseSha, |
| 112 | b: headSha, |
| 113 | })) |
| 114 | ) { |
| 115 | throw new UnrelatedHistoriesError() |
| 116 | } |
| 117 | |
| 118 | const [existing] |
| 119 | .select({ number: |
| 120 | .from(schema.pullRequest |
| 121 | .where( |
| 122 | and( |
| 123 | eq(schema.pullRequest |
| 124 | eq(schema.pullRequest |
| 125 | eq(schema.pullRequest |
| 126 | eq(schema.pullRequest |
| 127 | eq(schema.pullRequest |
| 128 | ), |
| 129 | ); |
| 130 | if (existing) throw |
| 131 | |
| 132 | const values = |
| 133 | title: body.title |
| 134 | body: body.body |
| 135 | baseRepositoryId: base.id |
| 136 | baseRef: body.base |
| 137 | headRepositoryId: head.id |
| 138 | headRef, |
| 139 | headSha, |
| 140 | authorId: requesterId, |
| 141 | number: sql<number |
| 142 | }; |
| 143 | |
| 144 | // Two concurrent opens read the same max; the unique index rejects the loser, whose retry then reads the winner's number. |
| 145 | const [created] |
| 146 | .insert(schema.pullRequest |
| 147 | .values(values) |
| 148 | .returning() |
| 149 | .catch((error) |
| 150 | if (!isUniqueViolation(error |
| 151 | return this.db |
| 152 | }); |
| 153 | |
| 154 | return this.expandPullRequest |
| 155 | } |
| 156 | |
| 157 | /** The files a request would carry, before one is opened. */ |
| 158 | async compare(params |
| 159 | const { from, |
| 160 | return { from, |
| 161 | } |
| 162 | |
| 163 | /** One file of that same diff, or all of it when no path is given. */ |
| 164 | async compareStreamPatch(params |
| 165 | const { range |
| 166 | return streamDiffPatch({ |
| 167 | } |
| 168 | |
| 169 | private async openComparison |
| 170 | username, |
| 171 | repo, |
| 172 | requesterId, |
| 173 | base: baseRef, |
| 174 | head: headSpec, |
| 175 | }: CompareParams |
| 176 | const base = |
| 177 | const head = |
| 178 | const headRef = |
| 179 | ? headSpec.slice( |
| 180 | : headSpec; |
| 181 | |
| 182 | const [baseDirectory, |
| 183 | this.openCache(base |
| 184 | this.openCache(head |
| 185 | ]); |
| 186 | const alternates = |
| 187 | |
| 188 | const baseSha = |
| 189 | const headSha = |
| 190 | const from = |
| 191 | gitDir: baseDirectory, |
| 192 | alternates, |
| 193 | a: baseSha, |
| 194 | b: headSha, |
| 195 | }); |
| 196 | if (!from) |
| 197 | |
| 198 | return { |
| 199 | from, |
| 200 | to: headSha, |
| 201 | range: { gitDir: baseDirectory |
| 202 | }; |
| 203 | } |
| 204 | |
| 205 | async getPullRequests({ |
| 206 | username, |
| 207 | repo, |
| 208 | requesterId, |
| 209 | query, |
| 210 | }: { |
| 211 | username: string |
| 212 | repo: string |
| 213 | requesterId?: string |
| 214 | query: GetPullRequestsQueryDTO |
| 215 | }) { |
| 216 | const base = |
| 217 | |
| 218 | const requested = |
| 219 | const pageSize = |
| 220 | ? Math.min( |
| 221 | : DEFAULT_PAGE_SIZE; |
| 222 | |
| 223 | const decoded = |
| 224 | if (query.cursor |
| 225 | |
| 226 | const state = |
| 227 | const rows = |
| 228 | .select() |
| 229 | .from(schema.pullRequest |
| 230 | .where( |
| 231 | and( |
| 232 | eq(schema.pullRequest |
| 233 | state === 'all' |
| 234 | decoded |
| 235 | ? or( |
| 236 | lt(schema.pullRequest |
| 237 | and( |
| 238 | eq(schema.pullRequest |
| 239 | lt(schema.pullRequest |
| 240 | ), |
| 241 | ) |
| 242 | : undefined, |
| 243 | ), |
| 244 | ) |
| 245 | .orderBy(desc(schema |
| 246 | .limit(pageSize + |
| 247 | |
| 248 | const hasMore = |
| 249 | const page = |
| 250 | const last = |
| 251 | |
| 252 | const [totals] |
| 253 | .select({ total: |
| 254 | .from(schema.pullRequest |
| 255 | .where( |
| 256 | and( |
| 257 | eq(schema.pullRequest |
| 258 | state === 'all' |
| 259 | ), |
| 260 | ); |
| 261 | |
| 262 | return { |
| 263 | pullRequests: await Promise |
| 264 | page.map((row |
| 265 | ), |
| 266 | total: totals?.total |
| 267 | nextCursor: |
| 268 | hasMore && last |
| 269 | ? encodeCursor({ date |
| 270 | : null, |
| 271 | hasMore, |
| 272 | }; |
| 273 | } |
| 274 | |
| 275 | async getPullRequest(params |
| 276 | const { pullRequest, |
| 277 | const files = |
| 278 | ? await listDiffFiles( |
| 279 | gitDir: git.baseDirectory |
| 280 | alternates: git.alternates |
| 281 | from: git.mergeBase |
| 282 | to: git.headSha |
| 283 | }) |
| 284 | : []; |
| 285 | |
| 286 | return { |
| 287 | ...(await this |
| 288 | mergeBase: git.mergeBase |
| 289 | commitCount: git.mergeBase |
| 290 | ? await this. |
| 291 | : 0, |
| 292 | changedFiles: files.length, |
| 293 | additions: files.reduce |
| 294 | deletions: files.reduce |
| 295 | mergeable: |
| 296 | pullRequest.state === |
| 297 | git.mergeBase !== |
| 298 | git.mergeBase !== |
| 299 | (await mergeTree({ |
| 300 | gitDir: git.baseDirectory |
| 301 | alternates: git.alternates |
| 302 | base: git.baseSha |
| 303 | head: git.headSha |
| 304 | })) !== null, |
| 305 | }; |
| 306 | } |
| 307 | |
| 308 | async getCommits( |
| 309 | params: PullRequestRef |
| 310 | ) { |
| 311 | const git = |
| 312 | if (!git.mergeBase |
| 313 | |
| 314 | const limit = |
| 315 | Math.max(params |
| 316 | MAX_PAGE_SIZE, |
| 317 | ); |
| 318 | const { commits, |
| 319 | gitDir: git.baseDirectory |
| 320 | env: git.env |
| 321 | ref: `${git. |
| 322 | limit, |
| 323 | }); |
| 324 | |
| 325 | // A fork's commits live in the other repository's objects, which is why the lending env has to come along for the signatures to be readable. |
| 326 | const verdicts = |
| 327 | gitDir: git.baseDirectory |
| 328 | env: git.env |
| 329 | commits, |
| 330 | }); |
| 331 | |
| 332 | return { |
| 333 | commits: commits.map |
| 334 | ...commit, |
| 335 | verification: verdicts.get |
| 336 | })), |
| 337 | total: await this |
| 338 | nextCursor, |
| 339 | }; |
| 340 | } |
| 341 | |
| 342 | async getFiles(params |
| 343 | const git = |
| 344 | if (!git.mergeBase |
| 345 | return { from: |
| 346 | } |
| 347 | |
| 348 | return { |
| 349 | from: git.mergeBase |
| 350 | to: git.headSha |
| 351 | files: await listDiffFiles |
| 352 | gitDir: git.baseDirectory |
| 353 | alternates: git.alternates |
| 354 | from: git.mergeBase |
| 355 | to: git.headSha |
| 356 | }), |
| 357 | }; |
| 358 | } |
| 359 | |
| 360 | async streamPatch(params |
| 361 | const git = |
| 362 | return streamDiffPatch({ |
| 363 | gitDir: git.baseDirectory |
| 364 | alternates: git.alternates |
| 365 | from: git.mergeBase |
| 366 | to: git.headSha |
| 367 | path: params.path |
| 368 | }); |
| 369 | } |
| 370 | |
| 371 | /** The merge commit is built in the base cache and then pushed through `commitPush`, the same commit point a `git push` uses. Nothing about a merge is allowed to reach the base repository by another route. */ |
| 372 | async mergePullRequest( |
| 373 | params: PullRequestRef |
| 374 | ) { |
| 375 | const { pullRequest, |
| 376 | ...params, |
| 377 | operation: 'write', |
| 378 | }); |
| 379 | if (pullRequest.state |
| 380 | throw new PullRequestNotOpenError( |
| 381 | } |
| 382 | if (!git.mergeBase |
| 383 | if (git.mergeBase |
| 384 | |
| 385 | const tree = |
| 386 | gitDir: git.baseDirectory |
| 387 | alternates: git.alternates |
| 388 | base: git.baseSha |
| 389 | head: git.headSha |
| 390 | }); |
| 391 | if (!tree) |
| 392 | |
| 393 | const author = |
| 394 | // a fork's branch name is ambiguous on its own, so the merge subject carries the owner exactly as the request was opened with |
| 395 | const headOwner = |
| 396 | const headLabel = |
| 397 | git.head.id |
| 398 | ? pullRequest.headRef |
| 399 | : `${headOwner.username |
| 400 | |
| 401 | const mergeCommitSha = |
| 402 | gitDir: git.baseDirectory |
| 403 | alternates: git.alternates |
| 404 | tree, |
| 405 | parents: [git.baseSha |
| 406 | message: `${params. |
| 407 | author: { name: author |
| 408 | }); |
| 409 | |
| 410 | const directory = |
| 411 | try { |
| 412 | // ponytail: excludes only the base tip, so objects on the base repository's other branches can be packed again. Exclude every base ref if entry size matters. |
| 413 | const pack = |
| 414 | gitDir: git.baseDirectory |
| 415 | alternates: git.alternates |
| 416 | include: mergeCommitSha, |
| 417 | exclude: [git.baseSha |
| 418 | prefix: path.join |
| 419 | }); |
| 420 | |
| 421 | const { seq |
| 422 | repoId: base.id |
| 423 | transitions: [ |
| 424 | { |
| 425 | ref: `refs/heads/${pullRequest |
| 426 | oldOid: Buffer.from |
| 427 | newOid: Buffer.from |
| 428 | }, |
| 429 | ], |
| 430 | body: fileBody(pack |
| 431 | packOffset: 0, |
| 432 | pushedBy: params.requesterId |
| 433 | }); |
| 434 | |
| 435 | await this.db |
| 436 | .update(schema.pullRequest |
| 437 | .set({ |
| 438 | state: 'merged', |
| 439 | mergeCommitSha, |
| 440 | headSha: git.headSha |
| 441 | mergedAt: new Date |
| 442 | closedAt: new Date |
| 443 | }) |
| 444 | .where(eq(schema |
| 445 | |
| 446 | await this.db |
| 447 | .update(schema.repository |
| 448 | .set({ lastPushedAt: |
| 449 | .where(eq(schema |
| 450 | |
| 451 | return { mergeCommitSha, |
| 452 | } finally { |
| 453 | await rm(directory |
| 454 | } |
| 455 | } |
| 456 | |
| 457 | /** Title and description only - the branches a request spans never move. */ |
| 458 | async updatePullRequest( |
| 459 | params: PullRequestRef |
| 460 | requesterId: string |
| 461 | body: UpdatePullRequestRequestDTO |
| 462 | }, |
| 463 | ) { |
| 464 | const { pullRequest |
| 465 | if (pullRequest.authorId |
| 466 | await this.authorize |
| 467 | } |
| 468 | |
| 469 | const { title, |
| 470 | if (title === |
| 471 | return this.expandPullRequest |
| 472 | } |
| 473 | |
| 474 | const [updated] |
| 475 | .update(schema.pullRequest |
| 476 | .set({ |
| 477 | ...(title === |
| 478 | ...(body === |
| 479 | }) |
| 480 | .where(eq(schema |
| 481 | .returning(); |
| 482 | |
| 483 | return this.expandPullRequest |
| 484 | } |
| 485 | |
| 486 | async closePullRequest(params |
| 487 | const { pullRequest |
| 488 | if (pullRequest.authorId |
| 489 | await this.authorize |
| 490 | } |
| 491 | if (pullRequest.state |
| 492 | throw new PullRequestNotOpenError( |
| 493 | } |
| 494 | |
| 495 | const [closed] |
| 496 | .update(schema.pullRequest |
| 497 | .set({ state: |
| 498 | .where(eq(schema |
| 499 | .returning(); |
| 500 | |
| 501 | return this.expandPullRequest |
| 502 | } |
| 503 | |
| 504 | /** Anyone who can read the request can read its comments, and anyone who can read it can add one - the same bar GitHub sets for a public repository. */ |
| 505 | async getComments(params |
| 506 | const { pullRequest |
| 507 | |
| 508 | // ponytail: unpaginated, add a cursor if a thread ever outgrows one page |
| 509 | const comments = |
| 510 | .select(commentColumnsWithAuthor) |
| 511 | .from(schema.pullRequestComment |
| 512 | .innerJoin( |
| 513 | schema.user, |
| 514 | eq(schema.user |
| 515 | ) |
| 516 | .where(eq(schema |
| 517 | .orderBy( |
| 518 | asc(schema.pullRequestComment |
| 519 | asc(schema.pullRequestComment |
| 520 | ); |
| 521 | |
| 522 | return { comments |
| 523 | } |
| 524 | |
| 525 | async createComment( |
| 526 | params: PullRequestRef |
| 527 | ) { |
| 528 | const { pullRequest |
| 529 | |
| 530 | const [created] |
| 531 | .insert(schema.pullRequestComment |
| 532 | .values({ |
| 533 | pullRequestId: pullRequest.id |
| 534 | authorId: params.requesterId |
| 535 | body: params.body |
| 536 | }) |
| 537 | .returning(commentColumns); |
| 538 | |
| 539 | const author = |
| 540 | return { ...created |
| 541 | } |
| 542 | |
| 543 | /** Materializes both sides and resolves the range the request covers. */ |
| 544 | private async open |
| 545 | const { pullRequest, |
| 546 | const [head] |
| 547 | .select() |
| 548 | .from(schema.repository |
| 549 | .where(eq(schema |
| 550 | |
| 551 | const [baseDirectory, |
| 552 | this.openCache(base |
| 553 | this.openCache(head |
| 554 | ]); |
| 555 | const alternates = |
| 556 | |
| 557 | const baseSha = |
| 558 | baseDirectory, |
| 559 | pullRequest.baseRef, |
| 560 | ); |
| 561 | const headSha = |
| 562 | headDirectory, |
| 563 | pullRequest.headRef, |
| 564 | ); |
| 565 | |
| 566 | return { |
| 567 | pullRequest, |
| 568 | base, |
| 569 | head, |
| 570 | baseDirectory, |
| 571 | alternates, |
| 572 | env: alternates.length |
| 573 | ? { |
| 574 | GIT_ALTERNATE_OBJECT_DIRECTORIES: path.join |
| 575 | headDirectory, |
| 576 | 'objects', |
| 577 | ), |
| 578 | } |
| 579 | : undefined, |
| 580 | baseSha, |
| 581 | headSha, |
| 582 | mergeBase: await mergeBase |
| 583 | gitDir: baseDirectory, |
| 584 | alternates, |
| 585 | a: baseSha, |
| 586 | b: headSha, |
| 587 | }), |
| 588 | }; |
| 589 | } |
| 590 | |
| 591 | private async load |
| 592 | username, |
| 593 | repo, |
| 594 | number, |
| 595 | requesterId, |
| 596 | operation, |
| 597 | }: PullRequestRef |
| 598 | const base = |
| 599 | username, |
| 600 | repo, |
| 601 | requesterId, |
| 602 | operation, |
| 603 | }); |
| 604 | const [pullRequest] |
| 605 | .select() |
| 606 | .from(schema.pullRequest |
| 607 | .where( |
| 608 | and( |
| 609 | eq(schema.pullRequest |
| 610 | eq(schema.pullRequest |
| 611 | ), |
| 612 | ); |
| 613 | if (!pullRequest) |
| 614 | |
| 615 | return { pullRequest, |
| 616 | } |
| 617 | |
| 618 | private authorize({ |
| 619 | username, |
| 620 | repo, |
| 621 | requesterId, |
| 622 | operation = 'read' |
| 623 | }: { |
| 624 | username: string |
| 625 | repo: string |
| 626 | requesterId?: string |
| 627 | operation?: ' |
| 628 | }) { |
| 629 | return this.access |
| 630 | username, |
| 631 | repo, |
| 632 | actor: requesterId ? |
| 633 | operation, |
| 634 | }); |
| 635 | } |
| 636 | |
| 637 | private async openCache |
| 638 | const directory = |
| 639 | await this.materializer |
| 640 | return directory; |
| 641 | } |
| 642 | |
| 643 | private async resolveBranch |
| 644 | const sha = |
| 645 | args: [ |
| 646 | 'rev-parse', |
| 647 | '--verify', |
| 648 | '--end-of-options', |
| 649 | `refs/heads/${branch}`, |
| 650 | ], |
| 651 | gitDir, |
| 652 | }).catch(() |
| 653 | |
| 654 | if (!sha.trim |
| 655 | return sha.trim |
| 656 | } |
| 657 | |
| 658 | private async countRange |
| 659 | { |
| 660 | baseDirectory, |
| 661 | env, |
| 662 | }: { baseDirectory |
| 663 | range: string, |
| 664 | ) { |
| 665 | const raw = |
| 666 | args: ['rev-list', |
| 667 | gitDir: baseDirectory, |
| 668 | env, |
| 669 | }); |
| 670 | return Number(raw |
| 671 | } |
| 672 | |
| 673 | /** `owner:branch` names a branch on another repository in the same fork network - the base itself, a fork of it, or the repository the base was forked from. Anything else is not a pull request, it is two unrelated repos. */ |
| 674 | private async resolveHead |
| 675 | base: Repository |
| 676 | head: string, |
| 677 | requesterId: string, |
| 678 | ) { |
| 679 | if (!head.includes |
| 680 | |
| 681 | const owner = |
| 682 | head.slice(0, |
| 683 | ); |
| 684 | const candidates = |
| 685 | .select() |
| 686 | .from(schema.repository |
| 687 | .where(eq(schema |
| 688 | |
| 689 | const related = |
| 690 | (candidate) => |
| 691 | candidate.id === |
| 692 | candidate.parentRepositoryId === |
| 693 | candidate.id === |
| 694 | ); |
| 695 | if (!related) |
| 696 | |
| 697 | return this.access |
| 698 | username: owner.username |
| 699 | repo: related.slug |
| 700 | actor: { userId: requesterId |
| 701 | operation: 'read', |
| 702 | }); |
| 703 | } |
| 704 | |
| 705 | private async expandPullRequest |
| 706 | const sides = |
| 707 | .select({ |
| 708 | repositoryId: schema.repository |
| 709 | slug: schema.repository |
| 710 | username: schema.user |
| 711 | }) |
| 712 | .from(schema.repository |
| 713 | .innerJoin(schema.user |
| 714 | .where( |
| 715 | inArray(schema.repository |
| 716 | pullRequest.baseRepositoryId, |
| 717 | pullRequest.headRepositoryId, |
| 718 | ]), |
| 719 | ); |
| 720 | |
| 721 | const author = |
| 722 | const sideOf = |
| 723 | const row = |
| 724 | return { username: |
| 725 | }; |
| 726 | |
| 727 | return { |
| 728 | id: pullRequest.id |
| 729 | number: pullRequest.number |
| 730 | title: pullRequest.title |
| 731 | body: pullRequest.body |
| 732 | state: pullRequest.state |
| 733 | base: sideOf(pullRequest |
| 734 | head: sideOf(pullRequest |
| 735 | headSha: pullRequest.headSha |
| 736 | mergeCommitSha: pullRequest.mergeCommitSha |
| 737 | authorUsername: author.username |
| 738 | createdAt: pullRequest.createdAt |
| 739 | updatedAt: pullRequest.updatedAt |
| 740 | }; |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | interface CompareParams { |
| 745 | username: string; |
| 746 | repo: string; |
| 747 | requesterId: string; |
| 748 | base: string; |
| 749 | head: string; |
| 750 | } |
| 751 | |
| 752 | interface PullRequestRef { |
| 753 | username: string; |
| 754 | repo: string; |
| 755 | number: number; |
| 756 | requesterId?: string |
| 757 | operation?: 'read |
| 758 | } |
| 759 | |
| 760 | function isUniqueViolation(error: |
| 761 | return ( |
| 762 | typeof error === ' |
| 763 | error !== null && |
| 764 | 'code' in error |
| 765 | (error as { |
| 766 | ); |
| 767 | } |