From 027d9131ba3d357a9423e0e44a95716760b4206f Mon Sep 17 00:00:00 2001 From: Alexander Kreitner <180843591+Gl4dr3x@users.noreply.github.com> Date: Tue, 1 Dec 2026 09:52:51 +0100 Subject: [PATCH 1/3] feat(route): name why a Workoho route failed and bound its requests A route that fails now answers with the response header RSSHub-Error-Reason next to its error status: upstream-timeout, upstream-status, upstream-unreachable or parse-error. With upstream-status, RSSHub-Error-Upstream-Status carries the status the source answered with. The error handler classifies every route's error; anything it cannot name gets no header. The seven routes Workoho maintains read their source through fetchUpstream: six seconds a request, one retry, so a reader that waits 15 seconds gets the reason instead of its own timeout. A source that answers with something the route cannot read, or with no item, is a parse error. The EasyLife 365 changelog route read every changelog page on each request, 135 of them, and took over 30 seconds. It reads the site's own JSON feed now: one request, the 20 newest entries with their full HTML. Tests pin that each of the seven routes declares charset=utf-8 and delivers UTF-8 as RSS, Atom and JSON Feed. Co-Authored-By: Claude Fable 5.2 --- lib/errors/index.tsx | 6 + lib/errors/types/route-failure.ts | 21 +++ lib/routes/easylife365/changelogs.ts | 137 +++++++------- lib/routes/flexopus/changelog.ts | 7 +- lib/routes/microsoft/message-center.ts | 13 +- lib/routes/microsoftlearn/entra-whats-new.ts | 8 +- lib/routes/microsoftlearn/intune-blog.ts | 12 +- .../microsoftlearn/intune-in-development.ts | 8 +- lib/routes/microsoftlearn/intune-whats-new.ts | 8 +- lib/utils/route-failure.test.ts | 178 ++++++++++++++++++ lib/utils/route-failure.ts | 100 ++++++++++ 11 files changed, 403 insertions(+), 95 deletions(-) create mode 100644 lib/errors/types/route-failure.ts create mode 100644 lib/utils/route-failure.test.ts create mode 100644 lib/utils/route-failure.ts diff --git a/lib/errors/index.tsx b/lib/errors/index.tsx index b78603815c00..4b28d9051494 100644 --- a/lib/errors/index.tsx +++ b/lib/errors/index.tsx @@ -7,6 +7,7 @@ import { config } from '@/config'; import { getDebugInfo, setDebugInfo } from '@/utils/debug-info'; import logger from '@/utils/logger'; import { requestMetric } from '@/utils/otel'; +import { classifyFailure, reasonHeader, upstreamStatusHeader } from '@/utils/route-failure'; import Error from '@/views/error'; import NotFoundError from './types/not-found'; @@ -72,6 +73,11 @@ export const errorHandler: ErrorHandler = (error, ctx) => { ctx.status(503); break; } + const failure = classifyFailure(error); + if (failure) { + ctx.header(reasonHeader, failure.reason); + failure.upstreamStatus && ctx.header(upstreamStatusHeader, String(failure.upstreamStatus)); + } const message = `${error.name}: ${errorMessage}`; logger.error(`Error in ${requestPath}: ${message}`); diff --git a/lib/errors/types/route-failure.ts b/lib/errors/types/route-failure.ts new file mode 100644 index 000000000000..24e20a5cfa85 --- /dev/null +++ b/lib/errors/types/route-failure.ts @@ -0,0 +1,21 @@ +export const routeFailureReasons = ['upstream-timeout', 'upstream-status', 'upstream-unreachable', 'parse-error'] as const; + +export type RouteFailureReason = (typeof routeFailureReasons)[number]; + +/** + * A route failed for a reason a reader of the feed can act on. The error + * handler names the reason in the `RSSHub-Error-Reason` response header. + */ +class RouteFailureError extends Error { + name = 'RouteFailureError'; + reason: RouteFailureReason; + upstreamStatus?: number; + + constructor(reason: RouteFailureReason, message: string, options?: { cause?: unknown; upstreamStatus?: number }) { + super(message, { cause: options?.cause }); + this.reason = reason; + this.upstreamStatus = options?.upstreamStatus; + } +} + +export default RouteFailureError; diff --git a/lib/routes/easylife365/changelogs.ts b/lib/routes/easylife365/changelogs.ts index 565571a101b1..cd068699f64b 100644 --- a/lib/routes/easylife365/changelogs.ts +++ b/lib/routes/easylife365/changelogs.ts @@ -1,90 +1,81 @@ -import { load } from 'cheerio'; - -import got from '@/utils/got'; - -function parseDateFromLink(link: string) { - const match = link.match(/\/changelogs\/(\d{4})\/(\d{2})\/(\d{2})\//); - if (!match) { - return; - } - - const [, yyyy, mm, dd] = match; - return new Date(`${yyyy}-${mm}-${dd}T00:00:00Z`).toUTCString(); +import type { DataItem, Route } from '@/types'; +import { parseDate } from '@/utils/parse-date'; +import { fetchUpstream, requireItems } from '@/utils/route-failure'; + +interface ChangelogFeedItem { + content_html?: string; + date_modified?: string; + date_published?: string; + summary?: string; + tags?: string[]; + title?: string; + url?: string; } -function cleanDescription(text: string) { - return text - .replaceAll(/\s+/g, ' ') - .replace(/^←\s*Back to Changelog/, '') - .replace(/Have questions\? Reach out to us for more information\.?Contact Us$/i, '') - .trim(); -} +const rootUrl = 'https://docs.easylife365.cloud'; +const currentUrl = `${rootUrl}/changelogs`; +// The site's own feed of its newest changelogs, with each one's full text. +const feedUrl = `${currentUrl}/feed.json`; + +const productNames: Record = { + collab: 'Collaboration', + identity: 'Identity', + mail: 'Mail', + meet: 'Meet', + tipster: 'Tipster', +}; function getProductFromLink(link: string) { - const match = link.match(/\/changelogs\/\d{4}\/\d{2}\/\d{2}\/([^/]+)\//); - if (!match) { - return ''; - } + const product = link.match(/\/changelogs\/\d{4}\/\d{2}\/\d{2}\/([^/]+)\//)?.[1]; - const productMap: Record = { - collab: 'Collaboration', - identity: 'Identity', - mail: 'Mail', - meet: 'Meet', - tipster: 'Tipster', - }; + return product ? (productNames[product] ?? product) : ''; +} + +function getDateFromLink(link: string) { + const match = link.match(/\/changelogs\/(\d{4})\/(\d{2})\/(\d{2})\//); - return productMap[match[1]] ?? match[1]; + return match ? parseDate(`${match[1]}-${match[2]}-${match[3]}`) : undefined; } -export const route = { +export const route: Route = { path: '/changelogs', name: 'Changelogs', categories: ['program-update'], example: '/easylife365/changelogs', - maintainers: ['dein-github-name'], - handler: async () => { - const rootUrl = 'https://docs.easylife365.cloud'; - const currentUrl = `${rootUrl}/changelogs`; - - const response = await got(currentUrl); - const $ = load(response.data); - - const links = [ - ...new Set( - $('a[href*="/changelogs/"]') - .toArray() - .map((el) => $(el).attr('href')) - .filter((href): href is string => typeof href === 'string' && href.length > 0) - .map((href) => new URL(href, rootUrl).toString()) - ), - ]; - - const item = await Promise.all( - links.map(async (link) => { - const detailResponse = await got(link); - const detail$ = load(detailResponse.data); - - const rawTitle = detail$('main h1').first().text().trim() || detail$('h1').first().text().trim() || detail$('title').first().text().trim() || link.split('/').at(-1) || 'Untitled'; - - const product = getProductFromLink(link); - const title = product ? `${product}: ${rawTitle}` : rawTitle; + maintainers: [], + radar: [ + { + source: ['docs.easylife365.cloud/changelogs'], + target: '/changelogs', + }, + ], + handler, + url: 'docs.easylife365.cloud/changelogs', +}; - const rawDescription = detail$('main').first().text() || detail$('article').first().text() || ''; +async function handler() { + const feed = await fetchUpstream<{ items?: ChangelogFeedItem[] }>(feedUrl, { responseType: 'json' }); + const entries = Array.isArray(feed?.items) ? feed.items.filter((entry) => typeof entry?.url === 'string' && entry.url.length > 0) : []; - return { - title, - link, - description: cleanDescription(rawDescription), - pubDate: parseDateFromLink(link), - }; - }) - ); + const item = requireItems(entries, 'changelog entries').map((entry): DataItem => { + const link = new URL(entry.url!, rootUrl).toString(); + const product = getProductFromLink(link); + const rawTitle = entry.title || link.split('/').at(-1) || 'Untitled'; + const date = entry.date_published || entry.date_modified; return { - title: 'EasyLife 365 Changelogs', - link: currentUrl, - item, + title: product ? `${product}: ${rawTitle}` : rawTitle, + link, + description: entry.content_html || entry.summary || '', + pubDate: date ? parseDate(date) : getDateFromLink(link), + category: entry.tags?.length ? entry.tags : undefined, }; - }, -}; + }); + + return { + title: 'EasyLife 365 Changelogs', + link: currentUrl, + item, + language: 'en' as const, + }; +} diff --git a/lib/routes/flexopus/changelog.ts b/lib/routes/flexopus/changelog.ts index 1ed2cdff5c71..f5de2b2407a1 100644 --- a/lib/routes/flexopus/changelog.ts +++ b/lib/routes/flexopus/changelog.ts @@ -1,8 +1,8 @@ import { load } from 'cheerio'; import type { Route } from '@/types'; -import ofetch from '@/utils/ofetch'; import { parseDate } from '@/utils/parse-date'; +import { fetchUpstream, requireItems } from '@/utils/route-failure'; const baseUrl = 'https://help.flexopus.com'; const apiKey = 'c1841f6cc3813bc6405fcf7353'; @@ -33,15 +33,16 @@ export const route: Route = { }; async function handler() { - const data = await ofetch(`${baseUrl}/en/ghost/api/content/posts/`, { + const data = await fetchUpstream<{ posts?: Array> }>(`${baseUrl}/en/ghost/api/content/posts/`, { query: { key: apiKey, filter: 'tag:hash-changelog', limit: 15, }, + responseType: 'json', }); - const items = data.posts.map((post) => { + const items = requireItems(Array.isArray(data?.posts) ? data.posts : [], 'changelog posts').map((post) => { const $ = load(post.html || ''); $('[referrerpolicy]').removeAttr('referrerpolicy'); $('.kg-callout-card-accent').remove(); diff --git a/lib/routes/microsoft/message-center.ts b/lib/routes/microsoft/message-center.ts index 5661ae68b35f..faf8b1955419 100644 --- a/lib/routes/microsoft/message-center.ts +++ b/lib/routes/microsoft/message-center.ts @@ -1,9 +1,10 @@ import { load } from 'cheerio'; +import RouteFailureError from '@/errors/types/route-failure'; import type { DataItem, Route } from '@/types'; import { ViewType } from '@/types'; -import got from '@/utils/got'; import { parseDate } from '@/utils/parse-date'; +import { fetchUpstream, requireItems } from '@/utils/route-failure'; interface MessageCenterDetail { Name: string; @@ -71,14 +72,16 @@ export const route: Route = { async function handler(ctx) { const limit = Number.parseInt(ctx.req.query('limit') ?? String(defaultLimit), 10); const pageSize = Number.isNaN(limit) || limit <= 0 ? defaultLimit : limit; - const { data: messages }: { data: MessageCenterMessage[] } = await got(dataUrl); + const messages = await fetchUpstream(dataUrl, { responseType: 'json' }); if (!Array.isArray(messages)) { - throw new TypeError('Failed to fetch Microsoft 365 Message Center archive data.'); + throw new RouteFailureError('parse-error', 'The Microsoft 365 Message Center archive is not a list of messages.'); } - const item = messages - .filter((message) => isMessageCenterMessage(message)) + const item = requireItems( + messages.filter((message) => isMessageCenterMessage(message)), + 'Message Center posts' + ) .toSorted((a, b) => getTimestamp(b) - getTimestamp(a)) .slice(0, pageSize) .map((message): DataItem => { diff --git a/lib/routes/microsoftlearn/entra-whats-new.ts b/lib/routes/microsoftlearn/entra-whats-new.ts index e2bbc136461c..e4e1f0c6b9a9 100644 --- a/lib/routes/microsoftlearn/entra-whats-new.ts +++ b/lib/routes/microsoftlearn/entra-whats-new.ts @@ -1,7 +1,7 @@ import { load } from 'cheerio'; -import got from '@/utils/got'; import { parseDate } from '@/utils/parse-date'; +import { fetchUpstream, requireItems } from '@/utils/route-failure'; export const route = { path: '/entra/whats-new', @@ -12,8 +12,8 @@ export const route = { handler: async () => { const currentUrl = 'https://learn.microsoft.com/en-us/entra/fundamentals/whats-new'; - const response = await got(currentUrl); - const $ = load(response.data); + const page = await fetchUpstream(currentUrl); + const $ = load(page); const item: Array<{ title: string; @@ -75,7 +75,7 @@ export const route = { return { title: 'Microsoft Entra releases and announcements', link: currentUrl, - item, + item: requireItems(item, 'announcements'), }; }, }; diff --git a/lib/routes/microsoftlearn/intune-blog.ts b/lib/routes/microsoftlearn/intune-blog.ts index 32a96c059478..c6eb0474f97b 100644 --- a/lib/routes/microsoftlearn/intune-blog.ts +++ b/lib/routes/microsoftlearn/intune-blog.ts @@ -1,5 +1,7 @@ +import RouteFailureError from '@/errors/types/route-failure'; import type { Data, DataItem, Route } from '@/types'; import { parseDate } from '@/utils/parse-date'; +import { fetchUpstream, requireItems } from '@/utils/route-failure'; import parser from '@/utils/rss-parser'; export const route: Route = { @@ -20,9 +22,15 @@ export const route: Route = { async function handler(): Promise { const feedUrl = 'https://techcommunity.microsoft.com/t5/s/gxcuf89792/rss/board?board.id=microsoftintuneblog'; - const feed = await parser.parseURL(feedUrl); + const document = await fetchUpstream(feedUrl); + let feed: Awaited>; + try { + feed = await parser.parseString(document); + } catch (error) { + throw new RouteFailureError('parse-error', 'The Intune blog did not answer with a feed.', { cause: error }); + } - const items: DataItem[] = feed.items.map((item) => ({ + const items: DataItem[] = requireItems(feed.items ?? [], 'blog posts').map((item) => ({ title: item.title ?? '', link: item.link, description: item.content ?? item.contentSnippet ?? '', diff --git a/lib/routes/microsoftlearn/intune-in-development.ts b/lib/routes/microsoftlearn/intune-in-development.ts index 018fc827b8da..14202bc91b22 100644 --- a/lib/routes/microsoftlearn/intune-in-development.ts +++ b/lib/routes/microsoftlearn/intune-in-development.ts @@ -1,7 +1,7 @@ import { load } from 'cheerio'; import type { Route } from '@/types'; -import got from '@/utils/got'; +import { fetchUpstream, requireItems } from '@/utils/route-failure'; export const route: Route = { path: '/intune/in-development', @@ -12,8 +12,8 @@ export const route: Route = { handler: async () => { const currentUrl = 'https://learn.microsoft.com/en-us/intune/whats-new/in-development'; - const response = await got(currentUrl); - const $ = load(response.data); + const page = await fetchUpstream(currentUrl); + const $ = load(page); const items: Array<{ title: string; link: string; description: string }> = []; @@ -65,7 +65,7 @@ export const route: Route = { return { title: 'In development for Microsoft Intune', link: currentUrl, - item: items, + item: requireItems(items, 'features in development'), }; }, }; diff --git a/lib/routes/microsoftlearn/intune-whats-new.ts b/lib/routes/microsoftlearn/intune-whats-new.ts index b05dcbe4da0a..29e5b2a12f4a 100644 --- a/lib/routes/microsoftlearn/intune-whats-new.ts +++ b/lib/routes/microsoftlearn/intune-whats-new.ts @@ -1,8 +1,8 @@ import { load } from 'cheerio'; import type { Route } from '@/types'; -import got from '@/utils/got'; import { parseDate } from '@/utils/parse-date'; +import { fetchUpstream, requireItems } from '@/utils/route-failure'; export const route: Route = { path: '/intune/whats-new', @@ -13,8 +13,8 @@ export const route: Route = { handler: async () => { const currentUrl = 'https://learn.microsoft.com/en-us/intune/whats-new/'; - const response = await got(currentUrl); - const $ = load(response.data); + const page = await fetchUpstream(currentUrl); + const $ = load(page); const item: Array<{ title: string; link: string; description: string; pubDate?: Date }> = []; @@ -82,7 +82,7 @@ export const route: Route = { return { title: "What's new in Microsoft Intune", link: currentUrl, - item, + item: requireItems(item, 'features'), }; }, }; diff --git a/lib/utils/route-failure.test.ts b/lib/utils/route-failure.test.ts new file mode 100644 index 000000000000..be38a8b5534e --- /dev/null +++ b/lib/utils/route-failure.test.ts @@ -0,0 +1,178 @@ +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { delay, http, HttpResponse } from 'msw'; +import { describe, expect, it } from 'vitest'; + +import RouteFailureError, { routeFailureReasons } from '@/errors/types/route-failure'; + +// The application replaces fetch with one the mock server cannot see, so the +// mocked one is taken before the application loads and put back after. +const { default: server } = await import('@/setup.test'); +const mockedFetch = globalThis.fetch; +const { default: app } = await import('@/app'); +const { default: ofetch } = await import('@/utils/ofetch'); +const { classifyFailure, reasonHeader, upstreamStatusHeader } = await import('@/utils/route-failure'); +globalThis.fetch = mockedFetch; + +// What a request failed with. +const rejection = async (request: Promise) => { + try { + await request; + } catch (error) { + return error; + } +}; + +const learnPage = (body: string) => `
${body}
`; + +// Each route Workoho maintains, with a document of its source that holds one +// item whose title has characters outside ASCII. +const routes = [ + { + path: '/easylife365/changelogs', + source: 'https://docs.easylife365.cloud/changelogs/feed.json', + answer: () => + HttpResponse.json({ + items: [{ url: 'https://docs.easylife365.cloud/changelogs/2026/11/27/collab/aster', title: 'Größe – Aster', content_html: '

Größe

', date_modified: '2026-11-27T00:00:00.000Z', tags: ['collab'] }], + }), + }, + { + path: '/flexopus/changelog', + source: 'https://help.flexopus.com/en/ghost/api/content/posts/', + answer: () => HttpResponse.json({ posts: [{ id: '1', title: 'Größe – Räume', html: '

Größe

', url: 'https://help.flexopus.com/en/1/', published_at: '2026-11-27T00:00:00.000Z' }] }), + }, + { + path: '/microsoft/message-center', + source: 'https://raw.githubusercontent.com/merill/mc/main/%40data/messages.json', + // GitHub serves the file as text/plain. + answer: () => HttpResponse.text(JSON.stringify([{ Id: 'MC1', Title: 'Größe – update', Source: 'messageCenter', StartDateTime: '2026-11-27T00:00:00Z', Body: { Content: '

Größe

' } }])), + }, + { + path: '/microsoftlearn/entra/whats-new', + source: 'https://learn.microsoft.com/en-us/entra/fundamentals/whats-new', + answer: () => HttpResponse.html(learnPage('

November 2026

Größe – preview

Text

')), + }, + { + path: '/microsoftlearn/intune/blog', + source: 'https://techcommunity.microsoft.com/t5/s/gxcuf89792/rss/board', + answer: () => HttpResponse.xml('BlogGröße – posthttps://techcommunity.microsoft.com/1Text'), + }, + { + path: '/microsoftlearn/intune/in-development', + source: 'https://learn.microsoft.com/en-us/intune/whats-new/in-development', + answer: () => HttpResponse.html(learnPage('

App management

Größe – planned

Text

')), + }, + { + path: '/microsoftlearn/intune/whats-new', + source: 'https://learn.microsoft.com/en-us/intune/whats-new/', + answer: () => HttpResponse.html(learnPage('

Week of November 23, 2026

App management

Größe – released

Text

')), + }, +]; + +describe('classifyFailure', () => { + it('names a status the source answered with', async () => { + server.use(http.get('http://rsshub.test/gone', () => new HttpResponse(null, { status: 404 }))); + const error = await rejection(ofetch('http://rsshub.test/gone', { retry: 0 })); + expect(classifyFailure(error)).toEqual({ reason: 'upstream-status', upstreamStatus: 404 }); + }); + + it('names a source that did not answer in time', async () => { + server.use( + http.get('http://rsshub.test/slow', async () => { + await delay(500); + return HttpResponse.text('late'); + }) + ); + const error = await rejection(ofetch('http://rsshub.test/slow', { retry: 0, timeout: 50 })); + expect(classifyFailure(error)).toEqual({ reason: 'upstream-timeout' }); + }); + + it('names a source that could not be reached', async () => { + // A port nothing listens on any more: the mock server lets the request through. + const listener = createServer(); + await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve)); + const { port } = listener.address() as AddressInfo; + await new Promise((resolve) => listener.close(resolve)); + + const error = await rejection(ofetch(`http://127.0.0.1:${port}/`, { retry: 0 })); + expect(classifyFailure(error)).toEqual({ reason: 'upstream-unreachable' }); + }); + + it('names a document the route cannot read', () => { + expect(classifyFailure(new RouteFailureError('parse-error', 'changed'))).toEqual({ reason: 'parse-error' }); + expect(classifyFailure(new TypeError('x is undefined'))).toEqual({ reason: 'parse-error' }); + expect(classifyFailure(new SyntaxError('Unexpected token'))).toEqual({ reason: 'parse-error' }); + }); + + it('gives no reason for anything else', () => { + expect(classifyFailure(new Error('this route is empty'))).toBeUndefined(); + expect(classifyFailure('text')).toBeUndefined(); + expect(classifyFailure(null)).toBeUndefined(); + }); + + it('drops an upstream status that is no HTTP status', () => { + expect(classifyFailure(new RouteFailureError('upstream-status', 'odd', { upstreamStatus: 700 }))).toEqual({ reason: 'upstream-status' }); + }); +}); + +describe('a route that fails', () => { + it('answers 503 with the status its source gave', async () => { + server.use(http.get(routes[5].source, () => new HttpResponse(null, { status: 404 }))); + const response = await app.request(`${routes[5].path}?format=json`); + expect(response.status).toBe(503); + expect(response.headers.get(reasonHeader)).toBe('upstream-status'); + expect(response.headers.get(upstreamStatusHeader)).toBe('404'); + expect(response.headers.get('content-type')?.toLowerCase()).toContain('charset=utf-8'); + }); + + it('answers 503 with a parse error when the page holds no item', async () => { + server.use(http.get(routes[5].source, () => HttpResponse.html(learnPage('

Moved.

')))); + const response = await app.request(routes[5].path); + expect(response.status).toBe(503); + expect(response.headers.get(reasonHeader)).toBe('parse-error'); + expect(response.headers.get(upstreamStatusHeader)).toBeNull(); + expect(response.headers.get('content-type')?.toLowerCase()).toContain('charset=utf-8'); + }); + + it('answers 503 with a parse error when the source is not the JSON it reads', async () => { + server.use(http.get(routes[0].source, () => HttpResponse.html('Sign in'))); + const response = await app.request(routes[0].path); + expect(response.status).toBe(503); + expect(response.headers.get(reasonHeader)).toBe('parse-error'); + }); + + it('answers 503 with a parse error when the source is no feed', async () => { + server.use(http.get(routes[4].source, () => HttpResponse.html('Sign in'))); + const response = await app.request(routes[4].path); + expect(response.status).toBe(503); + expect(response.headers.get(reasonHeader)).toBe('parse-error'); + }); + + it('names no reason outside the fixed set', async () => { + const response = await app.request('/test/error'); + expect(response.status).toBe(503); + expect(response.headers.get(reasonHeader)).toBeNull(); + expect(routeFailureReasons).toEqual(['upstream-timeout', 'upstream-status', 'upstream-unreachable', 'parse-error']); + }); +}); + +describe('the routes Workoho maintains', () => { + for (const route of routes) { + for (const format of ['rss', 'atom', 'json']) { + it(`${route.path} delivers UTF-8 and says so as ${format}`, async () => { + server.use(http.get(route.source, route.answer)); + const response = await app.request(`${route.path}?format=${format}`); + expect(response.status).toBe(200); + expect(response.headers.get('content-type')?.toLowerCase()).toContain('charset=utf-8'); + expect(response.headers.get(reasonHeader)).toBeNull(); + + const text = new TextDecoder('utf-8', { fatal: true }).decode(await response.arrayBuffer()); + expect(text).toContain('Größe –'); + if (format !== 'json') { + expect(text).toMatch(/^<\?xml version="1\.0" encoding="UTF-8"\?>/); + } + }); + } + } +}); diff --git a/lib/utils/route-failure.ts b/lib/utils/route-failure.ts new file mode 100644 index 000000000000..a294ec03d5ea --- /dev/null +++ b/lib/utils/route-failure.ts @@ -0,0 +1,100 @@ +import type { RouteFailureReason } from '@/errors/types/route-failure'; +import RouteFailureError from '@/errors/types/route-failure'; +import ofetch from '@/utils/ofetch'; + +export const reasonHeader = 'RSSHub-Error-Reason'; +export const upstreamStatusHeader = 'RSSHub-Error-Upstream-Status'; + +// A reader that waits 15 seconds for the feed gets the reason instead of +// its own timeout: two attempts and the pause between them stay below that. +const upstreamTimeout = 6000; +const upstreamRetry = 1; +const upstreamRetryDelay = 500; + +const timeoutNames = new Set(['TimeoutError', 'AbortError', 'HeadersTimeoutError', 'BodyTimeoutError', 'ConnectTimeoutError']); +const timeoutCodes = new Set(['ETIMEDOUT', 'ESOCKETTIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']); +const requestErrorNames = new Set(['FetchError', 'HTTPError', 'RequestError']); + +interface Failure { + reason: RouteFailureReason; + upstreamStatus?: number; +} + +const isStatus = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 100 && value <= 599; + +const timedOut = (error: unknown, depth = 0): boolean => { + if (!error || typeof error !== 'object' || depth > 5) { + return false; + } + const { name, code, cause } = error as { name?: unknown; code?: unknown; cause?: unknown }; + return (typeof name === 'string' && timeoutNames.has(name)) || (typeof code === 'string' && timeoutCodes.has(code)) || timedOut(cause, depth + 1); +}; + +/** + * Why a route failed, when the error says so: a request to the source that + * timed out, was answered with an error status or reached nobody, or a + * document that is not what the route reads. Anything else has no reason. + */ +export const classifyFailure = (error: unknown): Failure | undefined => { + if (!error || typeof error !== 'object') { + return; + } + if (error instanceof RouteFailureError) { + return { reason: error.reason, upstreamStatus: isStatus(error.upstreamStatus) ? error.upstreamStatus : undefined }; + } + + const { name, statusCode, status, response } = error as { name?: unknown; statusCode?: unknown; status?: unknown; response?: { status?: unknown; statusCode?: unknown } }; + + if (typeof name === 'string' && requestErrorNames.has(name)) { + const upstreamStatus = [statusCode, status, response?.status, response?.statusCode].find((value) => isStatus(value)); + if (upstreamStatus !== undefined) { + return { reason: 'upstream-status', upstreamStatus }; + } + return { reason: timedOut(error) ? 'upstream-timeout' : 'upstream-unreachable' }; + } + if (name === 'TimeoutError') { + return { reason: 'upstream-timeout' }; + } + if (error instanceof TypeError || error instanceof SyntaxError) { + return { reason: 'parse-error' }; + } +}; + +/** + * The source's document for a route that names its failures: bounded in time, + * and a document that is not the expected kind is a parse error, not a crash + * further down. + */ +export const fetchUpstream = async (url: string, options: { query?: Record; responseType?: 'json' | 'text' } = {}): Promise => { + const responseType = options.responseType ?? 'text'; + const data = await ofetch(url, { + query: options.query, + // A source that serves JSON as text/plain is still parsed. + parseResponse: responseType === 'json' ? parseJson : undefined, + responseType: responseType === 'json' ? undefined : 'text', + timeout: upstreamTimeout, + retry: upstreamRetry, + retryDelay: upstreamRetryDelay, + }); + + if (responseType === 'text' && typeof data !== 'string') { + throw new RouteFailureError('parse-error', `The source at ${new URL(url).host} did not answer with text.`); + } + return data as T; +}; + +function parseJson(text: string) { + try { + return JSON.parse(text); + } catch (error) { + throw new RouteFailureError('parse-error', 'The source did not answer with JSON.', { cause: error }); + } +} + +/** Fails the route with a parse error when what it read holds no item. */ +export const requireItems = (items: T[], what: string): T[] => { + if (items.length === 0) { + throw new RouteFailureError('parse-error', `No ${what} found; the source's page may have changed.`); + } + return items; +}; From 76e33b7034c9cb1ed7630a1126f88d73c66e8a65 Mon Sep 17 00:00:00 2001 From: Alexander Kreitner <180843591+Gl4dr3x@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:09:54 +0100 Subject: [PATCH 2/3] fix(route): see an error status before parsing and bound the whole read A JSON source that answered an error status with an HTML page was reported as a parse error and not retried, because the body was parsed before the status was checked. The document is read as text now and parsed after. ofetch's timeout ends with the headers, so a deadline of 13 seconds covers the body too. A TypeError or SyntaxError from any route no longer counts as a parse error: only an error a route raises itself does. Co-Authored-By: Claude Fable 5.2 --- lib/utils/route-failure.test.ts | 21 ++++++++++++--- lib/utils/route-failure.ts | 47 +++++++++++++++++++++------------ 2 files changed, 48 insertions(+), 20 deletions(-) diff --git a/lib/utils/route-failure.test.ts b/lib/utils/route-failure.test.ts index be38a8b5534e..3a2d93882c7a 100644 --- a/lib/utils/route-failure.test.ts +++ b/lib/utils/route-failure.test.ts @@ -101,12 +101,12 @@ describe('classifyFailure', () => { it('names a document the route cannot read', () => { expect(classifyFailure(new RouteFailureError('parse-error', 'changed'))).toEqual({ reason: 'parse-error' }); - expect(classifyFailure(new TypeError('x is undefined'))).toEqual({ reason: 'parse-error' }); - expect(classifyFailure(new SyntaxError('Unexpected token'))).toEqual({ reason: 'parse-error' }); }); - it('gives no reason for anything else', () => { + it('gives no reason for anything else, a bug in a route included', () => { expect(classifyFailure(new Error('this route is empty'))).toBeUndefined(); + expect(classifyFailure(new TypeError('x is undefined'))).toBeUndefined(); + expect(classifyFailure(new SyntaxError('Unexpected token'))).toBeUndefined(); expect(classifyFailure('text')).toBeUndefined(); expect(classifyFailure(null)).toBeUndefined(); }); @@ -142,6 +142,21 @@ describe('a route that fails', () => { expect(response.headers.get(reasonHeader)).toBe('parse-error'); }); + it('names the status, not a parse error, when a JSON source answers with an error page, and tries again first', async () => { + let requests = 0; + server.use( + http.get(routes[0].source, () => { + requests++; + return HttpResponse.html('Bad gateway', { status: 502 }); + }) + ); + const response = await app.request(routes[0].path); + expect(response.status).toBe(503); + expect(response.headers.get(reasonHeader)).toBe('upstream-status'); + expect(response.headers.get(upstreamStatusHeader)).toBe('502'); + expect(requests).toBe(2); + }); + it('answers 503 with a parse error when the source is no feed', async () => { server.use(http.get(routes[4].source, () => HttpResponse.html('Sign in'))); const response = await app.request(routes[4].path); diff --git a/lib/utils/route-failure.ts b/lib/utils/route-failure.ts index a294ec03d5ea..5edb458c719a 100644 --- a/lib/utils/route-failure.ts +++ b/lib/utils/route-failure.ts @@ -6,10 +6,12 @@ export const reasonHeader = 'RSSHub-Error-Reason'; export const upstreamStatusHeader = 'RSSHub-Error-Upstream-Status'; // A reader that waits 15 seconds for the feed gets the reason instead of -// its own timeout: two attempts and the pause between them stay below that. +// its own timeout: two attempts and the pause between them stay below that, +// and so does the deadline for the whole read, body included. const upstreamTimeout = 6000; const upstreamRetry = 1; const upstreamRetryDelay = 500; +const upstreamDeadline = 13000; const timeoutNames = new Set(['TimeoutError', 'AbortError', 'HeadersTimeoutError', 'BodyTimeoutError', 'ConnectTimeoutError']); const timeoutCodes = new Set(['ETIMEDOUT', 'ESOCKETTIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']); @@ -33,7 +35,8 @@ const timedOut = (error: unknown, depth = 0): boolean => { /** * Why a route failed, when the error says so: a request to the source that * timed out, was answered with an error status or reached nobody, or a - * document that is not what the route reads. Anything else has no reason. + * document the route itself refused (`RouteFailureError`). Anything else has + * no reason: a bug in a route is not the source's fault. */ export const classifyFailure = (error: unknown): Failure | undefined => { if (!error || typeof error !== 'object') { @@ -55,39 +58,49 @@ export const classifyFailure = (error: unknown): Failure | undefined => { if (name === 'TimeoutError') { return { reason: 'upstream-timeout' }; } - if (error instanceof TypeError || error instanceof SyntaxError) { - return { reason: 'parse-error' }; - } }; /** * The source's document for a route that names its failures: bounded in time, * and a document that is not the expected kind is a parse error, not a crash - * further down. + * further down. The document is always read as text, so an error status is + * seen, and retried, before anything is parsed: a source that serves JSON as + * text/plain is still parsed, and an error page is never taken for bad JSON. */ export const fetchUpstream = async (url: string, options: { query?: Record; responseType?: 'json' | 'text' } = {}): Promise => { - const responseType = options.responseType ?? 'text'; - const data = await ofetch(url, { + const request = ofetch(url, { query: options.query, - // A source that serves JSON as text/plain is still parsed. - parseResponse: responseType === 'json' ? parseJson : undefined, - responseType: responseType === 'json' ? undefined : 'text', + responseType: 'text', timeout: upstreamTimeout, retry: upstreamRetry, retryDelay: upstreamRetryDelay, }); + const text = await withDeadline(request, new URL(url).host); - if (responseType === 'text' && typeof data !== 'string') { + if (typeof text !== 'string') { throw new RouteFailureError('parse-error', `The source at ${new URL(url).host} did not answer with text.`); } - return data as T; -}; - -function parseJson(text: string) { + if (options.responseType !== 'json') { + return text as T; + } try { return JSON.parse(text); } catch (error) { - throw new RouteFailureError('parse-error', 'The source did not answer with JSON.', { cause: error }); + throw new RouteFailureError('parse-error', `The source at ${new URL(url).host} did not answer with JSON.`, { cause: error }); + } +}; + +// ofetch's timeout ends when the headers arrive; a source that then stalls +// its body is cut off here. The request itself is left to end on its own. +async function withDeadline(request: Promise, host: string): Promise { + let timer: ReturnType | undefined; + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => reject(new RouteFailureError('upstream-timeout', `The source at ${host} did not answer within ${upstreamDeadline / 1000} seconds.`)), upstreamDeadline); + }); + try { + return await Promise.race([request, deadline]); + } finally { + clearTimeout(timer); } } From b5ba024980c24f14e8db69790088d2940ce1985c Mon Sep 17 00:00:00 2001 From: Alexander Kreitner <180843591+Gl4dr3x@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:22:20 +0100 Subject: [PATCH 3/3] fix(route): abort a stalled source, keep failures out of caches The 13 second deadline answered the reader but left the request running when a source stalled its body. Each attempt now carries its own signal with six seconds for headers and body, and the retry is fetchUpstream's own: once, on a timeout, an unreachable source or a status that may pass (408, 425, 429, 500, 502, 503, 504). A failing route's 503 kept the feed's public max-age from the header middleware; it answers no-store now. A connect that timed out on one of several addresses arrives as an AggregateError and is named a timeout, not unreachable. The upstream status header is set in an if. Co-Authored-By: Claude Fable 5.2 --- lib/errors/index.tsx | 7 +++- lib/utils/route-failure.test.ts | 66 ++++++++++++++++++++++++++++++++- lib/utils/route-failure.ts | 58 +++++++++++++++++------------ 3 files changed, 105 insertions(+), 26 deletions(-) diff --git a/lib/errors/index.tsx b/lib/errors/index.tsx index 4b28d9051494..4a1b4a69a36d 100644 --- a/lib/errors/index.tsx +++ b/lib/errors/index.tsx @@ -56,6 +56,8 @@ export const errorHandler: ErrorHandler = (error, ctx) => { case 'HTTPError': case 'RequestError': case 'FetchError': + // The header middleware set a public max-age for the feed; a failure is not kept. + ctx.header('Cache-Control', 'no-store'); ctx.status(503); break; case 'RequestInProgressError': @@ -70,13 +72,16 @@ export const errorHandler: ErrorHandler = (error, ctx) => { errorMessage += 'The route does not exist or has been deleted.'; break; default: + ctx.header('Cache-Control', 'no-store'); ctx.status(503); break; } const failure = classifyFailure(error); if (failure) { ctx.header(reasonHeader, failure.reason); - failure.upstreamStatus && ctx.header(upstreamStatusHeader, String(failure.upstreamStatus)); + if (failure.upstreamStatus) { + ctx.header(upstreamStatusHeader, String(failure.upstreamStatus)); + } } const message = `${error.name}: ${errorMessage}`; diff --git a/lib/utils/route-failure.test.ts b/lib/utils/route-failure.test.ts index 3a2d93882c7a..ec7af323a510 100644 --- a/lib/utils/route-failure.test.ts +++ b/lib/utils/route-failure.test.ts @@ -2,7 +2,7 @@ import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { delay, http, HttpResponse } from 'msw'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import RouteFailureError, { routeFailureReasons } from '@/errors/types/route-failure'; @@ -12,7 +12,9 @@ const { default: server } = await import('@/setup.test'); const mockedFetch = globalThis.fetch; const { default: app } = await import('@/app'); const { default: ofetch } = await import('@/utils/ofetch'); -const { classifyFailure, reasonHeader, upstreamStatusHeader } = await import('@/utils/route-failure'); +const { classifyFailure, fetchUpstream, reasonHeader, upstreamStatusHeader } = await import('@/utils/route-failure'); +// The application's own fetch, for a test against a real listener. +const appFetch = globalThis.fetch; globalThis.fetch = mockedFetch; // What a request failed with. @@ -99,6 +101,17 @@ describe('classifyFailure', () => { expect(classifyFailure(error)).toEqual({ reason: 'upstream-unreachable' }); }); + it('names a connect that timed out on every address of the source', () => { + const connect = Object.assign(new AggregateError([Object.assign(new Error('v6'), { code: 'ETIMEDOUT' }), Object.assign(new Error('v4'), { code: 'ECONNREFUSED' })], 'connect failed'), { code: 'ETIMEDOUT' }); + const inner = new AggregateError([Object.assign(new Error('v6'), { code: 'ENETUNREACH' }), Object.assign(new Error('v4'), { code: 'UND_ERR_CONNECT_TIMEOUT' })], 'connect failed'); + const refused = new AggregateError([Object.assign(new Error('v4'), { code: 'ECONNREFUSED' })], 'connect failed'); + const fetchError = (cause: unknown) => Object.assign(new Error('fetch failed', { cause: new TypeError('fetch failed', { cause }) }), { name: 'FetchError' }); + + expect(classifyFailure(fetchError(connect))).toEqual({ reason: 'upstream-timeout' }); + expect(classifyFailure(fetchError(inner))).toEqual({ reason: 'upstream-timeout' }); + expect(classifyFailure(fetchError(refused))).toEqual({ reason: 'upstream-unreachable' }); + }); + it('names a document the route cannot read', () => { expect(classifyFailure(new RouteFailureError('parse-error', 'changed'))).toEqual({ reason: 'parse-error' }); }); @@ -116,6 +129,53 @@ describe('classifyFailure', () => { }); }); +describe('fetchUpstream', () => { + it('aborts a source that sends its headers and then stalls the body, on each of its two attempts', async () => { + // A real listener read with the application's own fetch: the mock server + // does not tie a body to the request's signal. + let requests = 0; + let closed = 0; + const listener = createServer((request, response) => { + requests++; + request.socket.on('close', () => closed++); + // Headers and a first chunk at once, then nothing. + response.writeHead(200, { 'Content-Type': 'application/json' }); + response.write('{"items":'); + }); + await new Promise((resolve) => listener.listen(0, '127.0.0.1', resolve)); + const { port } = listener.address() as AddressInfo; + + globalThis.fetch = appFetch; + try { + const started = Date.now(); + const error = await rejection(fetchUpstream(`http://127.0.0.1:${port}/`, { responseType: 'json', timeout: 600 })); + + expect(classifyFailure(error)).toEqual({ reason: 'upstream-timeout' }); + expect(requests).toBe(2); + expect(Date.now() - started).toBeLessThan(5000); + // The connections are gone, not left to the client's own body timeout. + await vi.waitFor(() => expect(closed).toBe(2), { timeout: 2000 }); + } finally { + globalThis.fetch = mockedFetch; + listener.closeAllConnections(); + await new Promise((resolve) => listener.close(resolve)); + } + }); + + it('does not try again when the source answers with a status that will not change', async () => { + let requests = 0; + server.use( + http.get('http://rsshub.test/forbidden', () => { + requests++; + return new HttpResponse('no', { status: 403 }); + }) + ); + const error = await rejection(fetchUpstream('http://rsshub.test/forbidden')); + expect(classifyFailure(error)).toEqual({ reason: 'upstream-status', upstreamStatus: 403 }); + expect(requests).toBe(1); + }); +}); + describe('a route that fails', () => { it('answers 503 with the status its source gave', async () => { server.use(http.get(routes[5].source, () => new HttpResponse(null, { status: 404 }))); @@ -123,6 +183,8 @@ describe('a route that fails', () => { expect(response.status).toBe(503); expect(response.headers.get(reasonHeader)).toBe('upstream-status'); expect(response.headers.get(upstreamStatusHeader)).toBe('404'); + // A proxy must not keep serving the failure for the feed's max-age. + expect(response.headers.get('cache-control')).toBe('no-store'); expect(response.headers.get('content-type')?.toLowerCase()).toContain('charset=utf-8'); }); diff --git a/lib/utils/route-failure.ts b/lib/utils/route-failure.ts index 5edb458c719a..296b5889d224 100644 --- a/lib/utils/route-failure.ts +++ b/lib/utils/route-failure.ts @@ -6,12 +6,11 @@ export const reasonHeader = 'RSSHub-Error-Reason'; export const upstreamStatusHeader = 'RSSHub-Error-Upstream-Status'; // A reader that waits 15 seconds for the feed gets the reason instead of -// its own timeout: two attempts and the pause between them stay below that, -// and so does the deadline for the whole read, body included. +// its own timeout: two attempts, each with its body, and the pause between +// them stay below that. const upstreamTimeout = 6000; -const upstreamRetry = 1; const upstreamRetryDelay = 500; -const upstreamDeadline = 13000; +const upstreamRetryStatuses = new Set([408, 425, 429, 500, 502, 503, 504]); const timeoutNames = new Set(['TimeoutError', 'AbortError', 'HeadersTimeoutError', 'BodyTimeoutError', 'ConnectTimeoutError']); const timeoutCodes = new Set(['ETIMEDOUT', 'ESOCKETTIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT']); @@ -28,8 +27,9 @@ const timedOut = (error: unknown, depth = 0): boolean => { if (!error || typeof error !== 'object' || depth > 5) { return false; } - const { name, code, cause } = error as { name?: unknown; code?: unknown; cause?: unknown }; - return (typeof name === 'string' && timeoutNames.has(name)) || (typeof code === 'string' && timeoutCodes.has(code)) || timedOut(cause, depth + 1); + // A connect to a host with several addresses fails as an AggregateError, one error an address. + const { name, code, cause, errors } = error as { name?: unknown; code?: unknown; cause?: unknown; errors?: unknown }; + return (typeof name === 'string' && timeoutNames.has(name)) || (typeof code === 'string' && timeoutCodes.has(code)) || timedOut(cause, depth + 1) || (Array.isArray(errors) && errors.some((inner) => timedOut(inner, depth + 1))); }; /** @@ -67,15 +67,8 @@ export const classifyFailure = (error: unknown): Failure | undefined => { * seen, and retried, before anything is parsed: a source that serves JSON as * text/plain is still parsed, and an error page is never taken for bad JSON. */ -export const fetchUpstream = async (url: string, options: { query?: Record; responseType?: 'json' | 'text' } = {}): Promise => { - const request = ofetch(url, { - query: options.query, - responseType: 'text', - timeout: upstreamTimeout, - retry: upstreamRetry, - retryDelay: upstreamRetryDelay, - }); - const text = await withDeadline(request, new URL(url).host); +export const fetchUpstream = async (url: string, options: { query?: Record; responseType?: 'json' | 'text'; timeout?: number } = {}): Promise => { + const text = await readWithRetry(url, options.query, options.timeout ?? upstreamTimeout); if (typeof text !== 'string') { throw new RouteFailureError('parse-error', `The source at ${new URL(url).host} did not answer with text.`); @@ -90,20 +83,39 @@ export const fetchUpstream = async (url: string, options: { query?: } }; -// ofetch's timeout ends when the headers arrive; a source that then stalls -// its body is cut off here. The request itself is left to end on its own. -async function withDeadline(request: Promise, host: string): Promise { - let timer: ReturnType | undefined; - const deadline = new Promise((_, reject) => { - timer = setTimeout(() => reject(new RouteFailureError('upstream-timeout', `The source at ${host} did not answer within ${upstreamDeadline / 1000} seconds.`)), upstreamDeadline); - }); +// One attempt, headers and body, within `timeout`. ofetch's own timeout ends +// when the headers arrive, so the signal is ours: it aborts the request +// itself, and a source that stalls its body leaves no connection behind. +async function readOnce(url: string, query: Record | undefined, timeout: number): Promise { + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(new RouteFailureError('upstream-timeout', `The source at ${new URL(url).host} did not answer within ${timeout / 1000} seconds.`)), timeout); try { - return await Promise.race([request, deadline]); + return await ofetch(url, { query, responseType: 'text', signal: controller.signal, retry: 0 }); + } catch (error) { + // An abort surfaces wrapped or bare, depending on where it hit. + throw controller.signal.aborted ? controller.signal.reason : error; } finally { clearTimeout(timer); } } +const retryable = (error: unknown) => { + const failure = classifyFailure(error); + return failure !== undefined && failure.reason !== 'parse-error' && (failure.upstreamStatus === undefined || upstreamRetryStatuses.has(failure.upstreamStatus)); +}; + +async function readWithRetry(url: string, query: Record | undefined, timeout: number): Promise { + try { + return await readOnce(url, query, timeout); + } catch (error) { + if (!retryable(error)) { + throw error; + } + } + await new Promise((resolve) => setTimeout(resolve, upstreamRetryDelay)); + return readOnce(url, query, timeout); +} + /** Fails the route with a parse error when what it read holds no item. */ export const requireItems = (items: T[], what: string): T[] => { if (items.length === 0) {