diff --git a/lib/errors/index.tsx b/lib/errors/index.tsx index b78603815c00..4a1b4a69a36d 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'; @@ -55,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': @@ -69,9 +72,17 @@ 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); + if (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..ec7af323a510 --- /dev/null +++ b/lib/utils/route-failure.test.ts @@ -0,0 +1,255 @@ +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; + +import { delay, http, HttpResponse } from 'msw'; +import { describe, expect, it, vi } 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, 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. +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 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' }); + }); + + 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(); + }); + + it('drops an upstream status that is no HTTP status', () => { + expect(classifyFailure(new RouteFailureError('upstream-status', 'odd', { upstreamStatus: 700 }))).toEqual({ reason: 'upstream-status' }); + }); +}); + +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 }))); + 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'); + // 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'); + }); + + 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('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); + 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..296b5889d224 --- /dev/null +++ b/lib/utils/route-failure.ts @@ -0,0 +1,125 @@ +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, each with its body, and the pause between +// them stay below that. +const upstreamTimeout = 6000; +const upstreamRetryDelay = 500; +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']); +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; + } + // 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))); +}; + +/** + * 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 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') { + 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' }; + } +}; + +/** + * 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. 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'; 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.`); + } + if (options.responseType !== 'json') { + return text as T; + } + try { + return JSON.parse(text); + } catch (error) { + throw new RouteFailureError('parse-error', `The source at ${new URL(url).host} did not answer with JSON.`, { cause: error }); + } +}; + +// 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 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) { + throw new RouteFailureError('parse-error', `No ${what} found; the source's page may have changed.`); + } + return items; +};