( endpoints: string[], tryEndpoint: (endpoint: string) => Promise<T>, now: () => number = Date.now, )
| 53 | }; |
| 54 | |
| 55 | export async function selectFastestSuccessfulEndpoint<T>( |
| 56 | endpoints: string[], |
| 57 | tryEndpoint: (endpoint: string) => Promise<T>, |
| 58 | now: () => number = Date.now, |
| 59 | ): Promise<{ |
| 60 | successes: EndpointAttemptSuccess<T>[]; |
| 61 | failures: EndpointAttemptFailure[]; |
| 62 | }> { |
| 63 | const attempts = await Promise.all( |
| 64 | endpoints.map(async endpoint => { |
| 65 | const start = now(); |
| 66 | try { |
| 67 | const value = await tryEndpoint(endpoint); |
| 68 | return { |
| 69 | ok: true as const, |
| 70 | endpoint, |
| 71 | value, |
| 72 | duration: now() - start, |
| 73 | }; |
| 74 | } catch (error) { |
| 75 | return { |
| 76 | ok: false as const, |
| 77 | endpoint, |
| 78 | error: normalizeError(error), |
| 79 | }; |
| 80 | } |
| 81 | }), |
| 82 | ); |
| 83 | |
| 84 | const successes: EndpointAttemptSuccess<T>[] = []; |
| 85 | const failures: EndpointAttemptFailure[] = []; |
| 86 | |
| 87 | for (const attempt of attempts) { |
| 88 | if (attempt.ok) { |
| 89 | successes.push({ |
| 90 | endpoint: attempt.endpoint, |
| 91 | value: attempt.value, |
| 92 | duration: attempt.duration, |
| 93 | }); |
| 94 | continue; |
| 95 | } |
| 96 | |
| 97 | failures.push({ |
| 98 | endpoint: attempt.endpoint, |
| 99 | error: attempt.error, |
| 100 | }); |
| 101 | } |
| 102 | |
| 103 | successes.sort((left, right) => left.duration - right.duration); |
| 104 | |
| 105 | return { |
| 106 | successes, |
| 107 | failures, |
| 108 | }; |
| 109 | } |
| 110 | |
| 111 | export async function executeEndpointFallback<T>({ |
| 112 | configuredEndpoints, |
no test coverage detected