| 1 | import { StatusError } from 'itty-router'; |
| 2 | |
| 3 | export const updateZip = async (tag: string, env: Env) => { |
| 4 | // Try calling download worker |
| 5 | const req = new Request(`https://download.fontsource.org/${tag}`, { |
| 6 | method: 'POST', |
| 7 | headers: { |
| 8 | Authorization: `Bearer ${env.UPLOAD_KEY}`, |
| 9 | }, |
| 10 | }); |
| 11 | |
| 12 | const resp = await fetch(req); |
| 13 | if (!resp.ok) { |
| 14 | const error = await resp.text(); |
| 15 | |
| 16 | if (resp.status === 524) { |
| 17 | throw new StatusError( |
| 18 | resp.status, |
| 19 | 'Timeout from download worker. Please try again later as the package may be still downloading to our servers.', |
| 20 | ); |
| 21 | } |
| 22 | |
| 23 | throw new StatusError( |
| 24 | resp.status, |
| 25 | `Bad response from download worker. ${error}`, |
| 26 | ); |
| 27 | } |
| 28 | |
| 29 | // Check again if download.zip exists in bucket |
| 30 | let retries = 0; |
| 31 | let zip = await env.FONTS.get(`${tag}/download.zip`); |
| 32 | while (!zip && retries < 3) { |
| 33 | zip = await env.FONTS.get(`${tag}/download.zip`); |
| 34 | retries++; |
| 35 | // Exponential backoff |
| 36 | await new Promise((resolve) => setTimeout(resolve, retries * 300)); |
| 37 | } |
| 38 | |
| 39 | if (!zip) { |
| 40 | throw new StatusError( |
| 41 | 500, |
| 42 | 'Internal Server Error. Failed to update zip file.', |
| 43 | ); |
| 44 | } |
| 45 | |
| 46 | return zip; |
| 47 | }; |
| 48 | |
| 49 | export const updateFile = async (tag: string, file: string, env: Env) => { |
| 50 | // Try calling download worker |