/** 원격 검증 요청의 제한·취소·본문 수집. docs/specs/remote-harness-validation.md v1.1.0 */ const { checkCancellation } = require('./harness-command'); const { configurationError } = require('../config/harness-configuration'); async function harnessHttpRequest(url, { method = 'GET', headers = {}, body, signal, shouldCancel, timeoutMs = 30000, maxBufferBytes = 2 * 1024 * 1024 } = {}) { const target = new URL(url); if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw configurationError('an HTTP(S) URL without embedded credentials is required'); if (!Number.isFinite(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2147483647) throw configurationError('invalid HTTP timeout'); if (!Number.isSafeInteger(maxBufferBytes) || maxBufferBytes <= 0) throw configurationError('invalid HTTP body limit'); checkCancellation(signal, shouldCancel); return new Promise((resolve, reject) => { let req, response, timer, poll, settled = false, bytes = 0, failure, result, requestClosed = false, responseClosed = false, starting = true; const chunks = []; const cleanup = () => { clearTimeout(timer); clearInterval(poll); signal?.removeEventListener('abort', cancel); }; const finish = () => { // destroy나 end는 종료 영수증이 아니다. 실패도 생성된 모든 로컬 객체의 close를 기다린다. // 원격 브리지의 실제 작업 취소를 확인하는 계약과는 별개다. if (settled || starting || req && !requestClosed || response && !responseClosed || !failure && !result) return; settled = true; cleanup(); if (failure) reject(failure); else resolve(result); }; const destroy = object => { try { object?.destroy(); } catch (error) { failure ||= error; } }; const stop = error => { if (settled) return; if (!failure) { failure = error; cleanup(); destroy(response); destroy(req); } finish(); }; const cancel = () => { try { checkCancellation(signal, shouldCancel); } catch (error) { stop(error); } }; try { req = require(target.protocol === 'https:' ? 'https' : 'http').request(target, { method, headers }, res => { response = res; // 취소와 응답 callback이 경합해도 늦은 응답의 close를 먼저 구독한다. res.on('close', () => { responseClosed = true; if (!result && !failure) stop(new Error('HTTP response was interrupted')); finish(); }); res.on('data', chunk => { if (settled || failure) return; bytes += chunk.length; if (bytes > maxBufferBytes) return stop(Object.assign(new Error('HTTP response exceeded body limit'), { code: 'HARNESS_OUTPUT_LIMIT' })); chunks.push(chunk); }); res.on('error', stop); res.on('aborted', () => stop(new Error('HTTP response was interrupted'))); res.on('end', () => { if (settled || failure) return; if (!res.complete) return stop(new Error('HTTP response was incomplete')); cancel(); if (failure) return; result = { status: res.statusCode, text: Buffer.concat(chunks).toString('utf8') }; finish(); }); if (failure || settled) { destroy(res); finish(); } }); req.on('close', () => { requestClosed = true; if (!response && !failure) stop(new Error('HTTP request closed without a response')); finish(); }); req.on('error', stop); starting = false; if (failure) { destroy(req); finish(); return; } timer = setTimeout(() => stop(Object.assign(new Error('HTTP validation timed out'), { code: 'HARNESS_TIMEOUT' })), timeoutMs); if (shouldCancel) poll = setInterval(cancel, 50); signal?.addEventListener('abort', cancel, { once: true }); cancel(); if (!failure) req.end(body); } catch (error) { starting = false; stop(error); } }); } module.exports = { harnessHttpRequest };