|
| 1 | +import got, { type OptionsOfTextResponseBody, type Method } from 'got' |
| 2 | +import { Failbot, HTTPBackend } from '@github/failbot' |
| 3 | + |
| 4 | +const HAYSTACK_APP = 'docs' |
| 5 | + |
| 6 | +async function retryingGot(input: RequestInfo | URL, init?: RequestInit): Promise<Response> { |
| 7 | + const url = typeof input === 'string' ? input : input.toString() |
| 8 | + |
| 9 | + // Extract body from fetch init for got options |
| 10 | + const gotOptions: OptionsOfTextResponseBody = { |
| 11 | + method: (init?.method as Method) || 'GET', |
| 12 | + body: typeof init?.body === 'string' ? init.body : undefined, |
| 13 | + headers: init?.headers as Record<string, string> | undefined, |
| 14 | + // With the timeout at 3000 (milliseconds) and the retry.limit |
| 15 | + // at 4 (times), the total worst-case is: |
| 16 | + // 3000 * 4 + 1000 + 2000 + 3000 + 4000 + 8000 = 30 seconds |
| 17 | + timeout: { |
| 18 | + response: 3000, |
| 19 | + }, |
| 20 | + retry: { |
| 21 | + // This means it will wait... |
| 22 | + // 1. 1000ms |
| 23 | + // 2. 2000ms |
| 24 | + // 3. 4000ms |
| 25 | + // 4. 8000ms |
| 26 | + // 5. give up! |
| 27 | + // |
| 28 | + // From the documentation: |
| 29 | + // |
| 30 | + // Delays between retries counts with function |
| 31 | + // 1000 * Math.pow(2, retry - 1) + Math.random() * 100, |
| 32 | + // where retry is attempt number (starts from 1). |
| 33 | + // |
| 34 | + limit: 4, |
| 35 | + }, |
| 36 | + } |
| 37 | + |
| 38 | + const gotResponse = await got(url, gotOptions) |
| 39 | + |
| 40 | + // Convert got response to fetch-compatible Response |
| 41 | + return new Response(gotResponse.body, { |
| 42 | + status: gotResponse.statusCode, |
| 43 | + statusText: gotResponse.statusMessage, |
| 44 | + headers: gotResponse.headers as HeadersInit, |
| 45 | + }) |
| 46 | +} |
| 47 | + |
| 48 | +export function report(error: Error, metadata?: Record<string, unknown>) { |
| 49 | + // If there's no HAYSTACK_URL set, bail early |
| 50 | + if (!process.env.HAYSTACK_URL) { |
| 51 | + return |
| 52 | + } |
| 53 | + |
| 54 | + const backends = [ |
| 55 | + new HTTPBackend({ |
| 56 | + haystackURL: process.env.HAYSTACK_URL, |
| 57 | + fetchFn: retryingGot, |
| 58 | + }), |
| 59 | + ] |
| 60 | + const failbot = new Failbot({ |
| 61 | + app: HAYSTACK_APP, |
| 62 | + backends, |
| 63 | + }) |
| 64 | + |
| 65 | + return failbot.report(error, metadata) |
| 66 | +} |
| 67 | + |
| 68 | +// Kept for legacy so you can continue to do: |
| 69 | +// |
| 70 | +// import FailBot from './lib/failbot' |
| 71 | +// ... |
| 72 | +// FailBot.report(myError) |
| 73 | +// |
| 74 | +export default { |
| 75 | + report, |
| 76 | +} |
0 commit comments