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