| 1 | import { StaleAttemptError |
| 2 |
| 3 | const REQUEST_TIMEOUT_MS = 30_000; |
| 4 | // Backoff between tries of one callback: the API restarting must not cost the import, but a dead API must not hold it past its lease either. |
| 5 | const RETRY_DELAYS_MS = [1_000, 5_000, 20_000]; |
| 6 |
| 7 | export type ImportedLabel = { |
| 8 | name: string; |
| 9 | color: string; |
| 10 | description: string | null; |
| 11 | }; |
| 12 |
| 13 | export type ImportedPullRequest = { |
| 14 | state: "open" | "closed" | "merged"; |
| 15 | draft: boolean; |
| 16 | baseRef: string; |
| 17 | headRef: string; |
| 18 | headSha: string; |
| 19 | headInRepository: boolean; |
| 20 | mergeCommitSha: string | null; |
| 21 | mergedAt: string | null; |
| 22 | }; |
| 23 |
| 24 | export type ImportedIssue = { |
| 25 | number: number; |
| 26 | title: string; |
| 27 | body: string | null; |
| 28 | authorLogin: string; |
| 29 | state: "open" | "closed"; |
| 30 | createdAt: string; |
| 31 | updatedAt: string; |
| 32 | closedAt: string | null; |
| 33 | labels: ImportedLabel[]; |
| 34 | pullRequest?: ImportedPullRequest; |
| 35 | }; |
| 36 |
| 37 | export type ImportedRelease = { |
| 38 | tagName: string; |
| 39 | name: string | null; |
| 40 | body: string | null; |
| 41 | isDraft: boolean; |
| 42 | isPrerelease: boolean; |
| 43 | createdAt: string; |
| 44 | publishedAt: string | null; |
| 45 | }; |
| 46 |
| 47 | export type ImportedComment = { |
| 48 | githubId: number; |
| 49 | issueNumber: number; |
| 50 | authorLogin: string; |
| 51 | body: string; |
| 52 | createdAt: string; |
| 53 | updatedAt: string; |
| 54 | }; |
| 55 |
| 56 | export type Outcome = |
| 57 | | { succeeded: true; defaultBranch: string } |
| 58 | | { succeeded: false; error: string; retryable: boolean }; |
| 59 |
| 60 | /** Postgres cannot store U+0000 in text, and GitHub text can carry it, such as a pasted error message about a binary file. */ |
| 61 | function withoutNul(_key: string, value: unknown) { |
| 62 | return typeof value === "string" ? value.replaceAll("\0", "\uFFFD") : value; |
| 63 | } |
| 64 |
| 65 | /** The API's callbacks for one attempt. Every call carries the attempt, and a 409 means the API moved on. */ |
| 66 | export class GhostCallbacks { |
| 67 | constructor( |
| 68 | private readonly apiUrl: string, |
| 69 | private readonly secret: string, |
| 70 | private readonly importId: string, |
| 71 | private readonly attempt: string, |
| 72 | private readonly fetchImpl: typeof fetch = fetch, |
| 73 | private readonly sleep: (ms: number) => Promise<void> = Bun.sleep, |
| 74 | ) {} |
| 75 |
| 76 | heartbeat() { |
| 77 | return this.post("heartbeat", {}); |
| 78 | } |
| 79 |
| 80 | releases(releases: ImportedRelease[]) { |
| 81 | return this.post("releases", { releases }); |
| 82 | } |
| 83 |
| 84 | issues(issues: ImportedIssue[]) { |
| 85 | return this.post("issues", { issues }); |
| 86 | } |
| 87 |
| 88 | comments(comments: ImportedComment[]) { |
| 89 | return this.post("comments", { comments }); |
| 90 | } |
| 91 |
| 92 | finish(outcome: Outcome) { |
| 93 | return this.post("finish", outcome); |
| 94 | } |
| 95 |
| 96 | private async post(path: string, body: object) { |
| 97 | const url = new URL( |
| 98 | `/api/internal/imports/${this.importId}/${path}`, |
| 99 | this.apiUrl, |
| 100 | ); |
| 101 | const payload = JSON.stringify( |
| 102 | { attempt: this.attempt, ...body }, |
| 103 | withoutNul, |
| 104 | ); |
| 105 |
| 106 | for (let attempt = 0; ; attempt++) { |
| 107 | const response = await this.fetchImpl(url, { |
| 108 | method: "POST", |
| 109 | headers: { |
| 110 | "Content-Type": "application/json", |
| 111 | Authorization: `Bearer ${this.secret}`, |
| 112 | }, |
| 113 | body: payload, |
| 114 | signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), |
| 115 | }).catch((error: unknown) => error as Error); |
| 116 |
| 117 | if (response instanceof Response) { |
| 118 | if (response.ok) return; |
| 119 | if (response.status === 409) throw new StaleAttemptError(); |
| 120 | if (response.status < 500) { |
| 121 | throw new Error( |
| 122 | `The API refused ${path} with ${response.status}: ${await response.text()}`, |
| 123 | ); |
| 124 | } |
| 125 | } |
| 126 |
| 127 | const delay = RETRY_DELAYS_MS[attempt]; |
| 128 | if (delay === undefined) { |
| 129 | const reason = |
| 130 | response instanceof Response |
| 131 | ? `status ${response.status}` |
| 132 | : response.message; |
| 133 | throw new Error(`The API did not take ${path}: ${reason}`); |
| 134 | } |
| 135 | await this.sleep(delay); |
| 136 | } |
| 137 | } |
| 138 | } |