| 1 | import path from 'node:path'; |
| 2 | import { createDatabase, type |
| 3 | import { ConfigService } |
| 4 | import type { AuthService |
| 5 | import { and, eq |
| 6 | import { migrate } |
| 7 | import { |
| 8 | afterAll, |
| 9 | afterEach, |
| 10 | beforeAll, |
| 11 | beforeEach, |
| 12 | describe, |
| 13 | expect, |
| 14 | it, |
| 15 | vi, |
| 16 | } from 'vitest'; |
| 17 | |
| 18 | import type { Auth |
| 19 | import { |
| 20 | GitHubImportsDisabledError, |
| 21 | GitHubNotConnectedError, |
| 22 | ImportNotFailedError, |
| 23 | ImportNotFoundError, |
| 24 | ImportRetryWouldOverwriteError, |
| 25 | RepositoryImportingError, |
| 26 | StaleImportAttemptError, |
| 27 | } from '../../lib/imports/imports.errors.js'; |
| 28 | import { assertNotImporting } |
| 29 | import { ImportsService } |
| 30 | import type { RepositoriesService |
| 31 | import { RepositoryAccessService } |
| 32 | import { |
| 33 | ImportDispatcherService, |
| 34 | MAX_IMPORT_ATTEMPTS, |
| 35 | } from './import-dispatcher.service.js'; |
| 36 | import { ImportWriterService } |
| 37 | |
| 38 | const CONNECTION = process |
| 39 | const MIGRATIONS = path |
| 40 | import.meta.dirname, |
| 41 | '../../../../../packages/db/drizzle', |
| 42 | ); |
| 43 | |
| 44 | const OWNER = ' |
| 45 | const STRANGER = ' |
| 46 | const CONFIGURED = new |
| 47 | IMPORTER_URL: 'http://importer:3004', |
| 48 | IMPORTER_SECRET: 'secret', |
| 49 | GITHUB_CLIENT_ID: 'id', |
| 50 | GITHUB_CLIENT_SECRET: 'client-secret', |
| 51 | }); |
| 52 | |
| 53 | const issue = { |
| 54 | number: 3, |
| 55 | title: 'Crash on start', |
| 56 | body: 'It crashes', |
| 57 | authorLogin: 'octocat', |
| 58 | state: 'closed' as |
| 59 | createdAt: '2024-01-01T00:00:00.000Z', |
| 60 | updatedAt: '2024-01-03T00:00:00.000Z', |
| 61 | closedAt: '2024-01-02T00:00:00.000Z', |
| 62 | labels: [{ name: |
| 63 | }; |
| 64 | |
| 65 | const pullRequest = { |
| 66 | state: 'merged' as |
| 67 | draft: false, |
| 68 | baseRef: 'main', |
| 69 | headRef: 'fix', |
| 70 | headSha: 'b'.repeat |
| 71 | headInRepository: false, |
| 72 | mergeCommitSha: 'a'.repeat |
| 73 | mergedAt: '2024-01-02T00:00:00.000Z', |
| 74 | }; |
| 75 | |
| 76 | // Needs a throwaway Postgres; the suite is skipped without one. |
| 77 | describe.skipIf(!CONNECTION |
| 78 | let db: |
| 79 | let pool: |
| 80 | let dispatcher: |
| 81 | let writer: |
| 82 | let imports: |
| 83 | let repositoryId: |
| 84 | let importer: |
| 85 | let keys = |
| 86 | |
| 87 | const auth = |
| 88 | api: { |
| 89 | createApiKey: vi.fn |
| 90 | const id = |
| 91 | await db.insert |
| 92 | id, |
| 93 | referenceId: body.userId |
| 94 | key: `hashed-${id |
| 95 | createdAt: new Date |
| 96 | updatedAt: new Date |
| 97 | }); |
| 98 | return { id, |
| 99 | }), |
| 100 | getAccessToken: vi.fn |
| 101 | }, |
| 102 | } as unknown as |
| 103 | |
| 104 | async function startImport |
| 105 | values: Partial |
| 106 | ) { |
| 107 | const [row] |
| 108 | .insert(schema.repositoryImport |
| 109 | .values({ |
| 110 | repositoryId, |
| 111 | requestedById: OWNER, |
| 112 | source: 'octo/repo', |
| 113 | ...values, |
| 114 | }) |
| 115 | .returning(); |
| 116 | return row; |
| 117 | } |
| 118 | |
| 119 | async function importRow |
| 120 | const [row] |
| 121 | .select() |
| 122 | .from(schema.repositoryImport |
| 123 | .where(eq(schema |
| 124 | return row; |
| 125 | } |
| 126 | |
| 127 | async function keyExists |
| 128 | if (!id) |
| 129 | const rows = |
| 130 | .select() |
| 131 | .from(schema.apikey |
| 132 | .where(eq(schema |
| 133 | return rows.length |
| 134 | } |
| 135 | |
| 136 | beforeAll(async () |
| 137 | ({ db, pool |
| 138 | await migrate(db |
| 139 | }); |
| 140 | |
| 141 | beforeEach(async () |
| 142 | await db |
| 143 | .delete(schema.user |
| 144 | .where(inArray(schema |
| 145 | await db.insert |
| 146 | { |
| 147 | id: OWNER, |
| 148 | name: 'Owner', |
| 149 | email: 'import-owner@example.com', |
| 150 | username: 'import_owner', |
| 151 | }, |
| 152 | { |
| 153 | id: STRANGER, |
| 154 | name: 'Stranger', |
| 155 | email: 'import-stranger@example.com', |
| 156 | username: 'import_stranger', |
| 157 | }, |
| 158 | ]); |
| 159 | await db.insert |
| 160 | id: 'account_import_owner', |
| 161 | accountId: '1', |
| 162 | providerId: 'github', |
| 163 | userId: OWNER, |
| 164 | updatedAt: new Date |
| 165 | }); |
| 166 | const [repository] |
| 167 | .insert(schema.repository |
| 168 | .values({ |
| 169 | name: 'repo', |
| 170 | slug: 'repo', |
| 171 | ownerId: OWNER, |
| 172 | visibility: 'public', |
| 173 | }) |
| 174 | .returning(); |
| 175 | repositoryId = repository. |
| 176 | |
| 177 | importer = vi. |
| 178 | vi.stubGlobal('fetch |
| 179 | dispatcher = new |
| 180 | writer = new |
| 181 | imports = new |
| 182 | db, |
| 183 | CONFIGURED, |
| 184 | auth, |
| 185 | { |
| 186 | createRepository: async () |
| 187 | } as unknown as |
| 188 | new RepositoryAccessService(db |
| 189 | dispatcher, |
| 190 | ); |
| 191 | }); |
| 192 | |
| 193 | afterEach(async () |
| 194 | await dispatcher.onApplicationShutdown |
| 195 | vi.unstubAllGlobals(); |
| 196 | await db.delete |
| 197 | }); |
| 198 | |
| 199 | afterAll(async () |
| 200 | await db |
| 201 | .delete(schema.user |
| 202 | .where(inArray(schema |
| 203 | await pool.end |
| 204 | }); |
| 205 | |
| 206 | describe('dispatching', |
| 207 | it('hands a pending import to the importer with a fresh push key', |
| 208 | await startImport(); |
| 209 | expect(await dispatcher |
| 210 | |
| 211 | const row = |
| 212 | expect(row).toMatchObject |
| 213 | expect(await keyExists |
| 214 | const job = |
| 215 | expect(job).toEqual |
| 216 | importId: row.id |
| 217 | attempt: row.claimToken |
| 218 | source: 'octo/repo', |
| 219 | destination: 'import_owner/repo', |
| 220 | githubToken: 'gh-token', |
| 221 | ghostToken: `ghost_pat_${row |
| 222 | }); |
| 223 | }); |
| 224 | |
| 225 | it('puts a refused job back with backoff and drops its key', |
| 226 | importer.mockResolvedValue(new |
| 227 | await startImport(); |
| 228 | await dispatcher.tick |
| 229 | |
| 230 | const row = |
| 231 | expect(row).toMatchObject |
| 232 | status: 'pending', |
| 233 | attempts: 1, |
| 234 | apiKeyId: null, |
| 235 | lastError: 'The import could not be started', |
| 236 | }); |
| 237 | expect(row.nextAttemptAt |
| 238 | Date.now() - |
| 239 | ); |
| 240 | expect( |
| 241 | await db |
| 242 | .select() |
| 243 | .from(schema.apikey |
| 244 | .where(eq(schema |
| 245 | ).toEqual([]); |
| 246 | }); |
| 247 | |
| 248 | it('retries an attempt whose importer went silent, with a new token and key', |
| 249 | await startImport(); |
| 250 | await dispatcher.tick |
| 251 | const first = |
| 252 | await db |
| 253 | .update(schema.repositoryImport |
| 254 | .set({ leaseUntil: |
| 255 | .where(eq(schema |
| 256 | |
| 257 | await dispatcher.tick |
| 258 | const second = |
| 259 | expect(second).toMatchObject |
| 260 | status: 'running', |
| 261 | attempts: 2, |
| 262 | lastError: 'The importer stopped responding', |
| 263 | }); |
| 264 | expect(second.claimToken |
| 265 | expect(await keyExists |
| 266 | expect(await keyExists |
| 267 | await expect( |
| 268 | dispatcher.renewLease(first |
| 269 | ).rejects.toBeInstanceOf( |
| 270 | }); |
| 271 | |
| 272 | it('fails a silent attempt that used the last try', |
| 273 | await startImport(); |
| 274 | await dispatcher.tick |
| 275 | const row = |
| 276 | await db |
| 277 | .update(schema.repositoryImport |
| 278 | .set({ |
| 279 | attempts: MAX_IMPORT_ATTEMPTS, |
| 280 | leaseUntil: sql`now() - interval '1 second'` |
| 281 | }) |
| 282 | .where(eq(schema |
| 283 | |
| 284 | expect(await dispatcher |
| 285 | expect(await importRow |
| 286 | status: 'failed', |
| 287 | apiKeyId: null, |
| 288 | lastError: 'The importer stopped responding', |
| 289 | }); |
| 290 | expect(await keyExists |
| 291 | }); |
| 292 | |
| 293 | it('fails without retrying when the GitHub account is gone', |
| 294 | await db.delete |
| 295 | await startImport(); |
| 296 | await dispatcher.tick |
| 297 | expect((await importRow |
| 298 | expect(importer).not |
| 299 | }); |
| 300 | |
| 301 | it('has nothing to do without imports', |
| 302 | expect(await dispatcher |
| 303 | }); |
| 304 | }); |
| 305 | |
| 306 | describe('callbacks', |
| 307 | async function running |
| 308 | await startImport(); |
| 309 | await dispatcher.tick |
| 310 | return importRow(); |
| 311 | } |
| 312 | |
| 313 | it('renews the lease of the current attempt', |
| 314 | const row = |
| 315 | await db |
| 316 | .update(schema.repositoryImport |
| 317 | .set({ leaseUntil: |
| 318 | .where(eq(schema |
| 319 | expect(await dispatcher |
| 320 | repositoryId, |
| 321 | ); |
| 322 | expect((await importRow |
| 323 | Date.now() + |
| 324 | ); |
| 325 | }); |
| 326 | |
| 327 | it('records success, the default branch, and drops the key', |
| 328 | const row = |
| 329 | await dispatcher.settle |
| 330 | succeeded: true, |
| 331 | defaultBranch: 'trunk', |
| 332 | }); |
| 333 | expect(await importRow |
| 334 | status: 'succeeded', |
| 335 | apiKeyId: null, |
| 336 | }); |
| 337 | expect(await keyExists |
| 338 | const [repository] |
| 339 | .select() |
| 340 | .from(schema.repository |
| 341 | .where(eq(schema |
| 342 | expect(repository.defaultBranch |
| 343 | await expect( |
| 344 | dispatcher.settle(row |
| 345 | succeeded: true, |
| 346 | defaultBranch: null, |
| 347 | }), |
| 348 | ).rejects.toBeInstanceOf( |
| 349 | }); |
| 350 | |
| 351 | it('retries a retryable failure and fails a permanent one', |
| 352 | const row = |
| 353 | await dispatcher.settle |
| 354 | succeeded: false, |
| 355 | error: 'GitHub hiccup', |
| 356 | retryable: true, |
| 357 | }); |
| 358 | expect(await importRow |
| 359 | status: 'pending', |
| 360 | lastError: 'GitHub hiccup', |
| 361 | }); |
| 362 | |
| 363 | await db |
| 364 | .update(schema.repositoryImport |
| 365 | .set({ nextAttemptAt: |
| 366 | .where(eq(schema |
| 367 | await dispatcher.tick |
| 368 | const next = |
| 369 | await dispatcher.settle |
| 370 | succeeded: false, |
| 371 | error: 'Repository not found', |
| 372 | retryable: false, |
| 373 | }); |
| 374 | expect(await importRow |
| 375 | status: 'failed', |
| 376 | lastError: 'Repository not found', |
| 377 | }); |
| 378 | }); |
| 379 | |
| 380 | it('fails a retryable failure once attempts run out', |
| 381 | const row = |
| 382 | await db |
| 383 | .update(schema.repositoryImport |
| 384 | .set({ attempts: |
| 385 | .where(eq(schema |
| 386 | await dispatcher.settle |
| 387 | succeeded: false, |
| 388 | error: 'Still broken', |
| 389 | retryable: true, |
| 390 | }); |
| 391 | expect((await importRow |
| 392 | }); |
| 393 | }); |
| 394 | |
| 395 | describe('writing', |
| 396 | it('upserts releases by tag', |
| 397 | const release = |
| 398 | tagName: 'v1', |
| 399 | name: 'One', |
| 400 | body: null, |
| 401 | isDraft: false, |
| 402 | isPrerelease: false, |
| 403 | createdAt: '2024-01-01T00:00:00.000Z', |
| 404 | publishedAt: '2024-01-01T00:00:00.000Z', |
| 405 | }; |
| 406 | await writer.writeReleases |
| 407 | await writer.writeReleases |
| 408 | { ...release, |
| 409 | ]); |
| 410 | await writer.writeReleases |
| 411 | |
| 412 | const rows = |
| 413 | .select() |
| 414 | .from(schema.release |
| 415 | .where(eq(schema |
| 416 | expect(rows).toHaveLength |
| 417 | expect(rows[0]) |
| 418 | name: 'One, again', |
| 419 | authorId: schema.IMPORTER_USER_ID |
| 420 | }); |
| 421 | }); |
| 422 | |
| 423 | it('keeps numbers, credits authors and attaches pull requests', |
| 424 | await writer.writeIssues |
| 425 | issue, |
| 426 | { ...issue, |
| 427 | { |
| 428 | ...issue, |
| 429 | number: 6, |
| 430 | state: 'open', |
| 431 | closedAt: null, |
| 432 | labels: [], |
| 433 | pullRequest: { |
| 434 | ...pullRequest, |
| 435 | state: 'open', |
| 436 | mergeCommitSha: null, |
| 437 | mergedAt: null, |
| 438 | }, |
| 439 | }, |
| 440 | ]); |
| 441 | |
| 442 | const rows = |
| 443 | .select() |
| 444 | .from(schema.issue |
| 445 | .where(eq(schema |
| 446 | .orderBy(schema.issue |
| 447 | expect( |
| 448 | rows.map((row |
| 449 | ).toEqual([ |
| 450 | [3, 'closed', |
| 451 | [5, 'closed', |
| 452 | [6, 'closed', |
| 453 | ]); |
| 454 | expect(rows[0] |
| 455 | '_Opened by [@octocat](https://github.com/octocat) on GitHub._\n\nIt crashes', |
| 456 | ); |
| 457 | expect(rows[0] |
| 458 | expect(rows[2] |
| 459 | |
| 460 | const pulls = |
| 461 | .select() |
| 462 | .from(schema.pullRequest |
| 463 | .where(inArray(schema |
| 464 | expect(pulls.find |
| 465 | state: 'merged', |
| 466 | mergeCommitSha: 'a'.repeat |
| 467 | headRepositoryId: null, |
| 468 | }); |
| 469 | expect(pulls.find |
| 470 | 'closed', |
| 471 | ); |
| 472 | |
| 473 | const labels = |
| 474 | .select({ name: |
| 475 | .from(schema.issueLabel |
| 476 | .innerJoin(schema.label |
| 477 | .where(eq(schema |
| 478 | expect(labels).toEqual |
| 479 | }); |
| 480 | |
| 481 | it('keeps a same-repository head live', |
| 482 | await writer.writeIssues |
| 483 | { |
| 484 | ...issue, |
| 485 | state: 'open', |
| 486 | closedAt: null, |
| 487 | labels: [], |
| 488 | pullRequest: { |
| 489 | ...pullRequest, |
| 490 | state: 'open', |
| 491 | headInRepository: true, |
| 492 | mergeCommitSha: null, |
| 493 | mergedAt: null, |
| 494 | }, |
| 495 | }, |
| 496 | ]); |
| 497 | const [pull] |
| 498 | .select({ |
| 499 | state: schema.pullRequest |
| 500 | headRepositoryId: schema.pullRequest |
| 501 | }) |
| 502 | .from(schema.pullRequest |
| 503 | .innerJoin( |
| 504 | schema.issue, |
| 505 | eq(schema.issue |
| 506 | ) |
| 507 | .where(eq(schema |
| 508 | expect(pull).toEqual |
| 509 | }); |
| 510 | |
| 511 | it('deduplicates comment batches and starts over when the issue is sent again', |
| 512 | await writer.writeIssues |
| 513 | const comment = |
| 514 | githubId: 4_000_000_000, |
| 515 | issueNumber: 3, |
| 516 | authorLogin: 'hubot', |
| 517 | body: 'Same here', |
| 518 | createdAt: '2024-01-01T01:00:00.000Z', |
| 519 | updatedAt: '2024-01-01T01:00:00.000Z', |
| 520 | }; |
| 521 | await writer.writeComments |
| 522 | comment, |
| 523 | comment, |
| 524 | { ...comment, |
| 525 | { ...comment, |
| 526 | ]); |
| 527 | await writer.writeComments |
| 528 | await writer.writeComments |
| 529 | |
| 530 | const read = |
| 531 | const [row] |
| 532 | .select() |
| 533 | .from(schema.issue |
| 534 | .where( |
| 535 | and( |
| 536 | eq(schema.issue |
| 537 | eq(schema.issue |
| 538 | ), |
| 539 | ); |
| 540 | const comments = |
| 541 | .select() |
| 542 | .from(schema.issueComment |
| 543 | .where(eq(schema |
| 544 | return { row, |
| 545 | }; |
| 546 | |
| 547 | const before = |
| 548 | expect(before.comments |
| 549 | expect(before.comments |
| 550 | comment.githubId, |
| 551 | comment.githubId + |
| 552 | ]); |
| 553 | expect(before.row |
| 554 | expect(before.row |
| 555 | expect(before.comments |
| 556 | '_Posted by [@hubot](https://github.com/hubot) on GitHub._\n\nSame here', |
| 557 | ); |
| 558 | |
| 559 | await writer.writeIssues |
| 560 | const after = |
| 561 | expect(after.row |
| 562 | expect(after.comments |
| 563 | |
| 564 | await writer.writeComments |
| 565 | { ...comment, |
| 566 | ]); |
| 567 | expect((await read |
| 568 | }); |
| 569 | |
| 570 | it('writes nothing for an empty batch', |
| 571 | await writer.writeIssues |
| 572 | expect( |
| 573 | await db |
| 574 | .select() |
| 575 | .from(schema.issue |
| 576 | .where(eq(schema |
| 577 | ).toEqual([]); |
| 578 | }); |
| 579 | }); |
| 580 | |
| 581 | describe('the import flow', |
| 582 | const owner = |
| 583 | username: 'import_owner', |
| 584 | repo: 'repo', |
| 585 | requesterId: OWNER, |
| 586 | }; |
| 587 | |
| 588 | it('reports availability and the linked account', |
| 589 | expect(await imports |
| 590 | enabled: true, |
| 591 | connected: true, |
| 592 | }); |
| 593 | expect(await imports |
| 594 | enabled: true, |
| 595 | connected: false, |
| 596 | }); |
| 597 | }); |
| 598 | |
| 599 | it('lists repositories with the linked account only', |
| 600 | importer.mockResolvedValueOnce( |
| 601 | Response.json([ |
| 602 | { full_name: 'octo/repo', |
| 603 | ]), |
| 604 | ); |
| 605 | expect(await imports |
| 606 | repositories: [ |
| 607 | { fullName: 'octo/repo', |
| 608 | ], |
| 609 | }); |
| 610 | await expect(imports |
| 611 | GitHubNotConnectedError, |
| 612 | ); |
| 613 | }); |
| 614 | |
| 615 | it('starts an import for a readable repository', |
| 616 | importer.mockResolvedValueOnce(Response |
| 617 | await imports.start |
| 618 | expect(importer.mock |
| 619 | 'https://api.github.com/repos/octo/repo', |
| 620 | ); |
| 621 | expect((await importRow |
| 622 | await expect(assertNotImporting |
| 623 | RepositoryImportingError, |
| 624 | ); |
| 625 | }); |
| 626 | |
| 627 | it('refuses to start without configuration or a linked account', |
| 628 | const disabled = |
| 629 | db, |
| 630 | new ConfigService({}) |
| 631 | auth, |
| 632 | {} as RepositoriesService, |
| 633 | new RepositoryAccessService(db |
| 634 | dispatcher, |
| 635 | ); |
| 636 | await expect( |
| 637 | disabled.start({ |
| 638 | ).rejects.toBeInstanceOf( |
| 639 | await expect( |
| 640 | imports.start({ |
| 641 | ).rejects.toBeInstanceOf( |
| 642 | }); |
| 643 | |
| 644 | it('shows progress and retries a failed import', |
| 645 | await expect(imports |
| 646 | ImportNotFoundError, |
| 647 | ); |
| 648 | await expect(imports |
| 649 | ImportNotFoundError, |
| 650 | ); |
| 651 | |
| 652 | await startImport({ |
| 653 | status: 'failed', |
| 654 | attempts: MAX_IMPORT_ATTEMPTS, |
| 655 | lastError: 'boom', |
| 656 | }); |
| 657 | expect( |
| 658 | await imports.status |
| 659 | ).toMatchObject({ |
| 660 | status: 'failed', |
| 661 | lastError: 'boom', |
| 662 | source: 'octo/repo', |
| 663 | }); |
| 664 | await assertNotImporting(db |
| 665 | |
| 666 | await writer.writeIssues |
| 667 | await imports.retry |
| 668 | expect(await importRow |
| 669 | await expect(imports |
| 670 | ImportNotFailedError, |
| 671 | ); |
| 672 | }); |
| 673 | |
| 674 | it('refuses a retry after a local issue was created', |
| 675 | await startImport({ |
| 676 | await db.insert |
| 677 | repositoryId, |
| 678 | number: 1, |
| 679 | title: 'Local issue', |
| 680 | authorId: OWNER, |
| 681 | }); |
| 682 | const wake = |
| 683 | await expect(imports |
| 684 | ImportRetryWouldOverwriteError, |
| 685 | ); |
| 686 | expect(await importRow |
| 687 | status: 'failed', |
| 688 | attempts: 6, |
| 689 | lastError: 'boom', |
| 690 | }); |
| 691 | expect(wake).not |
| 692 | }); |
| 693 | |
| 694 | it('makes an issue being opened wait for a retry holding the import row, then refuses it', |
| 695 | await startImport({ |
| 696 | const retrying = |
| 697 | try { |
| 698 | await retrying.query |
| 699 | await retrying.query |
| 700 | 'select 1 from repository_import where repository_id = $1 for update', |
| 701 | [repositoryId], |
| 702 | ); |
| 703 | |
| 704 | let settled = |
| 705 | const opening = |
| 706 | .transaction((tx) |
| 707 | .finally(() => |
| 708 | settled = true; |
| 709 | }); |
| 710 | await new Promise |
| 711 | expect(settled).toBe |
| 712 | |
| 713 | await retrying.query |
| 714 | `update repository_import set status = 'pending' where repository_id = $1`, |
| 715 | [repositoryId], |
| 716 | ); |
| 717 | await retrying.query |
| 718 | await expect(opening |
| 719 | } finally { |
| 720 | retrying.release(); |
| 721 | } |
| 722 | }); |
| 723 | |
| 724 | it('retries only for a caller with GitHub linked', |
| 725 | await startImport({ |
| 726 | await db.delete |
| 727 | await expect(imports |
| 728 | GitHubNotConnectedError, |
| 729 | ); |
| 730 | }); |
| 731 | }); |
| 732 | }); |