The minimalistic document archiving platform.
feat(documents): add document reprocessing endpoint (#1513)
Corentin Thomasset1f1a9aded5db
diff --git a/.changeset/warm-carrots-search.md b/.changeset/warm-carrots-search.mdnew file mode 100644index 00000000..efae6768--- /dev/null+++ b/.changeset/warm-carrots-search.md@@ -0,0 +1,5 @@+---+'@papra/app': minor+---++Added an API endpoint to reprocess existing documents `POST /api/organizations/:organizationId/documents/:documentId/reprocess`. This endpoint allows re-running content extraction + auto tagging and tagging rules on existing documents.diff --git a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdxindex 2d7568a7..be6047e5 100644--- a/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx+++ b/apps/docs/src/content/docs/04-resources/03-api-endpoints.mdx@@ -229,6 +229,22 @@ Change the name or content (for search purposes) of a document.- Response (JSON)- `document`: The updated document.+### Reprocess a document++**POST** `/api/organizations/:organizationId/documents/:documentId/reprocess`++Enqueue a background task to reprocess an existing document using the current instance configuration, including its OCR languages. Processing happens asynchronously; existing content and tags are not cleared while the task is pending.++- Required API key permissions: `documents:update`+- The authenticated user must belong to the organization.+- Body: none+- Response: empty (202 status code). This confirms the task was queued, not that processing has completed.+- Rate limit: 100 requests per hour per organization by default, configurable with `DOCUMENT_REPROCESSING_RATE_LIMIT`.+- Errors+ - `403` (`document.reprocessing_disabled`): Reprocessing is disabled via `DOCUMENT_REPROCESSING_ENABLED` (enabled by default).+ - `404` (`document.not_found`): The document does not exist in the organization or is in the trash.+ - `429` (`server.too_many_requests`): The organization's reprocessing rate limit has been exceeded. The `Retry-After` header indicates how many seconds to wait before retrying.+### Get document activity**GET** `/api/organizations/:organizationId/documents/:documentId/activity`diff --git a/apps/papra-server/src/modules/documents/documents.config.ts b/apps/papra-server/src/modules/documents/documents.config.tsindex f3048214..7e937662 100644--- a/apps/papra-server/src/modules/documents/documents.config.ts+++ b/apps/papra-server/src/modules/documents/documents.config.ts@@ -1,5 +1,6 @@import type { ConfigDefinition } from 'figue';import * as v from 'valibot';+import { rateLimitConfigSchema } from '../app/rate-limit/rate-limit.config.schemas';import { booleanishSchema } from '../config/config.schemas';import { coercedNumberSchema } from '../shared/schemas/number.schemas';import { ocrLanguagesSchema, stringCoercedOcrLanguagesSchema } from './documents.schemas';@@ -17,6 +18,18 @@ export const documentsConfig = {default: ['eng'],env: 'DOCUMENTS_OCR_LANGUAGES',},+ isReprocessingEnabled: {+ doc: 'Whether to allow reprocessing existing documents using the current instance configuration',+ schema: booleanishSchema,+ default: true,+ env: 'DOCUMENT_REPROCESSING_ENABLED',+ },+ reprocessingRateLimit: {+ doc: 'The rate limit for document reprocessing requests per organization, e.g. "10/h" or "2/5m"',+ schema: rateLimitConfigSchema,+ default: '100/h',+ env: 'DOCUMENT_REPROCESSING_RATE_LIMIT',+ },isContentExtractionEnabled: {doc: 'Whether to enable content extraction (OCR and text extraction) for uploaded documents',schema: booleanishSchema,diff --git a/apps/papra-server/src/modules/documents/documents.errors.ts b/apps/papra-server/src/modules/documents/documents.errors.tsindex 034c74ce..74178130 100644--- a/apps/papra-server/src/modules/documents/documents.errors.ts+++ b/apps/papra-server/src/modules/documents/documents.errors.ts@@ -6,6 +6,12 @@ export const createDocumentNotFoundError = createErrorFactory({statusCode: 404,});+export const createDocumentReprocessingDisabledError = createErrorFactory({+ message: 'Document reprocessing is disabled.',+ code: 'document.reprocessing_disabled',+ statusCode: 403,+});+export const createDocumentIsNotDeletedError = createErrorFactory({message: 'Document is not deleted, cannot restore.',code: 'document.not_deleted',diff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.tsindex 7b03713a..c41cd8ff 100644--- a/apps/papra-server/src/modules/documents/documents.routes.ts+++ b/apps/papra-server/src/modules/documents/documents.routes.ts@@ -3,21 +3,31 @@ import { Readable } from 'node:stream';import * as v from 'valibot';import { requireAuthentication } from '../app/auth/auth.middleware';import { getUser } from '../app/auth/auth.models';+import { createTooManyRequestsError } from '../app/rate-limit/rate-limit.errors';+import { scopeKvStoreForRateLimit } from '../app/rate-limit/rate-limit.kv-store';+import { getRateLimit } from '../app/rate-limit/rate-limit.usecases';import { createCustomPropertiesRepository } from '../custom-properties/custom-properties.repository';+import { joinKeyParts } from '../kv-store/kv-store.models';import { organizationIdSchema } from '../organizations/organization.schemas';import { createOrganizationsRepository } from '../organizations/organizations.repository';import { ensureUserIsInOrganization } from '../organizations/organizations.usecases';import { createPlanEntitlementsRepository } from '../plan-entitlements/plan-entitlements.repository';import { createPlansRepository } from '../plans/plans.repository';import { getOrganizationPlan } from '../plans/plans.usecases';+import { systemClock } from '../shared/clock/clock';import { createQueryPaginationSchemaKeys } from '../shared/schemas/pagination.schemas';import { getFileStreamFromMultipartForm } from '../shared/streams/file-upload';+import { IN_MS } from '../shared/units';import { validateJsonBody, validateParams, validateQuery } from '../shared/validation/validation';import { createSubscriptionsRepository } from '../subscriptions/subscriptions.repository';import { createTagsRepository } from '../tags/tags.repository';import { DEFAULT_DOCUMENT_SEARCH_SORT } from './document-search/document-search.constants';import { searchOrganizationDocuments } from './document-search/document-search.usecase';-import { createDocumentIsNotDeletedError } from './documents.errors';+import {+ createDocumentIsNotDeletedError,+ createDocumentNotFoundError,+ createDocumentReprocessingDisabledError,+} from './documents.errors';import {formatDocumentForApi,formatDocumentsForApi,@@ -56,6 +66,73 @@ export function registerDocumentsRoutes(context: RouteDefinitionContext) {setupDeleteDocumentRoute(context);setupGetDocumentFileRoute(context);setupUpdateDocumentRoute(context);+ setupReprocessDocumentRoute(context);+}++function setupReprocessDocumentRoute({+ app,+ db,+ config,+ kvStore,+ taskServices,+}: RouteDefinitionContext) {+ app.post(+ '/api/organizations/:organizationId/documents/:documentId/reprocess',+ requireAuthentication({ apiKeyPermissions: ['documents:update'] }),+ validateParams(+ v.strictObject({+ organizationId: organizationIdSchema,+ documentId: documentIdSchema,+ }),+ ),+ async (context) => {+ const { userId } = getUser({ context });+ const { organizationId, documentId } = context.req.valid('param');++ const organizationsRepository = createOrganizationsRepository({ db });+ await ensureUserIsInOrganization({ userId, organizationId, organizationsRepository });++ if (!config.documents.isReprocessingEnabled) {+ throw createDocumentReprocessingDisabledError();+ }++ const documentsRepository = createDocumentsRepository({ db });+ const { document } = await getDocumentOrThrow({+ documentId,+ organizationId,+ documentsRepository,+ });++ if (document.isDeleted) {+ throw createDocumentNotFoundError();+ }++ const { hasExceededLimit, resetAt } = await getRateLimit({+ ...config.documents.reprocessingRateLimit,+ key: joinKeyParts(['document-reprocessing', organizationId]),+ kvStore: scopeKvStoreForRateLimit({ kvStore }),+ });++ if (hasExceededLimit) {+ const retryAfter = Math.max(+ 1,+ Math.ceil(+ (resetAt.epochMilliseconds - systemClock.now().epochMilliseconds) / IN_MS.SECOND,+ ),+ );+ context.header('Retry-After', String(retryAfter));+ throw createTooManyRequestsError();+ }++ // Reuse the processing pipeline without clearing content or tags while the job is pending.+ await taskServices.scheduleJob({+ taskName: 'extract-document-file-content',+ data: { documentId, organizationId, ocrLanguages: config.documents.ocrLanguages },+ });++ return context.body(null, 202);+ },+ );}function setupCreateDocumentRoute({ app, ...deps }: RouteDefinitionContext) {