| 6 |
| 7 | import process from "node:process"; |
| 8 | import { createHash, randomUUID } from "node:crypto"; |
| 9 | import { mkdirSync, readFileSync, readdirSync, realpathSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"; |
| 10 | import { basename, dirname, join, resolve } from "node:path"; |
| 11 | import { writeFileAtomicSync } from "./cache.ts"; |
| 12 | import type { CacheEntry, ModuleSource } from "./cache.ts"; |
| 13 | import { MAX_REDIRECTS, isHttpUrl } from "./constants.ts"; |
| 14 |
| 15 | const LOCK_VERSION = "5"; |
| 16 | const lockPath = process.env.URL_IMPORT_LOCK ? resolve(process.env.URL_IMPORT_LOCK) : null; |
| 17 | // As in Deno --no-lock, frozen has no effect unless a lock file is enabled. |
| 18 | const frozen = lockPath !== null && process.env.URL_IMPORT_FROZEN === "1"; |
| 19 | const lockWait = new Int32Array(new SharedArrayBuffer(4)); |
| 20 |
| 21 | interface LockFileData { |
| 22 | version: string; |
| 23 | redirects: Record<string, string>; |
| 24 | remote: Record<string, string>; |
| 25 | [key: string]: unknown; |
| 26 | } |
| 27 |
| 28 | export function hashSource(source: ModuleSource): string { |
| 29 | return createHash("sha256").update(source).digest("hex"); |
| 30 | } |
| 31 |
| 32 | function isRecord(value: unknown): value is Record<string, unknown> { |
| 33 | return typeof value === "object" && value !== null && !Array.isArray(value); |
| 34 | } |
| 35 |
| 36 | function isStringRecord(value: unknown): value is Record<string, string> { |
| 37 | return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string"); |
| 38 | } |
| 39 |
| 40 | function loadLockFile(path: string): LockFileData { |
| 41 | let text: string; |
| 42 | try { |
| 43 | text = readFileSync(path, "utf8"); |
| 44 | } catch (error) { |
| 45 | if (error instanceof Error && "code" in error && error.code === "ENOENT") { |
| 46 | return { version: LOCK_VERSION, redirects: {}, remote: {} }; |
| 47 | } |
| 48 | throw error; |
| 49 | } |
| 50 | const data: unknown = JSON.parse(text); |
| 51 | if (!isRecord(data) || (data.version !== undefined && typeof data.version !== "string") || |
| 52 | (data.redirects !== undefined && !isStringRecord(data.redirects)) || |
| 53 | (data.remote !== undefined && !isStringRecord(data.remote))) { |
| 54 | throw new Error(`Invalid lock file: ${path}`); |
| 55 | } |
| 56 | return { |
| 57 | ...data, |
| 58 | version: typeof data.version === "string" ? data.version : LOCK_VERSION, |
| 59 | redirects: isStringRecord(data.redirects) ? data.redirects : {}, |
| 60 | remote: isStringRecord(data.remote) ? data.remote : {}, |
| 61 | }; |
| 62 | } |
| 63 |
| 64 | /** Only reclaim a known owner after its process has exited; never steal a live lock. */ |
| 65 | function removeDeadOwner(directory: string): void { |
| 66 | try { |
| 67 | const owners = readdirSync(directory); |
| 68 | if (owners.length !== 1) return; |
| 69 | const owner = owners[0]!; |
| 70 | const match = /^owner-(\d+)-/.exec(owner); |
| 71 | if (!match) return; |
| 72 | try { |
| 73 | process.kill(Number(match[1]), 0); |
| 74 | return; |
| 75 | } catch (error) { |
| 76 | if (!(error instanceof Error && "code" in error && error.code === "ESRCH")) return; |
| 77 | } |
| 78 | // Unlink the specific owner first. Competing reclaimers cannot then remove |
| 79 | // a newly acquired directory because only one can unlink this owner file. |
| 80 | unlinkSync(join(directory, owner)); |
| 81 | rmdirSync(directory); |
| 82 | } catch (error) { |
| 83 | if (!(error instanceof Error && "code" in error && (error.code === "ENOENT" || error.code === "ENOTEMPTY"))) throw error; |
| 84 | } |
| 85 | } |
| 86 |
| 87 | /** |
| 88 | * mkdir is the cross-process exclusion point. The transaction contains only |
| 89 | * synchronous filesystem operations, so a worker cannot yield while owning it. |
| 90 | * A bounded wait also reports abandoned empty locks instead of hanging forever. |
| 91 | */ |
| 92 | function acquireLock(path: string): () => void { |
| 93 | const directory = `${path}.lock`; |
| 94 | const owner = join(directory, `owner-${process.pid}-${randomUUID()}`); |
| 95 | const deadline = Date.now() + 15_000; |
| 96 | while (true) { |
| 97 | try { |
| 98 | mkdirSync(directory, { mode: 0o700 }); |
| 99 | try { |
| 100 | writeFileSync(owner, "", { flag: "wx", mode: 0o600 }); |
| 101 | } catch (error) { |
| 102 | rmdirSync(directory); |
| 103 | throw error; |
| 104 | } |
| 105 | return () => { |
| 106 | unlinkSync(owner); |
| 107 | rmdirSync(directory); |
| 108 | }; |
| 109 | } catch (error) { |
| 110 | if (!(error instanceof Error && "code" in error && error.code === "EEXIST")) throw error; |
| 111 | if (Date.now() >= deadline) throw new Error(`Timed out waiting to update lock file ${path}`); |
| 112 | removeDeadOwner(directory); |
| 113 | Atomics.wait(lockWait, 0, 0, 10); |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 |
| 118 | function canonicalLockPath(path: string): string { |
| 119 | try { |
| 120 | return realpathSync(path); |
| 121 | } catch (error) { |
| 122 | if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error; |
| 123 | return join(realpathSync(dirname(path)), basename(path)); |
| 124 | } |
| 125 | } |
| 126 |
| 127 | function sortedRecord(record: Record<string, string>): Record<string, string> { |
| 128 | return Object.fromEntries(Object.keys(record).sort().map((key) => [key, record[key]!])); |
| 129 | } |
| 130 |
| 131 | /** Reload inside the filesystem lock so main-thread and worker snapshots cannot diverge. */ |
| 132 | function updateLock(update: (data: LockFileData) => void): void { |
| 133 | if (!lockPath) return; |
| 134 | if (frozen) { |
| 135 | update(loadLockFile(lockPath)); |
| 136 | return; |
| 137 | } |
| 138 |
| 139 | mkdirSync(dirname(lockPath), { recursive: true }); |
| 140 | // Deno follows lockfile symlinks. All aliases must lock, read and replace the |
| 141 | // same target, not independently lock the names of their symlinks. |
| 142 | const target = canonicalLockPath(lockPath); |
| 143 | const release = acquireLock(target); |
| 144 | try { |
| 145 | const data = loadLockFile(target); |
| 146 | const previous = JSON.stringify(data); |
| 147 | update(data); |
| 148 | if (JSON.stringify(data) !== previous) { |
| 149 | const { version, redirects, remote, ...preserved } = data; |
| 150 | const output = { |
| 151 | version, |
| 152 | ...(Object.keys(redirects).length ? { redirects: sortedRecord(redirects) } : {}), |
| 153 | ...(Object.keys(remote).length ? { remote: sortedRecord(remote) } : {}), |
| 154 | ...preserved, |
| 155 | }; |
| 156 | writeFileAtomicSync(target, JSON.stringify(output, null, 2) + "\n"); |
| 157 | } |
| 158 | } finally { |
| 159 | release(); |
| 160 | } |
| 161 | } |
| 162 |
| 163 | function requireMutableLock(): void { |
| 164 | if (frozen) throw new Error("The lockfile is out of date. Rerun without --frozen and with URL_IMPORT_FROZEN=0 to update it."); |
| 165 | } |
| 166 |
| 167 | function normalizeUrl(url: string): string { |
| 168 | return new URL(url).href; |
| 169 | } |
| 170 |
| 171 | /** Deno seeds its module graph with recorded redirects, even when reloading. */ |
| 172 | export function resolveLockRedirects(url: string): string[] { |
| 173 | const chain = [normalizeUrl(url)]; |
| 174 | if (!lockPath) return chain; |
| 175 | const { redirects } = loadLockFile(lockPath); |
| 176 | while (true) { |
| 177 | const target = redirects[chain.at(-1)!]; |
| 178 | if (target === undefined) return chain; |
| 179 | if (chain.length > MAX_REDIRECTS) throw new Error(`Too many locked redirects for ${url}`); |
| 180 | const normalized = normalizeUrl(target); |
| 181 | if (!isHttpUrl(normalized)) throw new TypeError(`Unsupported locked redirect URL: ${normalized}`); |
| 182 | if (chain.includes(normalized)) throw new Error(`Circular locked redirect for ${url}`); |
| 183 | chain.push(normalized); |
| 184 | } |
| 185 | } |
| 186 |
| 187 | function verifySource(data: LockFileData, url: string, source: ModuleSource): void { |
| 188 | const key = normalizeUrl(url); |
| 189 | const actual = hashSource(source); |
| 190 | const expected = data.remote[key]; |
| 191 | if (expected !== undefined && expected !== actual) { |
| 192 | throw new Error(`Integrity check failed for ${key}\nActual: ${actual}\nExpected: ${expected}`); |
| 193 | } |
| 194 | if (expected === undefined) { |
| 195 | requireMutableLock(); |
| 196 | data.remote[key] = actual; |
| 197 | } |
| 198 | } |
| 199 |
| 200 | function verifyRedirect(data: LockFileData, from: string, to: string): void { |
| 201 | const source = normalizeUrl(from); |
| 202 | const target = normalizeUrl(to); |
| 203 | const expected = data.redirects[source]; |
| 204 | if (source === target) { |
| 205 | if (expected !== undefined) { |
| 206 | requireMutableLock(); |
| 207 | delete data.redirects[source]; |
| 208 | } |
| 209 | } else if (expected !== target) { |
| 210 | requireMutableLock(); |
| 211 | data.redirects[source] = target; |
| 212 | } |
| 213 | } |
| 214 |
| 215 | export function isLockEnabled(): boolean { |
| 216 | return lockPath !== null; |
| 217 | } |
| 218 |
| 219 | /** Verify a fetched module's source against its recorded SHA-256 hash. */ |
| 220 | export function verifyLock(url: string, source: ModuleSource): void { |
| 221 | updateLock((data) => verifySource(data, url, source)); |
| 222 | } |
| 223 |
| 224 | /** Record or verify one redirect hop, keeping Deno's original-to-next layout. */ |
| 225 | export function recordRedirect(from: string, to: string): void { |
| 226 | updateLock((data) => verifyRedirect(data, from, to)); |
| 227 | } |
| 228 |
| 229 | /** Check the source and every redirect as one transaction before publishing a cache entry. */ |
| 230 | export function verifyModuleLock(entry: CacheEntry): void { |
| 231 | updateLock((data) => { |
| 232 | verifySource(data, entry.finalUrl, entry.source); |
| 233 | for (let index = 0; index < entry.redirectChain.length - 1; index++) { |
| 234 | verifyRedirect(data, entry.redirectChain[index]!, entry.redirectChain[index + 1]!); |
| 235 | } |
| 236 | verifyRedirect(data, entry.finalUrl, entry.finalUrl); |
| 237 | }); |
| 238 | } |
| 239 |