From 2b2697364ae53b3a33c59916bef2af553f237a6d Mon Sep 17 00:00:00 2001 From: jm Date: Tue, 3 Nov 2026 00:12:14 +0100 Subject: [PATCH 1/2] JCU/perf(ssr): answer handle redirects without SSR (dataquest-dev/dspace-customers#1121) --- config/config.yml | 5 + package.json | 1 + scripts/test-handle-redirect.js | 200 +++++++++++++++++++++++++++++ server.ts | 11 ++ src/backend/handle-redirect.ts | 103 +++++++++++++++ src/config/config.server.ts | 2 +- src/config/default-app-config.ts | 9 ++ src/config/ssr-config.interface.ts | 9 ++ 8 files changed, 339 insertions(+), 1 deletion(-) create mode 100644 scripts/test-handle-redirect.js create mode 100644 src/backend/handle-redirect.ts diff --git a/config/config.yml b/config/config.yml index 3171e9bbdd5..6b52613e9dd 100644 --- a/config/config.yml +++ b/config/config.yml @@ -51,6 +51,11 @@ themes: href: assets/custom/images/favicons/manifest.webmanifest ssr: + # One anonymous REST lookup instead of an Angular render just to send a handle's 301. + # Search misses and errors fall through to Angular. DSPACE_SSR_HANDLEREDIRECT_ENABLED=false disables it. + handleRedirect: + enabled: true + timeoutMs: 1000 excludePathPatterns: - pattern: "^/communities/[a-f0-9-]{36}/browse(/.*)?$" flag: "i" diff --git a/package.json b/package.json index 434657a332f..d38ee947320 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "ng": "ng", "test:rest": "ts-node --project ./tsconfig.ts-node.json scripts/test-rest.ts", "test:ssr-cache-stats": "node --test scripts/test-ssr-cache-stats.js", + "test:handle-redirect": "node --test scripts/test-handle-redirect.js", "start": "npm run start:prod", "start:dev": "cross-env NODE_ENV=development npm run serve --watch", "start:prod": "npm run build:prod && cross-env NODE_ENV=production npm run serve:ssr", diff --git a/scripts/test-handle-redirect.js b/scripts/test-handle-redirect.js new file mode 100644 index 00000000000..59235450d0e --- /dev/null +++ b/scripts/test-handle-redirect.js @@ -0,0 +1,200 @@ +const assert = require('node:assert/strict'); +const { once } = require('node:events'); +const { createServer } = require('node:http'); +const { test } = require('node:test'); +const express = require('express'); +const cookieParser = require('cookie-parser'); + +process.env.TS_NODE_PROJECT = 'tsconfig.ts-node.json'; +process.env.TS_NODE_COMPILER_OPTIONS = JSON.stringify({ module: 'commonjs', moduleResolution: 'node10' }); +require('ts-node/register/transpile-only'); +const { createHandleRedirectHandler } = require('../src/backend/handle-redirect.ts'); + +const uuid = '0a5dea88-11ae-445f-851e-e336e06b1278'; +const handle = '20.500.14390/47366'; +const handleUrl = `/handle/${handle}`; +const object = (type = 'item', metadata = {}) => ({ type, uuid, handle, metadata }); +const searchResult = (dso) => ({ _embedded: { searchResult: { + page: { totalElements: dso ? 1 : 0 }, + _embedded: { objects: dso ? [{ _embedded: { indexableObject: dso } }] : [] } +} } }); + +async function listen(server) { + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + return `http://127.0.0.1:${server.address().port}`; +} + +async function fixture(t, options = {}) { + const requests = []; + const backend = createServer((req, res) => { + requests.push({ url: req.url, headers: req.headers, method: req.method }); + if (options.backend) { + options.backend(req, res); + } else { + res.setHeader('Content-Type', 'application/hal+json'); + res.end(JSON.stringify(options.data ?? searchResult(object()))); + } + }); + const rest = await listen(backend); + const app = express(); + app.use(cookieParser()); + const router = express.Router(); + router.get(/^\/handle\/[^/]+\/[^/]+\/?$/, createHandleRedirectHandler( + `${rest}/internal/server/`, options.namespace ?? '/', + { enabled: options.enabled ?? true, timeoutMs: options.timeoutMs ?? 1000 }, options.fetchRest + )); + router.use((req, res) => res.status(418).json({ + method: req.method, url: req.url, originalUrl: req.originalUrl, cookies: req.cookies + })); + app.use(options.namespace ?? '/', router); + const ui = createServer(app); + const base = await listen(ui); + t.after(async () => { + for (const server of [ui, backend]) { + const closed = new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + server.closeAllConnections(); + await closed; + } + }); + return { requests, get: (path = handleUrl, init = {}) => fetch(base + path, { ...init, redirect: 'manual' }) }; +} + +for (const [type, path] of [['item', 'items'], ['community', 'communities'], ['collection', 'collections']]) { + test(`${type} redirects with one anonymous server-side lookup`, async (t) => { + const { get, requests } = await fixture(t, { data: searchResult(object(type)) }); + const response = await get(handleUrl, { headers: { Cookie: 'preferences=cs; DSPACE-XSRF-COOKIE=secret' } }); + assert.equal(response.status, 301); + assert.equal(response.headers.get('location'), `/${path}/${uuid}`); + assert.equal(requests.length, 1); + const lookup = new URL(requests[0].url, 'http://internal'); + assert.equal(lookup.pathname, '/internal/server/api/discover/search/objects'); + assert.equal(lookup.searchParams.get('query'), `handle:"${handle}"`); + assert.equal(lookup.searchParams.get('size'), '2'); + assert.equal(requests[0].method, 'GET'); + assert.equal(requests[0].headers.cookie, undefined); + assert.equal(requests[0].headers.authorization, undefined); + }); +} + +test('entity redirects use the first visible metadata value, lowercase and URL encoding', async (t) => { + const dso = object('item', { 'dspace.entity.type': [{ value: 'Research Project/É' }, { value: 'Person' }] }); + dso.entityType = 'Ignored'; + const { get } = await fixture(t, { data: searchResult(dso) }); + const response = await get(); + assert.equal(response.status, 301); + assert.equal(response.headers.get('location'), `/entities/research%20project%2F%C3%A9/${uuid}`); +}); + +test('entityType property alone does not determine the route (hidden or withdrawn metadata)', async (t) => { + const { get } = await fixture(t, { data: searchResult({ ...object(), entityType: 'Person', withdrawn: true }) }); + assert.equal((await get()).headers.get('location'), `/items/${uuid}`); +}); + +for (const suffix of ['/', '?x=1', '/?x=1']) { + test(`trailing slash/query ${suffix} is dropped`, async (t) => { + const { get } = await fixture(t); + const response = await get(handleUrl + suffix); + assert.equal(response.status, 301); + assert.equal(response.headers.get('location'), `/items/${uuid}`); + }); +} + +test('HEAD redirects like GET, uses a backend GET and returns no body', async (t) => { + const { get, requests } = await fixture(t); + const response = await get(handleUrl, { method: 'HEAD' }); + assert.equal(response.status, 301); + assert.equal(response.headers.get('location'), `/items/${uuid}`); + assert.equal(await response.text(), ''); + assert.equal(requests[0].method, 'GET'); +}); + +for (const namespace of ['/repository', '/repository/']) { + test(`configured namespace ${namespace} is preserved exactly once`, async (t) => { + const { get } = await fixture(t, { namespace }); + const response = await get('/repository' + handleUrl); + assert.equal(response.status, 301); + assert.equal(response.headers.get('location'), `/repository/items/${uuid}`); + }); +} + +const invalidResults = [ + ['unknown or unindexed handle', searchResult()], + ['stale index handle', searchResult({ ...object(), handle: 'other/handle' })], + ['unsupported bitstream', searchResult(object('bitstream'))], + ['invalid UUID', searchResult({ ...object(), uuid: '../other' })], + ['missing metadata', searchResult({ ...object(), metadata: undefined })], + ['malformed entity metadata', searchResult(object('item', { 'dspace.entity.type': [{}] }))], + ['missing permission-filtered object', { _embedded: { searchResult: { page: { totalElements: 1 }, _embedded: { objects: [{}] } } } }], + ['ambiguous results', { _embedded: { searchResult: { page: { totalElements: 2 }, _embedded: { objects: [] } } } }], + ['unexpected response shape', {}] +]; +for (const [description, data] of invalidResults) { + test(`${description} falls through with request unchanged`, async (t) => { + const { get } = await fixture(t, { data }); + const url = handleUrl + '/?x=1'; + const response = await get(url); + assert.equal(response.status, 418); + assert.equal(response.headers.get('location'), null); + assert.deepEqual(await response.json(), { method: 'GET', url, originalUrl: url, cookies: {} }); + }); +} + +for (const status of [301, 302, 401, 403, 404, 500]) { + test(`backend ${status} falls through without following redirects`, async (t) => { + const { get, requests } = await fixture(t, { backend: (_req, res) => { + res.writeHead(status, { Location: '/must-not-follow' }); res.end(); + } }); + assert.equal((await get()).status, 418); + assert.equal(requests.length, 1); + }); +} + +test('invalid JSON falls through', async (t) => { + const { get } = await fixture(t, { backend: (_req, res) => res.end('not JSON') }); + assert.equal((await get()).status, 418); +}); + +test('network error falls through', async (t) => { + const { get } = await fixture(t, { fetchRest: async () => { throw new Error('ECONNREFUSED'); } }); + assert.equal((await get()).status, 418); +}); + +for (const bodyStarted of [false, true]) { + test(`backend timeout ${bodyStarted ? 'during body read' : 'before headers'} falls through`, async (t) => { + const { get } = await fixture(t, { timeoutMs: 50, backend: (_req, res) => { + if (bodyStarted) { res.writeHead(200); res.write('{'); } + // Deliberately never complete: the handler must abort instead of blocking SSR. + } }); + assert.equal((await get()).status, 418); + }); +} + +test('config disabled skips REST', async (t) => { + const { get, requests } = await fixture(t, { enabled: false }); + assert.equal((await get()).status, 418); + assert.equal(requests.length, 0); +}); + +for (const path of [handleUrl + '/full', handleUrl + '/file.pdf', '/bitstream' + handleUrl, + '/handle/handle/suffix', handleUrl + ';matrix=1', '/handle/20.500.14390/%34%37%33%36%36']) { + test(`unhandled path ${path} skips REST`, async (t) => { + const { get, requests } = await fixture(t); + assert.equal((await get(path)).status, 418); + assert.equal(requests.length, 0); + }); +} + +test('POST skips REST', async (t) => { + const { get, requests } = await fixture(t); + assert.equal((await get(handleUrl, { method: 'POST' })).status, 418); + assert.equal(requests.length, 0); +}); + +for (const headers of [{ Cookie: 'dsAuthInfo=private' }, { Authorization: 'Bearer private' }]) { + test(`authenticated request ${Object.keys(headers)[0]} stays in Angular`, async (t) => { + const { get, requests } = await fixture(t); + assert.equal((await get(handleUrl, { headers })).status, 418); + assert.equal(requests.length, 0); + }); +} diff --git a/server.ts b/server.ts index 47e20ae5423..2a4f9b587d7 100644 --- a/server.ts +++ b/server.ts @@ -59,6 +59,7 @@ import { RESPONSE, } from './src/express.tokens'; import { SsrExcludePatterns } from "./src/config/ssr-config.interface"; +import { createHandleRedirectHandler } from './src/backend/handle-redirect'; import { createSsrCacheStatsHandler, isDirectLoopbackRequest, @@ -204,6 +205,16 @@ export function app() { server.use(limiter); } + /** + * Resolve handles before the catch-all render: otherwise Angular spends CPU only to send a 301. + * Uncertain lookups stay in Angular, including objects missing from the search index. + */ + if (environment.ssr.enabled) { + router.get(/^\/handle\/[^/]+\/[^/]+\/?$/, createHandleRedirectHandler( + REST_BASE_URL, environment.ui.nameSpace, environment.ssr.handleRedirect, + )); + } + /* * Serve static resources (images, i18n messages, …) * Handle pre-compressed files with [express-static-gzip](https://github.com/tkoenig89/express-static-gzip) diff --git a/src/backend/handle-redirect.ts b/src/backend/handle-redirect.ts new file mode 100644 index 00000000000..92a9f6f08ae --- /dev/null +++ b/src/backend/handle-redirect.ts @@ -0,0 +1,103 @@ +import { + NextFunction, + Request, + RequestHandler, + Response, +} from 'express'; + +import { TOKENITEM } from '../app/core/auth/models/auth-token-info.model'; +import { HandleRedirectConfig } from '../config/ssr-config.interface'; + +/** + * Avoid rendering Angular just to send its permanent handle redirect. PID /find only returns a + * REST Location, which cannot distinguish /items from /entities. Discovery's exact handle lookup + * embeds the permission-filtered, current database object (not indexed metadata) in one call. + * Index misses, stale handles and anything uncertain keep the existing Angular behaviour. + */ +export function createHandleRedirectHandler( + restBaseUrl: string, + nameSpace: string, + config: HandleRedirectConfig, + fetchRest: typeof fetch = fetch, +): RequestHandler { + const handler = async (req: Request, res: Response, next: NextFunction) => { + // Keep unusual identifiers, matrix parameters and deeper/legacy bitstream paths in Angular. + const match = /^\/handle\/(\d+(?:\.\d+)*)\/([a-zA-Z0-9._-]+)\/?$/.exec(req.path); + if (!config?.enabled || (req.method !== 'GET' && req.method !== 'HEAD') || !match) { + next(); + return; + } + // Logged-in users may see different entity metadata or need the end-user agreement guard. + if (req.cookies?.[TOKENITEM] || req.headers.authorization) { + next(); + return; + } + + let path: string; + try { + const handle = `${match[1]}/${match[2]}`; + const url = new URL(`${restBaseUrl.replace(/\/$/, '')}/api/discover/search/objects`); + url.searchParams.set('query', `handle:"${handle}"`); + url.searchParams.set('size', '2'); + const response = await fetchRest(url, { + // Never follow a redirect or copy request headers: this lookup must remain anonymous. + redirect: 'manual', + headers: { Accept: 'application/hal+json' }, + signal: AbortSignal.timeout(config.timeoutMs), + }); + if (!response.ok) { + await response.body?.cancel(); + } else { + path = handlePath(await response.json(), handle); + } + } catch { + // Includes the body read in the timeout; SSR still owns errors, login and not-found pages. + } + + if (path) { + // Match DsoRedirectService: configured UI namespace, no incoming query, relative Location. + res.redirect(301, nameSpace.replace(/\/$/, '') + path); + } else { + next(); + } + }; + // Express 4 does not catch rejected promises from async middleware. + return (req, res, next) => { + void handler(req, res, next).catch(next); + }; +} + +function handlePath(data: any, handle: string): string | undefined { + const result = data?._embedded?.searchResult; + const objects = result?._embedded?.objects; + if (result?.page?.totalElements !== 1 || !Array.isArray(objects) || objects.length !== 1) { + return; + } + const dso = objects[0]?._embedded?.indexableObject; + if (dso?.handle !== handle || typeof dso.uuid !== 'string' || + !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(dso.uuid)) { + return; + } + switch (dso.type) { + case 'community': + return `/communities/${dso.uuid}`; + case 'collection': + return `/collections/${dso.uuid}`; + case 'item': { + if (!dso.metadata || typeof dso.metadata !== 'object' || Array.isArray(dso.metadata)) { + return; + } + const values = dso.metadata['dspace.entity.type']; + if (values !== undefined && (!Array.isArray(values) || + (values.length > 0 && (typeof values[0]?.value !== 'string' && values[0]?.value !== null)))) { + return; + } + // Like getItemPageRoute, use the first visible metadata value, not the entityType property: + // withdrawn items and hidden metadata can make those two values differ. + const entityType = values?.[0]?.value; + return entityType ? `/entities/${encodeURIComponent(entityType.toLowerCase())}/${dso.uuid}` : `/items/${dso.uuid}`; + } + default: + return; + } +} diff --git a/src/config/config.server.ts b/src/config/config.server.ts index 6ba7a7f1300..1146433944b 100644 --- a/src/config/config.server.ts +++ b/src/config/config.server.ts @@ -266,7 +266,7 @@ export const buildAppConfig = (destConfigPath?: string, mapping?: ServerHashedFi mapping.add(destConfigPath, content); // Only worth doing when we serve CSR: with SSR the configuration reaches the browser in the // transfer state and the file is never fetched, so the preload is spent on nothing. Note that - // DefaultAppConfig carries no `ssr` block, so `enabled` is undefined unless config.yml sets + // DefaultAppConfig does not set `ssr.enabled`, so it is undefined unless config.yml sets // it; testing for `false` is what keeps the link out of an SSR deployment. if ((appConfig as BuildConfig).ssr?.enabled === false) { // If we're serving for CSR we can retrieve the configuration before JS is loaded/executed diff --git a/src/config/default-app-config.ts b/src/config/default-app-config.ts index 67a088cc29c..c360cb9dba1 100644 --- a/src/config/default-app-config.ts +++ b/src/config/default-app-config.ts @@ -27,6 +27,7 @@ import { INotificationBoardOptions } from './notifications-config.interfaces'; import { QualityAssuranceConfig } from './quality-assurance.config'; import { SearchConfig } from './search-page-config.interface'; import { ServerConfig } from './server-config.interface'; +import { SSRConfig } from './ssr-config.interface'; import { SubmissionConfig } from './submission-config.interface'; import { SuggestionConfig } from './suggestion-config.interfaces'; import { ThemeConfig } from './theme.config'; @@ -38,6 +39,14 @@ export class DefaultAppConfig implements AppConfig { // NOTE: will log all redux actions and transfers in console debug = false; + // Other SSR defaults come from the build environment; keep its enabled flag intact. + ssr: Pick = { + handleRedirect: { + enabled: true, + timeoutMs: 1000, + }, + }; + // Angular express server settings // NOTE: these must be 'synced' with the 'dspace.ui.url' setting in your backend's local.cfg. ui: UIServerConfig = { diff --git a/src/config/ssr-config.interface.ts b/src/config/ssr-config.interface.ts index 16bb3f54d66..f87f217c486 100644 --- a/src/config/ssr-config.interface.ts +++ b/src/config/ssr-config.interface.ts @@ -5,7 +5,16 @@ export interface SsrExcludePatterns { flag?: string; } +export interface HandleRedirectConfig { + enabled: boolean; + /** Total anonymous REST lookup timeout, including the response body, in milliseconds. */ + timeoutMs: number; +} + export interface SSRConfig extends Config { + /** Resolve ordinary handle redirects without rendering Angular (enabled by default for JCU). */ + handleRedirect?: HandleRedirectConfig; + /** * A boolean flag indicating whether the SSR configuration is enabled * Defaults to true. From f1c537b3cbe4a68558f484f42f98c7d42d5230dd Mon Sep 17 00:00:00 2001 From: jm Date: Tue, 3 Nov 2026 00:49:19 +0100 Subject: [PATCH 2/2] JCU/perf(ssr): handle redirect review fixes (dataquest-dev/dspace-customers#1121) - 301 carries cache.control (max-age=604800), as the Angular redirect does today via addCacheControl - failed lookups (non-OK, errors, timeouts) are warned at most once per minute, with the count - missing or invalid timeoutMs falls back to 1000 ms instead of aborting every lookup - a body left unread by a failed JSON parse or abort is cancelled --- scripts/test-handle-redirect.js | 67 ++++++++++++++++++++++++++++++++- server.ts | 2 + src/backend/handle-redirect.ts | 56 +++++++++++++++++++++++++-- 3 files changed, 120 insertions(+), 5 deletions(-) diff --git a/scripts/test-handle-redirect.js b/scripts/test-handle-redirect.js index 59235450d0e..49207446cbc 100644 --- a/scripts/test-handle-redirect.js +++ b/scripts/test-handle-redirect.js @@ -42,7 +42,8 @@ async function fixture(t, options = {}) { const router = express.Router(); router.get(/^\/handle\/[^/]+\/[^/]+\/?$/, createHandleRedirectHandler( `${rest}/internal/server/`, options.namespace ?? '/', - { enabled: options.enabled ?? true, timeoutMs: options.timeoutMs ?? 1000 }, options.fetchRest + { enabled: options.enabled ?? true, timeoutMs: options.timeoutMs ?? 1000 }, + { fetchRest: options.fetchRest, cacheControl: options.cacheControl, warn: options.warn ?? (() => undefined), now: options.now } )); router.use((req, res) => res.status(418).json({ method: req.method, url: req.url, originalUrl: req.originalUrl, cookies: req.cookies @@ -198,3 +199,67 @@ for (const headers of [{ Cookie: 'dsAuthInfo=private' }, { Authorization: 'Beare assert.equal(requests.length, 0); }); } + +test('301 carries the configured Cache-Control, like the Angular redirect via addCacheControl', async (t) => { + const { get } = await fixture(t, { cacheControl: 'max-age=604800' }); + const response = await get(); + assert.equal(response.status, 301); + assert.equal(response.headers.get('cache-control'), 'max-age=604800'); +}); + +test('fall-through does not set Cache-Control', async (t) => { + const { get } = await fixture(t, { cacheControl: 'max-age=604800', data: searchResult(null) }); + const response = await get(); + assert.equal(response.status, 418); + assert.equal(response.headers.get('cache-control'), null); +}); + +test('failures are warned at most once per minute, with the count', async (t) => { + const warnings = []; + let clock = 0; + const { get } = await fixture(t, { + backend: (_req, res) => { res.statusCode = 500; res.end('boom'); }, + warn: (message) => warnings.push(message), now: () => clock, + }); + for (const at of [0, 1000, 2000]) { + clock = at; + assert.equal((await get()).status, 418); + } + assert.equal(warnings.length, 1); + assert.match(warnings[0], /HTTP 500/); + clock = 61_000; + assert.equal((await get()).status, 418); + assert.equal(warnings.length, 2); + assert.match(warnings[1], /3 failure\(s\)/); +}); + +test('a successful lookup or a search miss is not a failure', async (t) => { + const warnings = []; + const ok = await fixture(t, { warn: (message) => warnings.push(message) }); + assert.equal((await ok.get()).status, 301); + const miss = await fixture(t, { data: searchResult(null), warn: (message) => warnings.push(message) }); + assert.equal((await miss.get()).status, 418); + assert.deepEqual(warnings, []); +}); + +for (const timeoutMs of [undefined, 0, -5, Number.NaN, 'abc']) { + test(`invalid timeoutMs ${String(timeoutMs)} uses the 1000 ms default instead of aborting every lookup`, async (t) => { + const { get } = await fixture(t, { timeoutMs }); + // fixture() turns undefined into 1000 itself; pass the raw value through for the others. + assert.equal((await get()).status, 301); + }); +} + +test('a body left unread by failed JSON parsing is cancelled', async (t) => { + let cancelled = false; + const fetchRest = async () => { + const body = new ReadableStream({ pull: (c) => c.enqueue(new TextEncoder().encode('{"not json')), cancel: () => { cancelled = true; } }); + const response = new Response(body, { status: 200, headers: { 'Content-Type': 'application/hal+json' } }); + // json() fails before the stream ends; simulate it so the body stays unread. + response.json = async () => { throw new SyntaxError('Unexpected end of JSON input'); }; + return response; + }; + const { get } = await fixture(t, { fetchRest }); + assert.equal((await get()).status, 418); + assert.equal(cancelled, true); +}); diff --git a/server.ts b/server.ts index 2a4f9b587d7..bf3f7ca6876 100644 --- a/server.ts +++ b/server.ts @@ -212,6 +212,8 @@ export function app() { if (environment.ssr.enabled) { router.get(/^\/handle\/[^/]+\/[^/]+\/?$/, createHandleRedirectHandler( REST_BASE_URL, environment.ui.nameSpace, environment.ssr.handleRedirect, + // Same value addCacheControl gives the Angular redirect today (every handle contains a dot). + { cacheControl: environment.cache.control || 'max-age=604800' }, )); } diff --git a/src/backend/handle-redirect.ts b/src/backend/handle-redirect.ts index 92a9f6f08ae..1da47d275a9 100644 --- a/src/backend/handle-redirect.ts +++ b/src/backend/handle-redirect.ts @@ -8,6 +8,25 @@ import { import { TOKENITEM } from '../app/core/auth/models/auth-token-info.model'; import { HandleRedirectConfig } from '../config/ssr-config.interface'; +/** + * Avoid rendering Angular just to send its permanent handle redirect. PID /find only returns a + * REST Location, which cannot distinguish /items from /entities. Discovery's exact handle lookup + * embeds the permission-filtered, current database object (not indexed metadata) in one call. + * Index misses, stale handles and anything uncertain keep the existing Angular behaviour. + */ +/** Default for a missing or invalid timeoutMs, so a bad value cannot turn every lookup into an instant abort. */ +const DEFAULT_TIMEOUT_MS = 1000; +/** At most one warning per interval, so a scraper burst cannot flood the log. */ +const WARN_INTERVAL_MS = 60_000; + +export interface HandleRedirectOptions { + /** Cache-Control of the 301. The Angular redirect gets the static-file value because handles contain a dot. */ + cacheControl?: string; + fetchRest?: typeof fetch; + warn?: (message: string) => void; + now?: () => number; +} + /** * Avoid rendering Angular just to send its permanent handle redirect. PID /find only returns a * REST Location, which cannot distinguish /items from /entities. Discovery's exact handle lookup @@ -18,8 +37,26 @@ export function createHandleRedirectHandler( restBaseUrl: string, nameSpace: string, config: HandleRedirectConfig, - fetchRest: typeof fetch = fetch, + options: HandleRedirectOptions = {}, ): RequestHandler { + const fetchRest = options.fetchRest ?? fetch; + const warn = options.warn ?? ((message: string) => console.warn(message)); + const now = options.now ?? Date.now; + const timeoutMs = Number.isFinite(config?.timeoutMs) && config.timeoutMs > 0 ? config.timeoutMs : DEFAULT_TIMEOUT_MS; + // Failures fall through to Angular silently for the visitor; this keeps them visible to us. + let failures = 0; + let lastWarn = -Infinity; + const failed = (reason: string) => { + failures++; + const at = now(); + if (at - lastWarn >= WARN_INTERVAL_MS) { + warn(`Handle redirect lookup failed (${reason}); ${failures} failure(s) since the last warning, ` + + 'falling back to SSR.'); + failures = 0; + lastWarn = at; + } + }; + const handler = async (req: Request, res: Response, next: NextFunction) => { // Keep unusual identifiers, matrix parameters and deeper/legacy bitstream paths in Angular. const match = /^\/handle\/(\d+(?:\.\d+)*)\/([a-zA-Z0-9._-]+)\/?$/.exec(req.path); @@ -34,28 +71,39 @@ export function createHandleRedirectHandler( } let path: string; + let response: globalThis.Response; try { const handle = `${match[1]}/${match[2]}`; const url = new URL(`${restBaseUrl.replace(/\/$/, '')}/api/discover/search/objects`); url.searchParams.set('query', `handle:"${handle}"`); url.searchParams.set('size', '2'); - const response = await fetchRest(url, { + response = await fetchRest(url, { // Never follow a redirect or copy request headers: this lookup must remain anonymous. redirect: 'manual', headers: { Accept: 'application/hal+json' }, - signal: AbortSignal.timeout(config.timeoutMs), + signal: AbortSignal.timeout(timeoutMs), }); if (!response.ok) { + failed(`HTTP ${response.status}`); await response.body?.cancel(); } else { path = handlePath(await response.json(), handle); } - } catch { + } catch (error) { // Includes the body read in the timeout; SSR still owns errors, login and not-found pages. + const err = error as { name?: string, message?: string }; + failed(err?.name === 'TimeoutError' ? `timeout after ${timeoutMs} ms` : (err?.message ?? err?.name ?? 'unknown error')); + // Release a body left half-read by a failed json() or an abort. + if (response?.body && !response.bodyUsed) { + await response.body.cancel().catch(() => undefined); + } } if (path) { // Match DsoRedirectService: configured UI namespace, no incoming query, relative Location. + if (options.cacheControl) { + res.set('Cache-Control', options.cacheControl); + } res.redirect(301, nameSpace.replace(/\/$/, '') + path); } else { next();