The minimalistic document archiving platform.
feat(timeout): implement route-specific timeout configuration for uploads (#707)
Corentin Thomasseta213f0683bae
diff --git a/.changeset/khaki-glasses-draw.md b/.changeset/khaki-glasses-draw.mdnew file mode 100644index 00000000..218f73fd--- /dev/null+++ b/.changeset/khaki-glasses-draw.md@@ -0,0 +1,5 @@+---+"@papra/docker": patch+---++Added a dedicated increased timeout for the document upload routediff --git a/.changeset/ten-friends-shine.md b/.changeset/ten-friends-shine.mdnew file mode 100644index 00000000..a4df9f06--- /dev/null+++ b/.changeset/ten-friends-shine.md@@ -0,0 +1,5 @@+---+"@papra/docker": patch+---++Changed config key `config.server.routeTimeoutMs` to `config.server.defaultRouteTimeoutMs` (env variable remains the same)diff --git a/apps/papra-server/src/modules/app/middlewares/timeout.middleware.test.ts b/apps/papra-server/src/modules/app/middlewares/timeout.middleware.test.tsindex 224e16fe..d4b6e69f 100644--- a/apps/papra-server/src/modules/app/middlewares/timeout.middleware.test.ts+++ b/apps/papra-server/src/modules/app/middlewares/timeout.middleware.test.ts@@ -8,7 +8,7 @@ import { createTimeoutMiddleware } from './timeout.middleware';describe('middlewares', () => {describe('timeoutMiddleware', () => {test('when a request last longer than the config timeout, a 504 error is raised', async () => {- const config = overrideConfig({ server: { routeTimeoutMs: 50 } });+ const config = overrideConfig({ server: { defaultRouteTimeoutMs: 50 } });const app = new Hono<ServerInstanceGenerics>();registerErrorMiddleware({ app });@@ -45,5 +45,107 @@ describe('middlewares', () => {expect(response2.status).to.eql(200);expect(await response2.json()).to.eql({ status: 'ok' });});++ test('route-specific timeout overrides default timeout for matching routes', async () => {+ const config = overrideConfig({+ server: {+ defaultRouteTimeoutMs: 50,+ routeTimeouts: [+ {+ method: 'POST',+ route: '/api/upload/:id',+ timeoutMs: 200,+ },+ ],+ },+ });++ const app = new Hono<ServerInstanceGenerics>();+ registerErrorMiddleware({ app });++ // POST to matching route with longer timeout - should not timeout+ app.post(+ '/api/upload/:id',+ createTimeoutMiddleware({ config }),+ async (context) => {+ await new Promise(resolve => setTimeout(resolve, 100));+ return context.json({ status: 'ok' });+ },+ );++ // GET to same route - should timeout with default+ app.get(+ '/api/upload/:id',+ createTimeoutMiddleware({ config }),+ async (context) => {+ await new Promise(resolve => setTimeout(resolve, 100));+ return context.json({ status: 'ok' });+ },+ );++ // Different route - should timeout with default+ app.post(+ '/api/other',+ createTimeoutMiddleware({ config }),+ async (context) => {+ await new Promise(resolve => setTimeout(resolve, 100));+ return context.json({ status: 'ok' });+ },+ );++ // POST to matching pattern should succeed+ const response1 = await app.request('/api/upload/123', { method: 'POST' });+ expect(response1.status).to.eql(200);++ // GET to same path should timeout (method mismatch)+ const response2 = await app.request('/api/upload/123', { method: 'GET' });+ expect(response2.status).to.eql(504);++ // POST to different path should timeout (path mismatch)+ const response3 = await app.request('/api/other', { method: 'POST' });+ expect(response3.status).to.eql(504);+ });++ test('when registered globally with .use(), route-specific timeouts should work', async () => {+ const config = overrideConfig({+ server: {+ defaultRouteTimeoutMs: 50,+ routeTimeouts: [+ {+ method: 'POST',+ route: '/api/organizations/:orgId/documents',+ timeoutMs: 200,+ },+ ],+ },+ });++ const app = new Hono<ServerInstanceGenerics>();+ registerErrorMiddleware({ app });++ // Register middleware globally (like in server.ts)+ app.use(createTimeoutMiddleware({ config }));++ // Route that should have extended timeout+ app.post('/api/organizations/:orgId/documents', async (context) => {+ await new Promise(resolve => setTimeout(resolve, 100));+ return context.json({ status: 'upload ok' });+ });++ // Route that should use default timeout+ app.get('/api/other', async (context) => {+ await new Promise(resolve => setTimeout(resolve, 100));+ return context.json({ status: 'ok' });+ });++ // POST to upload route should succeed (extended timeout)+ const response1 = await app.request('/api/organizations/org-123/documents', { method: 'POST' });+ expect(response1.status).to.eql(200);+ expect(await response1.json()).to.eql({ status: 'upload ok' });++ // GET to other route should timeout (default timeout)+ const response2 = await app.request('/api/other', { method: 'GET' });+ expect(response2.status).to.eql(504);+ });});});diff --git a/apps/papra-server/src/modules/app/middlewares/timeout.middleware.ts b/apps/papra-server/src/modules/app/middlewares/timeout.middleware.tsindex dc2be75b..f48db109 100644--- a/apps/papra-server/src/modules/app/middlewares/timeout.middleware.ts+++ b/apps/papra-server/src/modules/app/middlewares/timeout.middleware.ts@@ -1,11 +1,42 @@import type { Config } from '../../config/config.types';import type { Context } from '../server.types';import { createMiddleware } from 'hono/factory';+import { routePath } from 'hono/route';import { createError } from '../../shared/errors/errors';+function getTimeoutForRoute({+ defaultRouteTimeoutMs,+ routeTimeouts,+ method,+ path,+}: {+ defaultRouteTimeoutMs: number;+ routeTimeouts: { method: string; route: string; timeoutMs: number }[];+ method: string;+ path: string;+}): number {+ const matchingRoute = routeTimeouts.find((routeConfig) => {+ if (routeConfig.method !== method) {+ return false;+ }++ if (routeConfig.route !== path) {+ return false;+ }++ return true;+ });++ return matchingRoute?.timeoutMs ?? defaultRouteTimeoutMs;+}+export function createTimeoutMiddleware({ config }: { config: Config }) {return createMiddleware(async (context: Context, next) => {- const { server: { routeTimeoutMs } } = config;+ const method = context.req.method;+ const path = routePath(context, -1); // Get the last matched route path, without the -1 we get /* for all routes+ const { defaultRouteTimeoutMs, routeTimeouts } = config.server;++ const timeoutMs = getTimeoutForRoute({ defaultRouteTimeoutMs, routeTimeouts, method, path });let timerId: NodeJS.Timeout | undefined;@@ -16,7 +47,7 @@ export function createTimeoutMiddleware({ config }: { config: Config }) {message: 'The request timed out',statusCode: 504,}),- ), routeTimeoutMs);+ ), timeoutMs);});try {diff --git a/apps/papra-server/src/modules/config/config.ts b/apps/papra-server/src/modules/config/config.tsindex 87699576..6424b0b3 100644--- a/apps/papra-server/src/modules/config/config.ts+++ b/apps/papra-server/src/modules/config/config.ts@@ -84,12 +84,29 @@ export const configDefinition = {default: '0.0.0.0',env: 'SERVER_HOSTNAME',},- routeTimeoutMs: {+ defaultRouteTimeoutMs: {doc: 'The maximum time in milliseconds for a route to complete before timing out',schema: z.coerce.number().int().positive(),default: 20_000,env: 'SERVER_API_ROUTES_TIMEOUT_MS',},+ routeTimeouts: {+ doc: 'Route-specific timeout overrides. Allows setting different timeouts for specific HTTP method and route paths.',+ schema: z.array(+ z.object({+ method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']),+ route: z.string(),+ timeoutMs: z.number().int().positive(),+ }),+ ),+ default: [+ {+ method: 'POST',+ route: '/api/organizations/:organizationId/documents',+ timeoutMs: 5 * 60 * 1000, // 5 minutes for file uploads+ },+ ],+ },corsOrigins: {doc: 'The CORS origin for the api server',schema: z.union([