projects/web/scripts/docs/fluxer-source.mjs

// Reads the Fluxer files the endpoint map needs at the commit projects/release/upstream/manifest.json pins: The OpenAPI
// document, and the docs site's config and HTTP API pages that the manifest lists as endpointDocs. Every file is checked
// against the SHA-256 hash the manifest pins, whether it was downloaded or cached, so a cache cannot change what a build
// reads. Files come from raw.githubusercontent.com at the pinned commit, never from a Fluxer host and with no GitHub API
// call or token. Copies are kept by content hash in projects/release/.cache/upstream/sha256 (gitignored), so a pin bump
// downloads only files whose content changed, and a legacy projects/web/.cache/fluxer copy seeds the shared store on read
import { readFile } from "node:fs/promises"
import { dirname, join, resolve } from "node:path"
import { fileURLToPath } from "node:url"
import { endpointDocsConfig, endpointDocsDirectory, validateManifest } from "../../../release/upstream.js"
import {
    defaultMaxBytes,
    pruneSha256Cache,
    readLimitedResponse,
    readVerifiedSha256,
    sha256Hex,
    sha256StoreDir,
    upstreamCachePath,
    writeVerifiedSha256,
} from "../../../release/upstream-cache.js"

const docsContentPath = dirname(endpointDocsDirectory)

export const defaultCacheDir = upstreamCachePath
export const legacyCacheDir = fileURLToPath(new URL("../../.cache/fluxer", import.meta.url))

const isRedirectError = (error) =>
    /redirect/i.test(String(error?.message ?? "")) || /redirect/i.test(String(error?.cause?.message ?? ""))

// A dropped connection, a server error or a rate limit is tried again, so a blip cannot fail a check or a release.
// Redirects, byte-limit breaches and real 4xx answers such as 404 stop immediately
export async function download(url, { attempt = 1, maxBytes = defaultMaxBytes, sleep = (ms) => new Promise((done) => setTimeout(done, ms)) } = {}) {
    let wait = attempt * 2000
    try {
        const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(30_000) })
        if (response.ok) {
            try {
                return await readLimitedResponse(response, maxBytes)
            } catch (error) {
                throw Object.assign(error instanceof Error ? error : new Error(String(error)), { final: true })
            }
        }
        await response.body?.cancel()
        if (response.status >= 300 && response.status < 400)
            throw Object.assign(new Error(`${url} attempted a redirect (HTTP ${response.status})`), { final: true })
        if (response.status !== 429 && response.status < 500)
            throw Object.assign(new Error(`${url} answered HTTP ${response.status}`), { final: true })
        const asked = Number(response.headers.get("retry-after"))
        if (asked > 0) wait = Math.min(asked, 120) * 1000
        throw new Error(`${url} answered HTTP ${response.status}`)
    } catch (error) {
        if (error?.final || isRedirectError(error) || attempt >= 6) throw error
        console.warn(`Retrying ${url} in ${Math.round(wait / 1000)} s: ${error.message}`)
        await sleep(wait)
        return download(url, { attempt: attempt + 1, maxBytes, sleep })
    }
}

const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/")

/** One file of a GitHub repository at an exact commit */
export const githubFile = (repository, commit, path) => download(`https://raw.githubusercontent.com/${repository}/${commit}/${encodePath(path)}`)

function resolveCacheLocations({ cacheDir, legacyDir }) {
    const envOverride = process.env.FLUXER_SOURCE_CACHE?.trim() || undefined
    const usesDefault = cacheDir === undefined || resolve(cacheDir) === resolve(legacyCacheDir)
    if (usesDefault) {
        if (envOverride) {
            return {
                storeRoot: resolve(envOverride),
                fallbackLegacyDir: legacyDir ? resolve(legacyDir) : undefined,
            }
        }
        return {
            storeRoot: resolve(defaultCacheDir),
            fallbackLegacyDir: legacyDir === null ? undefined : resolve(legacyDir ?? legacyCacheDir),
        }
    }
    return {
        storeRoot: resolve(cacheDir),
        fallbackLegacyDir: legacyDir ? resolve(legacyDir) : undefined,
    }
}

/**
 * The pinned OpenAPI document, the docs site's config and the HTTP API pages, each read by SHA-256 from the shared
 * upstream cache when its copy matches the pin, seeded from a verified legacy cache copy when available, and downloaded
 * into the cache otherwise
 * @param {any} manifest
 * @param {{ cacheDir?: string, legacyDir?: string | null, fetchFile?: (repository: string, commit: string, path: string) => Promise<Buffer>, log?: (...args: any[]) => void, prune?: boolean }} [options]
 * @returns {Promise<{ openapi: Buffer, config: string, documents: { path: string, text: string }[], downloaded: string[] }>}
 */
export async function fluxerSource(manifest, { cacheDir, legacyDir, fetchFile = githubFile, log = console.log, prune = true } = {}) {
    validateManifest(manifest)
    if (!manifest.endpointDocs) throw new Error("The upstream manifest pins no endpointDocs. Move the pin with node release/upstream.js --update <commit>")
    const { storeRoot, fallbackLegacyDir } = resolveCacheLocations({ cacheDir, legacyDir })
    const storeDir = sha256StoreDir(storeRoot)
    const pinned = [manifest.files.openapi, ...manifest.endpointDocs]
    const files = new Map()
    const downloaded = []
    for (const { path, sha256: expected } of pinned) {
        let { bytes, corrupted } = await readVerifiedSha256(storeRoot, expected)
        if (corrupted) log(`The cached ${path} does not match its pinned hash, downloading it again`)
        if (!bytes && fallbackLegacyDir) {
            const legacyBytes = await readFile(join(fallbackLegacyDir, manifest.commit, path)).catch(() => undefined)
            if (legacyBytes && sha256Hex(legacyBytes) === expected) {
                await writeVerifiedSha256(storeRoot, expected, legacyBytes)
                bytes = legacyBytes
            }
        }
        if (!bytes) {
            if (!downloaded.length) log(`Downloading Fluxer's pinned files at ${manifest.commit.slice(0, 12)} into ${storeDir}`)
            bytes = await fetchFile(manifest.repository, manifest.commit, path)
            const actual = sha256Hex(bytes)
            if (actual !== expected) throw new Error(`${path} at ${manifest.commit} hashes to ${actual}, not the pinned ${expected}`)
            await writeVerifiedSha256(storeRoot, expected, bytes)
            downloaded.push(path)
        }
        files.set(path, bytes)
    }
    if (prune) await pruneSha256Cache(storeRoot, new Set(pinned.map(({ sha256 }) => sha256)))
    return {
        openapi: files.get(manifest.files.openapi.path),
        config: files.get(endpointDocsConfig).toString("utf8"),
        documents: manifest.endpointDocs
            .filter(({ path }) => path !== endpointDocsConfig)
            .map(({ path }) => ({ path: path.slice(docsContentPath.length + 1), text: files.get(path).toString("utf8") })),
        downloaded,
    }
}