| 1 | import type { ConfigService } from '@nestjs/config'; |
| 2 | |
| 3 | import { ImporterUnavailableError } |
| 4 | |
| 5 | export type GitHubImportConfig |
| 6 | importerUrl: string |
| 7 | importerSecret: string |
| 8 | github: { |
| 9 | }; |
| 10 | |
| 11 | export type ImportJob |
| 12 | importId: string |
| 13 | attempt: string |
| 14 | source: string |
| 15 | destination: string |
| 16 | githubToken: string |
| 17 | ghostToken: string |
| 18 | }; |
| 19 | |
| 20 | const DISPATCH_TIMEOUT_MS = 10_000 |
| 21 | const RETRY_BASE_MS = 30_000 |
| 22 | const RETRY_CAP_MS = 30 |
| 23 | |
| 24 | /** Imports run only with all four set: the importer to hand jobs to, and the GitHub OAuth app that supplies a token for them. */ |
| 25 | export function githubImportConfig( |
| 26 | config: ConfigService |
| 27 | ): GitHubImportConfig | |
| 28 | const importerUrl = |
| 29 | const importerSecret = |
| 30 | const clientId = |
| 31 | const clientSecret = |
| 32 | if (!importerUrl || |
| 33 | return null; |
| 34 | } |
| 35 | return { importerUrl, |
| 36 | } |
| 37 | |
| 38 | /** Exponential with full jitter, so importers recovering together are not hit by every waiting import at once. */ |
| 39 | export function retryDelayMs(attempt |
| 40 | const ceiling = |
| 41 | return Math.round |
| 42 | } |
| 43 | |
| 44 | export async function dispatchToImporter |
| 45 | { importerUrl, importerSecret |
| 46 | job: ImportJob |
| 47 | ) { |
| 48 | const response = |
| 49 | method: 'POST', |
| 50 | headers: { |
| 51 | 'Content-Type': 'application/json', |
| 52 | Authorization: `Bearer ${importerSecret |
| 53 | }, |
| 54 | body: JSON.stringify |
| 55 | signal: AbortSignal.timeout |
| 56 | }).catch((cause |
| 57 | throw new ImporterUnavailableError( |
| 58 | }); |
| 59 | |
| 60 | if (!response.ok |
| 61 | throw new ImporterUnavailableError( |
| 62 | cause: new Error |
| 63 | `importer answered ${response.status |
| 64 | ), |
| 65 | }); |
| 66 | } |
| 67 | } |