diff --git a/lib/collaborators.js b/lib/collaborators.js index 5b942fd3..b0c4224f 100644 --- a/lib/collaborators.js +++ b/lib/collaborators.js @@ -43,23 +43,22 @@ Collaborator.TYPES = { }; export async function getCollaborators(cli, request, argv) { - const { readme, owner, repo } = argv; - let readmeText; - if (readme) { - cli.updateSpinner(`Reading collaborator contacts from ${readme}`); - readmeText = fs.readFileSync(readme, 'utf8'); - } else { - cli.updateSpinner( - 'Getting collaborator contacts from README of nodejs/node'); - const url = 'https://raw.githubusercontent.com/nodejs/node/HEAD/README.md'; - readmeText = await request.text(url); - } - + const { readme } = argv; let collaborators; try { + let readmeText; + if (readme) { + cli.updateSpinner(`Reading collaborator contacts from ${readme}`); + readmeText = fs.readFileSync(readme, 'utf8'); + } else { + cli.updateSpinner( + 'Getting collaborator contacts from README of nodejs/node'); + const url = 'https://raw.githubusercontent.com/nodejs/node/HEAD/README.md'; + readmeText = await request.text(url); + } collaborators = parseCollaborators(readmeText, cli); } catch (err) { - const readmePath = readme || `${owner}/${repo}/README.md`; + const readmePath = readme || 'nodejs/node/README.md'; cli.stopSpinner(`Failed to get collaborator info from ${readmePath}`, cli.SPINNER_STATUS.FAILED); throw err; diff --git a/lib/request.js b/lib/request.js index 731994d2..c900a2c8 100644 --- a/lib/request.js +++ b/lib/request.js @@ -16,6 +16,14 @@ function wrappedFetch(url, options, ...args) { return fetch(url, options, ...args); } +async function fetchResponse(request, url, options) { + const res = await request.fetch(url, options); + if (isDebugVerbosity()) { + debuglog('[Request] Got response from', url, ':\n', res.status, ' ', res.statusText); + } + return res; +} + export default class Request { constructor(credentials) { this.credentials = credentials; @@ -51,9 +59,19 @@ export default class Request { } async text(url, options = {}) { - const res = await this.fetch(url, options); - if (isDebugVerbosity()) { - debuglog('[Request] Got response from', url, ':\n', res.status, ' ', res.statusText); + const res = await fetchResponse(this, url, options); + if (!res.ok) { + const status = `${res.status} ${res.statusText ?? ''}`.trim(); + const message = `Unable to fetch ${url}: ${status}`; + try { + await res.body?.cancel(); + } catch (err) { + if (isDebugVerbosity()) { + debuglog('[Request] Failed to cancel response body from', url, ':\n', err); + } + throw new Error(message, { cause: err }); + } + throw new Error(message); } return res.text(); } @@ -71,7 +89,8 @@ export default class Request { async json(url, options = {}) { options.headers = options.headers || {}; - const text = await this.text(url, options); + const res = await fetchResponse(this, url, options); + const text = await res.text(); try { return JSON.parse(text); } catch (e) { diff --git a/lib/voting_session.js b/lib/voting_session.js index f9c499b1..013e31bb 100644 --- a/lib/voting_session.js +++ b/lib/voting_session.js @@ -71,17 +71,24 @@ export default class VotingSession extends Session { async decryptKeyPart(prInfo) { const subPath = `${prInfo.headRef.name}/vote.yml`; this.cli.startSpinner('Downloading vote file from remote...'); - const yamlString = await this.req.text( - `/repos/${this.owner}/${this.repo}/contents/${ - encodeURIComponent(subPath)}?ref=${prInfo.commits.nodes[0].commit.oid}`, - { - agent: this.req.proxyAgent, - headers: { - Accept: 'application/vnd.github.raw+json', - 'X-GitHub-Api-Version': '2026-03-10' + let yamlString; + try { + yamlString = await this.req.text( + `/repos/${this.owner}/${this.repo}/contents/${ + encodeURIComponent(subPath)}?ref=${prInfo.commits.nodes[0].commit.oid}`, + { + agent: this.req.proxyAgent, + headers: { + Accept: 'application/vnd.github.raw+json', + 'X-GitHub-Api-Version': '2026-03-10' + } } - } - ); + ); + } catch (err) { + this.cli.stopSpinner('Failed to download vote file', + this.cli.SPINNER_STATUS.FAILED); + throw err; + } this.cli.stopSpinner('Download complete'); const { shares } = yaml.load(yamlString); diff --git a/test/unit/collaborators.test.js b/test/unit/collaborators.test.js index cf378f48..64e6dee6 100644 --- a/test/unit/collaborators.test.js +++ b/test/unit/collaborators.test.js @@ -1,11 +1,15 @@ import { describe, it, beforeEach } from 'node:test'; +import { mkdtempSync, rmSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import assert from 'node:assert'; +import os from 'node:os'; +import path from 'node:path'; import { isCollaborator, getCollaborators } from '../../lib/collaborators.js'; +import Request from '../../lib/request.js'; import { readme, @@ -186,6 +190,95 @@ describe('collaborators', function() { async() => getCollaborators(cli, request, argv), /Error: Could not find any collaborators/); }); + + it('should stop spinner and rethrow when request.text rejects', async() => { + const argv = { owner: 'nodejs', repo: 'node' }; + const err = new Error('Unable to fetch README: 503 Service Unavailable'); + const request = { + async text() { + throw err; + } + }; + + await assert.rejects( + () => getCollaborators(cli, request, argv), + (caught) => caught === err); + cli.assertCalledWith({ + stopSpinner: [[ + 'Failed to get collaborator info from nodejs/node/README.md', + cli.SPINNER_STATUS.FAILED + ]] + }, { ignore: ['updateSpinner'] }); + }); + + it('should reject non-ok HTTP responses via Request instead of parse error', async() => { + const argv = { owner: 'nodejs', repo: 'node' }; + const request = Object.assign(Object.create(Request.prototype), { + credentials: {}, + proxyAgent: undefined + }); + let cancelled = false; + request.fetch = async() => ({ + ok: false, + status: 503, + statusText: 'Service Unavailable', + body: { + cancel: async() => { + cancelled = true; + } + }, + text: async() => '503' + }); + + await assert.rejects( + () => getCollaborators(cli, request, argv), + /Unable to fetch .*: 503 Service Unavailable/); + assert.strictEqual(cancelled, true); + cli.assertCalledWith({ + stopSpinner: [[ + 'Failed to get collaborator info from nodejs/node/README.md', + cli.SPINNER_STATUS.FAILED + ]] + }, { ignore: ['updateSpinner'] }); + }); + + it('should stop spinner and rethrow when local readme file cannot be read', async(t) => { + const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'ncu-collaborators-')); + t.after(() => rmSync(tmpDir, { recursive: true, force: true })); + const missingPath = path.join(tmpDir, 'missing-README.md'); + const argv = { owner: 'nodejs', repo: 'node', readme: missingPath }; + + await assert.rejects( + () => getCollaborators(cli, {}, argv), + { code: 'ENOENT' }); + cli.assertCalledWith({ + stopSpinner: [[ + `Failed to get collaborator info from ${missingPath}`, + cli.SPINNER_STATUS.FAILED + ]] + }, { ignore: ['updateSpinner'] }); + }); + + it('should report nodejs/node/README.md when remote fetch fails for another repo', + async() => { + const argv = { owner: 'nodejs', repo: 'llnode' }; + const err = new Error('Unable to fetch README: 503 Service Unavailable'); + const request = { + async text() { + throw err; + } + }; + + await assert.rejects( + () => getCollaborators(cli, request, argv), + (caught) => caught === err); + cli.assertCalledWith({ + stopSpinner: [[ + 'Failed to get collaborator info from nodejs/node/README.md', + cli.SPINNER_STATUS.FAILED + ]] + }, { ignore: ['updateSpinner'] }); + }); }); describe('isCollaborator', () => { diff --git a/test/unit/request.test.js b/test/unit/request.test.js index e244150a..22add73a 100644 --- a/test/unit/request.test.js +++ b/test/unit/request.test.js @@ -170,6 +170,149 @@ describe('Request', () => { }); }); }); + + describe('text', () => { + it('returns response text when status is ok', async() => { + const request = createRequest({}); + request.fetch = async() => ({ + ok: true, + status: 200, + statusText: 'OK', + text: async() => 'hello world' + }); + + const body = await request.text('https://example.com/README.md'); + assert.strictEqual(body, 'hello world'); + }); + + it('rejects non-ok responses and cancels the body', async() => { + const request = createRequest({}); + let cancelled = false; + let readBody = false; + request.fetch = async() => ({ + ok: false, + status: 503, + statusText: 'Service Unavailable', + body: { + cancel: async() => { + cancelled = true; + } + }, + text: async() => { + readBody = true; + return '503'; + } + }); + + await assert.rejects( + () => request.text('https://example.com/README.md'), + /Unable to fetch https:\/\/example\.com\/README\.md: 503 Service Unavailable/); + assert.strictEqual(cancelled, true); + assert.strictEqual(readBody, false); + }); + + it('rejects non-ok responses when res.body is missing', async() => { + const request = createRequest({}); + let readBody = false; + request.fetch = async() => ({ + ok: false, + status: 502, + statusText: 'Bad Gateway', + text: async() => { + readBody = true; + return '502'; + } + }); + + await assert.rejects( + () => request.text('https://example.com/README.md'), + /Unable to fetch https:\/\/example\.com\/README\.md: 502 Bad Gateway/); + assert.strictEqual(readBody, false); + }); + + it('rejects with HTTP status when cancelling an errored response body fails', async() => { + const request = createRequest({}); + const streamErr = new TypeError('terminated'); + const stream = new ReadableStream({ + start(controller) { + controller.error(streamErr); + } + }); + request.fetch = async() => new Response(stream, { + status: 503, + statusText: 'Service Unavailable' + }); + + await assert.rejects( + () => request.text('https://example.com/README.md'), + (err) => { + assert.strictEqual( + err.message, + 'Unable to fetch https://example.com/README.md: 503 Service Unavailable'); + assert.strictEqual(err.cause, streamErr); + return true; + }); + }); + + it('omits trailing space when statusText is empty', async() => { + const request = createRequest({}); + request.fetch = async() => ({ + ok: false, + status: 503, + statusText: '', + body: { cancel: async() => {} } + }); + + await assert.rejects( + () => request.text('https://example.com/README.md'), + (err) => { + assert.strictEqual(err.message, 'Unable to fetch https://example.com/README.md: 503'); + return true; + }); + }); + + it('preserves falsy body cancellation rejection reasons as cause', async() => { + const request = createRequest({}); + for (const reason of [false, undefined]) { + const stream = new ReadableStream({ + start(controller) { + controller.error(reason); + } + }); + request.fetch = async() => new Response(stream, { + status: 503, + statusText: 'Service Unavailable' + }); + + await assert.rejects( + () => request.text('https://example.com/README.md'), + (err) => { + assert.strictEqual( + err.message, + 'Unable to fetch https://example.com/README.md: 503 Service Unavailable'); + assert.strictEqual(Object.hasOwn(err, 'cause'), true); + assert.strictEqual(err.cause, reason); + return true; + }); + } + }); + }); + + describe('json', () => { + it('parses JSON payloads on non-ok responses', async() => { + const request = createRequest({}); + delete request.json; + request.fetch = async() => ({ + ok: false, + status: 401, + statusText: 'Unauthorized', + text: async() => '{"message":"Bad credentials"}' + }); + + const body = await request.json('/graphql', { method: 'POST' }); + assert.deepStrictEqual(body, { message: 'Bad credentials' }); + }); + }); }); describe('Request: OpenJS CNA', () => { diff --git a/test/unit/voting_session.test.js b/test/unit/voting_session.test.js new file mode 100644 index 00000000..345d43ca --- /dev/null +++ b/test/unit/voting_session.test.js @@ -0,0 +1,70 @@ +import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, it } from 'node:test'; +import assert from 'node:assert'; + +import { clearCachedConfig } from '../../lib/config.js'; +import Request from '../../lib/request.js'; +import VotingSession from '../../lib/voting_session.js'; +import TestCLI from '../fixtures/test_cli.js'; + +describe('VotingSession', () => { + it('stops spinner as failed when vote.yml fetch returns non-ok HTTP status', async(t) => { + const cli = new TestCLI(); + const hasXdg = Object.hasOwn(process.env, 'XDG_CONFIG_HOME'); + const origXdg = process.env.XDG_CONFIG_HOME; + const tmpDir = mkdtempSync(path.join(os.tmpdir(), 'ncu-vote-')); + t.after(() => { + rmSync(tmpDir, { recursive: true, force: true }); + }); + + const xdgDir = path.join(tmpDir, 'xdg'); + mkdirSync(xdgDir); + process.env.XDG_CONFIG_HOME = xdgDir; + clearCachedConfig(); + + const request = Object.assign(Object.create(Request.prototype), { + credentials: { github: 'dGVzdDp0b2tlbg==' }, + proxyAgent: undefined + }); + let cancelled = false; + request.fetch = async() => ({ + ok: false, + status: 503, + statusText: 'Service Unavailable', + body: { + cancel: async() => { + cancelled = true; + } + }, + text: async() => '503' + }); + + try { + const session = new VotingSession(cli, request, tmpDir, { + owner: 'nodejs', + repo: 'TSC', + prid: 12344 + }); + await assert.rejects( + () => session.decryptKeyPart({ + headRef: { name: 'vote-123' }, + commits: { nodes: [{ commit: { oid: '0123456789abcdef' } }] } + }), + /Unable to fetch .*: 503 Service Unavailable/); + assert.strictEqual(cancelled, true); + cli.assertCalledWith({ + startSpinner: [['Downloading vote file from remote...']], + stopSpinner: [['Failed to download vote file', cli.SPINNER_STATUS.FAILED]] + }); + } finally { + if (hasXdg) { + process.env.XDG_CONFIG_HOME = origXdg; + } else { + delete process.env.XDG_CONFIG_HOME; + } + clearCachedConfig(); + } + }); +});