projects/release/upstream-cache.js

// @ts-check

// Shared content-addressed cache helpers and bounded response reader for upstream Fluxer files under
// projects/release/.cache/upstream/
import { createHash, randomUUID } from "node:crypto"
import { mkdir, readFile, readdir, rename, rm, writeFile } from "node:fs/promises"
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"

// Shared gitignored root for cached upstream files: Top-level 40-hex Git blob IDs alongside sha256/<64-hex> files
export const upstreamCachePath = fileURLToPath(new URL("./.cache/upstream/", import.meta.url))
export const sha256Pattern = /^[a-f0-9]{64}$/
export const defaultMaxBytes = 32 * 1024 * 1024

/** @param {Buffer | Uint8Array} bytes */
export const sha256Hex = (bytes) => createHash("sha256").update(bytes).digest("hex")

/**
 * Folder holding SHA-256 content-addressed copies beneath an upstream cache root
 * @param {string} [root]
 */
export const sha256StoreDir = (root = upstreamCachePath) => join(root, "sha256")

/**
 * Path to one SHA-256 cached entry beneath an upstream cache root
 * @param {string} root
 * @param {string} hash
 */
export function sha256EntryPath(root, hash) {
    if (!sha256Pattern.test(hash)) throw new Error(`Invalid SHA-256 cache key: ${hash}`)
    return join(sha256StoreDir(root), hash)
}

/**
 * Writes bytes to a unique temporary file beside targetPath and renames it into place, so concurrent writers or an
 * interrupted run never leave a partial file at targetPath
 * @param {string} targetPath
 * @param {Buffer | Uint8Array} bytes
 */
export async function writeFileAtomic(targetPath, bytes) {
    await mkdir(dirname(targetPath), { recursive: true })
    const partial = `${targetPath}.${process.pid}.${randomUUID()}.partial`
    try {
        await writeFile(partial, bytes)
        await rename(partial, targetPath)
    } catch (error) {
        await rm(partial, { force: true }).catch(() => undefined)
        throw error
    }
}

/**
 * Reads a SHA-256 cached file only when its bytes still hash to expectedSha256
 * @param {string} root
 * @param {string} expectedSha256
 * @returns {Promise<{ bytes: Buffer, corrupted: false } | { bytes: undefined, corrupted: boolean }>}
 */
export async function readVerifiedSha256(root, expectedSha256) {
    const entry = sha256EntryPath(root, expectedSha256)
    const bytes = await readFile(entry).catch(() => undefined)
    if (!bytes) return { bytes: undefined, corrupted: false }
    if (sha256Hex(bytes) !== expectedSha256) return { bytes: undefined, corrupted: true }
    return { bytes, corrupted: false }
}

/**
 * Verifies that bytes match expectedSha256 and stores them atomically in the SHA-256 cache store
 * @param {string} root
 * @param {string} expectedSha256
 * @param {Buffer | Uint8Array} bytes
 */
export async function writeVerifiedSha256(root, expectedSha256, bytes) {
    const actual = sha256Hex(bytes)
    if (actual !== expectedSha256)
        throw new Error(`Upstream bytes hash to ${actual}, not the expected ${expectedSha256}`)
    await writeFileAtomic(sha256EntryPath(root, expectedSha256), bytes)
}

/**
 * Removes SHA-256 cache entries not in keepHashes, leaving non-hash entries such as active partial files and the
 * parent folder's Git blob copies untouched
 * @param {string} root
 * @param {ReadonlySet<string>} keepHashes
 */
export async function pruneSha256Cache(root, keepHashes) {
    const directory = sha256StoreDir(root)
    for (const name of await readdir(directory).catch(() => []))
        if (sha256Pattern.test(name) && !keepHashes.has(name)) await rm(join(directory, name), { force: true })
}

/**
 * Reads an HTTP response body while enforcing a strict streaming byte cap, cancelling the stream immediately when the
 * declared Content-Length or streamed chunks exceed limit
 * @param {Response} response
 * @param {number} [limit]
 * @returns {Promise<Buffer>}
 */
export async function readLimitedResponse(response, limit = defaultMaxBytes) {
    const contentLength = response.headers.get("content-length")
    if (contentLength !== null && /^\d+$/.test(contentLength.trim())) {
        const declared = Number(contentLength.trim())
        if (declared > limit) {
            await response.body?.cancel()
            throw new Error("Upstream document exceeds the byte limit")
        }
    }
    if (!response.body) {
        const bytes = Buffer.from(await response.arrayBuffer())
        if (bytes.length > limit) throw new Error("Upstream document exceeds the byte limit")
        return bytes
    }
    const reader = response.body.getReader()
    /** @type {Uint8Array[]} */
    const chunks = []
    let total = 0
    try {
        for (;;) {
            const { done, value } = await reader.read()
            if (done) break
            total += value.byteLength
            if (total > limit) {
                await reader.cancel()
                throw new Error("Upstream document exceeds the byte limit")
            }
            chunks.push(value)
        }
    } finally {
        reader.releaseLock()
    }
    return Buffer.concat(chunks, total)
}