| 6 | * Completion data arrives on a transferred port; the bounded wait also handles |
| 7 | * worker startup failures whose error events cannot run while this thread blocks. |
| 8 | */ |
| 9 |
| 10 | import { Worker, MessageChannel, receiveMessageOnPort } from "node:worker_threads"; |
| 11 | import process from "node:process"; |
| 12 | import { fileURLToPath } from "node:url"; |
| 13 | import { readCache } from "./cache.ts"; |
| 14 | import type { CacheEntry } from "./cache.ts"; |
| 15 | import { resolveLockRedirects, verifyModuleLock } from "./lock.ts"; |
| 16 | import { getFetchTimeoutMs, MAX_REDIRECTS, isHttpUrl } from "./constants.ts"; |
| 17 | import type { FetchOptions } from "./fetch.ts"; |
| 18 |
| 19 | const authTokens = process.env.DENO_AUTH_TOKENS; |
| 20 | let worker: Worker | null = null; |
| 21 |
| 22 | function getWorker(): Worker { |
| 23 | if (!worker) { |
| 24 | // Resolve relative to this module so source .ts and published .js both work. |
| 25 | const extension = import.meta.url.endsWith(".ts") ? ".ts" : ".js"; |
| 26 | const path = fileURLToPath(new URL(`./sync-fetch-worker${extension}`, import.meta.url)); |
| 27 | // Authentication is configured at registration, even if this worker starts |
| 28 | // lazily or restarts after a timeout. Preserve an unset variable as unset. |
| 29 | const env = { ...process.env }; |
| 30 | if (authTokens === undefined) delete env.DENO_AUTH_TOKENS; |
| 31 | else env.DENO_AUTH_TOKENS = authTokens; |
| 32 | // Hook and eval flags must never be inherited by the network worker. |
| 33 | const current = new Worker(path, { execArgv: [], env }); |
| 34 | current.unref(); |
| 35 | const reset = (): void => { if (worker === current) worker = null; }; |
| 36 | current.on("error", reset); |
| 37 | current.on("exit", reset); |
| 38 | worker = current; |
| 39 | } |
| 40 | return worker; |
| 41 | } |
| 42 |
| 43 | function discardWorker(current: Worker): void { |
| 44 | if (worker === current) worker = null; |
| 45 | void current.terminate(); |
| 46 | } |
| 47 |
| 48 | type WorkerResponse = { entry: CacheEntry } | { error: string }; |
| 49 |
| 50 | /** Fetch synchronously from verified disk cache or the network worker. */ |
| 51 | export function fetchModuleSync(url: string, options: FetchOptions = {}): CacheEntry { |
| 52 | const timeoutMs = getFetchTimeoutMs(options.timeoutMs); |
| 53 | const headers = [...new Headers(options.headers)]; |
| 54 | url = new URL(url).href; |
| 55 | if (!isHttpUrl(url)) throw new TypeError(`Expected an HTTP(S) module URL: ${url}`); |
| 56 | if (process.env.URL_IMPORT_RELOAD !== "1") { |
| 57 | const lockedChain = resolveLockRedirects(url); |
| 58 | const cached = readCache(lockedChain.at(-1)!); |
| 59 | if (cached) { |
| 60 | const entry = { ...cached, url, redirectChain: [...lockedChain.slice(0, -1), ...cached.redirectChain] }; |
| 61 | if (entry.redirectChain.length > MAX_REDIRECTS + 1) throw new Error(`Too many redirects fetching ${url}`); |
| 62 | verifyModuleLock(entry); |
| 63 | return entry; |
| 64 | } |
| 65 | } |
| 66 |
| 67 | const current = getWorker(); |
| 68 | const signal = new Int32Array(new SharedArrayBuffer(4)); |
| 69 | const { port1, port2 } = new MessageChannel(); |
| 70 | try { |
| 71 | try { |
| 72 | current.postMessage({ |
| 73 | url, |
| 74 | options: { timeoutMs, headers }, |
| 75 | signal: signal.buffer, |
| 76 | port: port2, |
| 77 | }, [port2]); |
| 78 | } catch (error) { |
| 79 | discardWorker(current); |
| 80 | throw error; |
| 81 | } |
| 82 | // Worker error/exit callbacks cannot execute during Atomics.wait. On timeout, |
| 83 | // clear the cached worker immediately so a subsequent request can restart it. |
| 84 | if (Atomics.wait(signal, 0, 0, timeoutMs) === "timed-out") { |
| 85 | discardWorker(current); |
| 86 | throw new Error(`Timed out fetching ${url}`); |
| 87 | } |
| 88 | const message = receiveMessageOnPort(port1); |
| 89 | if (!message) { |
| 90 | discardWorker(current); |
| 91 | throw new Error(`No response from fetch worker for ${url}`); |
| 92 | } |
| 93 | const response = message.message as WorkerResponse; |
| 94 | if ("error" in response) throw new Error(`Error fetching ${url}: ${response.error}`); |
| 95 | verifyModuleLock(response.entry); |
| 96 | return response.entry; |
| 97 | } finally { |
| 98 | port1.close(); |
| 99 | port2.close(); |
| 100 | } |
| 101 | } |
| 102 |