Initial commit: Pulse RSS feed aggregator with fetcher module and all interfaces

This commit is contained in:
Edo Limburg
2026-05-05 21:07:52 +02:00
commit 84cafa9ecb
16 changed files with 2913 additions and 0 deletions
+211
View File
@@ -0,0 +1,211 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { MockAgent } from 'undici';
import { HttpFetcher } from './fetcher.js';
describe('HttpFetcher', () => {
let mockAgent: MockAgent;
let fetcher: HttpFetcher;
beforeEach(() => {
mockAgent = new MockAgent();
mockAgent.disableNetConnect();
fetcher = new HttpFetcher({ timeout: 5000, dispatcher: mockAgent });
});
afterEach(async () => {
await mockAgent.close();
});
it('returns response for valid RSS feed', async () => {
const mockPool = mockAgent.get('https://example.com');
mockPool
.intercept({ path: '/feed.xml', method: 'GET' })
.reply(200, '<?xml version="1.0"?><rss></rss>', {
headers: { 'content-type': 'application/rss+xml' },
});
const result = await fetcher.fetch({
url: 'https://example.com/feed.xml',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(1);
expect(result.errors).toHaveLength(0);
expect(result.responses[0].body).toBe('<?xml version="1.0"?><rss></rss>');
expect(result.responses[0].contentType).toBe('application/rss+xml');
expect(result.responses[0].statusCode).toBe(200);
});
it('returns response for valid Atom feed', async () => {
const mockPool = mockAgent.get('https://example.com');
mockPool
.intercept({ path: '/atom.xml', method: 'GET' })
.reply(200, '<?xml version="1.0"?><feed></feed>', {
headers: { 'content-type': 'application/atom+xml' },
});
const result = await fetcher.fetch({
url: 'https://example.com/atom.xml',
expectedFormat: 'atom',
});
expect(result.responses).toHaveLength(1);
expect(result.errors).toHaveLength(0);
expect(result.responses[0].body).toBe('<?xml version="1.0"?><feed></feed>');
});
it('returns PARSE error for wrong content type', async () => {
const mockPool = mockAgent.get('https://example.com');
mockPool
.intercept({ path: '/feed.json', method: 'GET' })
.reply(200, '{"foo":"bar"}', {
headers: { 'content-type': 'application/json' },
});
const result = await fetcher.fetch({
url: 'https://example.com/feed.json',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('PARSE');
expect(result.errors[0].reason).toContain('Unexpected content type');
});
it('returns PARSE error when body does not look like XML', async () => {
const mockPool = mockAgent.get('https://example.com');
mockPool
.intercept({ path: '/plain.txt', method: 'GET' })
.reply(200, 'not xml at all', {
headers: { 'content-type': 'text/plain' },
});
const result = await fetcher.fetch({
url: 'https://example.com/plain.txt',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('PARSE');
});
it('returns UNKNOWN error for non-2xx status', async () => {
const mockPool = mockAgent.get('https://example.com');
mockPool
.intercept({ path: '/notfound.xml', method: 'GET' })
.reply(404, 'Not Found', {
headers: { 'content-type': 'text/plain' },
});
const result = await fetcher.fetch({
url: 'https://example.com/notfound.xml',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('UNKNOWN');
expect(result.errors[0].reason).toContain('404');
});
it('returns NETWORK error for connection refused', async () => {
const mockPool = mockAgent.get('https://offline.com');
const networkError = new Error('connect ECONNREFUSED 127.0.0.1:443');
mockPool.intercept({ path: '/feed.xml', method: 'GET' }).replyWithError(networkError);
const result = await fetcher.fetch({
url: 'https://offline.com/feed.xml',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('NETWORK');
});
it('returns TIMEOUT error for abort error', async () => {
const mockPool = mockAgent.get('https://slow.com');
const abortError = new Error('The operation was aborted');
abortError.name = 'AbortError';
mockPool.intercept({ path: '/feed.xml', method: 'GET' }).replyWithError(abortError);
const result = await fetcher.fetch({
url: 'https://slow.com/feed.xml',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(0);
expect(result.errors).toHaveLength(1);
expect(result.errors[0].code).toBe('TIMEOUT');
});
it('uses body sniff fallback when content-type is missing', async () => {
const mockPool = mockAgent.get('https://example.com');
mockPool
.intercept({ path: '/feed.xml', method: 'GET' })
.reply(200, '<?xml version="1.0"?><rss></rss>', {
headers: {},
});
const result = await fetcher.fetch({
url: 'https://example.com/feed.xml',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(1);
expect(result.errors).toHaveLength(0);
expect(result.responses[0].contentType).toBe('application/xml');
});
it('accepts generic application/xml for RSS', async () => {
const mockPool = mockAgent.get('https://example.com');
mockPool
.intercept({ path: '/feed.xml', method: 'GET' })
.reply(200, '<?xml version="1.0"?><rss></rss>', {
headers: { 'content-type': 'application/xml' },
});
const result = await fetcher.fetch({
url: 'https://example.com/feed.xml',
expectedFormat: 'rss',
});
expect(result.responses).toHaveLength(1);
expect(result.errors).toHaveLength(0);
});
it('processes multiple feeds with mixed results via fetchMany', async () => {
const okPool = mockAgent.get('https://ok.com');
okPool
.intercept({ path: '/feed.xml', method: 'GET' })
.reply(200, '<?xml version="1.0"?><rss></rss>', {
headers: { 'content-type': 'application/rss+xml' },
});
const failPool = mockAgent.get('https://fail.com');
failPool
.intercept({ path: '/feed.xml', method: 'GET' })
.reply(500, 'Internal Server Error', {
headers: { 'content-type': 'text/plain' },
});
const result = await fetcher.fetchMany([
{ url: 'https://ok.com/feed.xml', expectedFormat: 'rss' },
{ url: 'https://fail.com/feed.xml', expectedFormat: 'rss' },
]);
expect(result.responses).toHaveLength(1);
expect(result.errors).toHaveLength(1);
expect(result.responses[0].source).toBe('https://ok.com/feed.xml');
expect(result.errors[0].source).toBe('https://fail.com/feed.xml');
});
it('returns empty result for empty input array', async () => {
const result = await fetcher.fetchMany([]);
expect(result.responses).toHaveLength(0);
expect(result.errors).toHaveLength(0);
});
});
+178
View File
@@ -0,0 +1,178 @@
import { request, type Dispatcher } from 'undici';
import type { FetchInput, FetchResult, FeedResponse, FetchError } from '../../interfaces/feed.types.js';
import type { IFetcher } from '../../interfaces/fetcher.interface.js';
const VALID_RSS_CONTENT_TYPES = [
'application/xml',
'text/xml',
'application/rss+xml',
];
const VALID_ATOM_CONTENT_TYPES = [
'application/xml',
'text/xml',
'application/atom+xml',
];
function getValidTypes(expectedFormat: FetchInput['expectedFormat']): string[] {
return expectedFormat === 'rss' ? VALID_RSS_CONTENT_TYPES : VALID_ATOM_CONTENT_TYPES;
}
function normalizeContentType(contentType: string): string {
return contentType.split(';')[0].trim().toLowerCase();
}
function isValidFormat(expectedFormat: FetchInput['expectedFormat'], contentType: string): boolean {
const normalized = normalizeContentType(contentType);
const validTypes = getValidTypes(expectedFormat);
return validTypes.includes(normalized);
}
function bodyLooksLikeXml(body: string): boolean {
const trimmed = body.trimStart().toLowerCase();
return trimmed.startsWith('<?xml') || trimmed.startsWith('<rss') || trimmed.startsWith('<feed');
}
function classifyError(error: unknown, source: string): FetchError {
const err = error as Error & { code?: string };
const message = err.message ?? String(error);
if (
err.name === 'AbortError' ||
err.code === 'UND_ERR_CONNECT_TIMEOUT' ||
err.code === 'UND_ERR_REQUEST_TIMEOUT' ||
err.code === 'UND_ERR_HEADERS_TIMEOUT'
) {
return { source, reason: message, code: 'TIMEOUT' };
}
const networkCodes = ['ECONNREFUSED', 'ENOTFOUND', 'ETIMEDOUT', 'EAI_AGAIN', 'ECONNRESET', 'EPIPE', 'ENETUNREACH'];
if (
networkCodes.includes(err.code ?? '') ||
networkCodes.some((code) => message.includes(code))
) {
return { source, reason: message, code: 'NETWORK' };
}
return { source, reason: message, code: 'UNKNOWN' };
}
export interface HttpFetcherOptions {
timeout?: number;
concurrency?: number;
dispatcher?: Dispatcher;
}
export class HttpFetcher implements IFetcher {
private readonly timeout: number;
private readonly concurrency: number;
private readonly dispatcher?: Dispatcher;
constructor(options: HttpFetcherOptions = {}) {
this.timeout = options.timeout ?? 10_000;
this.concurrency = options.concurrency ?? 5;
this.dispatcher = options.dispatcher;
}
async fetch(input: FetchInput): Promise<FetchResult> {
const result: FetchResult = { responses: [], errors: [], fetchedAt: new Date() };
try {
const { statusCode, headers, body } = await request(input.url, {
method: 'GET',
headers: { 'User-Agent': 'Pulse-RSS-Fetcher/1.0' },
signal: AbortSignal.timeout(this.timeout),
dispatcher: this.dispatcher,
});
const responseBody = await body.text();
if (statusCode < 200 || statusCode >= 300) {
result.errors.push({
source: input.url,
reason: `HTTP ${statusCode}`,
code: 'UNKNOWN',
});
return result;
}
const contentType = (headers['content-type'] as string | undefined) ?? '';
if (contentType) {
if (!isValidFormat(input.expectedFormat, contentType)) {
if (!bodyLooksLikeXml(responseBody)) {
result.errors.push({
source: input.url,
reason: `Unexpected content type: ${contentType}`,
code: 'PARSE',
});
return result;
}
}
} else if (!bodyLooksLikeXml(responseBody)) {
result.errors.push({
source: input.url,
reason: 'Response does not appear to be XML',
code: 'PARSE',
});
return result;
}
result.responses.push({
source: input.url,
body: responseBody,
contentType: contentType || 'application/xml',
statusCode,
});
} catch (error) {
result.errors.push(classifyError(error, input.url));
}
return result;
}
async fetchMany(inputs: FetchInput[]): Promise<FetchResult> {
const result: FetchResult = { responses: [], errors: [], fetchedAt: new Date() };
const limit = createConcurrencyLimit(this.concurrency);
const results = await Promise.all(inputs.map((input) => limit(() => this.fetch(input))));
for (const r of results) {
result.responses.push(...r.responses);
result.errors.push(...r.errors);
}
return result;
}
}
function createConcurrencyLimit(concurrency: number) {
const queue: (() => void)[] = [];
let activeCount = 0;
return function <T>(fn: () => Promise<T>): Promise<T> {
return new Promise((resolve, reject) => {
const run = async () => {
activeCount++;
try {
const result = await fn();
resolve(result);
} catch (error) {
reject(error);
} finally {
activeCount--;
if (queue.length > 0) {
const next = queue.shift()!;
next();
}
}
};
if (activeCount < concurrency) {
run();
} else {
queue.push(run);
}
});
};
}
+1
View File
@@ -0,0 +1 @@
export { HttpFetcher, type HttpFetcherOptions } from './fetcher.js';