The minimalistic document archiving platform.
feat(storage): sync keys on document updates (#1525)
Corentin Thomasset7c9a96fc350a
diff --git a/.changeset/forty-humans-help.md b/.changeset/forty-humans-help.mdnew file mode 100644index 00000000..d1a4143b--- /dev/null+++ b/.changeset/forty-humans-help.md@@ -0,0 +1,5 @@+---+'@papra/app': patch+---++Added optional storage key synchronization so document renames are reflected in the underlying storage. Enable it with `DOCUMENT_STORAGE_KEY_SYNC_ENABLED=true` when using pattern-based storage keys.diff --git a/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdx b/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdxindex c3f57f9c..cb7e22ce 100644--- a/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdx+++ b/apps/docs/src/content/docs/03-guides/09-storage-key-patterns.mdx@@ -29,10 +29,10 @@ org_123456789012345678901234/invoice-2025.pdf### Storage Key Persistence-The generated storage key is stored in the database alongside each document record. This means that **changing the pattern configuration does not affect existing documents**, only newly uploaded documents will use the updated pattern. Existing documents retain their original storage keys and continue to be served from their original location.+The generated storage key is stored in the database alongside each document record. By default, **changing the pattern configuration only affects newly uploaded documents**. Existing documents retain their original storage keys unless you enable synchronization or explicitly migrate them.<Aside type="tip">-A migration tool to reprocess storage keys for existing documents (allowing you to move files from an old pattern to a new one, or even to a different storage backend) will be available in a future release.+Use the [storage migration guide](/guides/migrate-document-storage/) to reprocess existing documents in bulk or move them to another storage backend.</Aside>## Enabling Storage Key Patterns@@ -50,9 +50,25 @@ DOCUMENT_STORAGE_KEY_PATTERN={{organization.id}}/{{document.name}}```<Aside type="caution">-If you switch from the legacy system to the pattern-based system on an existing instance, only new documents will use the new pattern. Existing documents will continue to use their legacy storage keys (`{{organization.id}}/originals/{{document.id}}`) and remain accessible without any changes needed.+If you switch from the legacy system to the pattern-based system on an existing instance, existing documents keep their legacy storage keys and remain accessible. With synchronization enabled, they adopt the configured pattern on the next update that triggers synchronization.</Aside>+### Synchronizing Storage Keys on Document Updates++To reflect document renames in the underlying storage, enable synchronization alongside pattern-based storage:++```bash+DOCUMENT_STORAGE_USE_LEGACY_STORAGE_KEY_DEFINITION_SYSTEM=false+DOCUMENT_STORAGE_KEY_PATTERN={{organization.id}}/{{document.name}}+DOCUMENT_STORAGE_KEY_SYNC_ENABLED=true+```++The configuration option is `documentsStorage.pattern.isStorageKeySyncEnabled` and defaults to `false`. When enabled, qualifying document updates trigger pattern re-evaluation using the document's current metadata. Currently, synchronization is triggered by document name changes. Papra copies the stored file to the new key, updates its database reference, and removes the old file. Encrypted files retain their encryption metadata.++Enabling synchronization does not immediately move existing files: it applies to subsequent updates that trigger synchronization.++When synchronization is triggered, all expressions are re-evaluated, including `{{currentDate.*}}` and `{{random}}`. These expressions do not trigger synchronization on their own. Synchronization runs asynchronously on a best-effort basis; failures are logged without automatic retries. Failed copies or database updates retain the original file, while failed old-file cleanup leaves the new key usable.+### Docker Compose Example```yaml title="docker-compose.yml" ins={9-10}@@ -92,7 +108,7 @@ Multiple transformers can be chained, and each transformer receives the output o| Expression | Description | Example Output ||-----------|-------------|----------------|| `document.id` | The unique document identifier | `doc_123456789012345678901234` |-| `document.name` | The original file name (sanitized for safe filesystem use) | `invoice-2025.pdf` |+| `document.name` | The document name (sanitized for safe filesystem use) | `invoice-2025.pdf` || `organization.id` | The organization identifier | `org_123456789012345678901234` || `currentDate` | The current date and time in ISO 8601 format | `2025-06-15T14:30:00.000Z` || `currentDate.yyyy` | Current year (4 digits) | `2025` |@@ -224,6 +240,7 @@ DOCUMENT_STORAGE_PATTERN_ENABLE_RANDOM_SUFFIX_FALLBACK=false|----------|-------------|---------|| `DOCUMENT_STORAGE_USE_LEGACY_STORAGE_KEY_DEFINITION_SYSTEM` | Use the legacy storage key format (`{orgId}/originals/{docId}.{ext}`). Set to `false` to enable patterns. | `true` || `DOCUMENT_STORAGE_KEY_PATTERN` | The pattern template for generating storage keys | `{{organization.id}}/{{document.name}}` |+| `DOCUMENT_STORAGE_KEY_SYNC_ENABLED` | Synchronize storage keys on document updates when pattern-based storage is enabled | `false` || `DOCUMENT_STORAGE_PATTERN_MAX_INCREMENTAL_SUFFIX_ATTEMPTS` | Maximum number of incremental suffix attempts for conflict resolution | `9` || `DOCUMENT_STORAGE_PATTERN_ENABLE_RANDOM_SUFFIX_FALLBACK` | Enable random suffix fallback when all incremental suffixes are exhausted | `true` |diff --git a/apps/papra-server/src/modules/app/events/events.handlers.ts b/apps/papra-server/src/modules/app/events/events.handlers.tsindex 92d12983..02d22297 100644--- a/apps/papra-server/src/modules/app/events/events.handlers.ts+++ b/apps/papra-server/src/modules/app/events/events.handlers.ts@@ -10,6 +10,7 @@ import { registerInsertActivityLogOnDocumentRestoredHandler } from '../../documeimport { registerInsertActivityLogOnDocumentTagsChangedHandler } from '../../documents/events/activity-log.document-tags-changed';import { registerInsertActivityLogOnDocumentUpdatedHandler } from '../../documents/events/activity-log.document-updated';import { registerInsertActivityLogOnDocumentsTrashedHandler } from '../../documents/events/activity-log.documents-trashed';+import { registerSyncDocumentStorageKeyHandler } from '../../documents/events/storage-key.document-updated';import { registerTrackDocumentCreatedHandler } from '../../documents/events/tracking.document-created';import { registerTriggerWebhooksOnDocumentCreatedHandler } from '../../documents/events/webhooks.document-created';import { registerTriggerWebhooksOnDocumentTagsChangedHandler } from '../../documents/events/webhooks.document-tags-changed';@@ -17,6 +18,7 @@ import { registerTriggerWebhooksOnDocumentUpdatedHandler } from '../../documentsimport { registerTriggerWebhooksOnDocumentsTrashedHandler } from '../../documents/events/webhooks.documents-trashed';import { registerFirstUserAdminEventHandler } from '../../roles/event-handlers/first-user-admin.user-created';import { registerTrackingUserCreatedEventHandler } from '../../users/event-handlers/tracking.user-created';+import type { StorageService } from '../../storage/storage.services';export function registerEventHandlers(deps: {trackingServices: TrackingServices;@@ -25,6 +27,7 @@ export function registerEventHandlers(deps: {documentSearchServices: DocumentSearchServices;config: Config;webhookTriggerServices: WebhookTriggerServices;+ documentsStorageService: StorageService;}) {registerFirstUserAdminEventHandler(deps);registerTrackingUserCreatedEventHandler(deps);@@ -39,4 +42,5 @@ export function registerEventHandlers(deps: {registerTriggerWebhooksOnDocumentTagsChangedHandler(deps);registerInsertActivityLogOnDocumentTagsChangedHandler(deps);registerSyncDocumentSearchEventHandlers(deps);+ registerSyncDocumentStorageKeyHandler(deps);}diff --git a/apps/papra-server/src/modules/app/server.test-utils.ts b/apps/papra-server/src/modules/app/server.test-utils.tsindex a02ebc40..8b0ebd28 100644--- a/apps/papra-server/src/modules/app/server.test-utils.ts+++ b/apps/papra-server/src/modules/app/server.test-utils.ts@@ -78,6 +78,7 @@ export function createTestServerDependencies(documentSearchServices,config,webhookTriggerServices,+ documentsStorageService,});return {diff --git a/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts b/apps/papra-server/src/modules/documents/document-storage.usecases.test.tsindex e4e081ce..d05a98f4 100644--- a/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts+++ b/apps/papra-server/src/modules/documents/document-storage.usecases.test.ts@@ -1,9 +1,20 @@import type { StoragePatternConfig } from './storage-patterns/storage-pattern.types';+import { Buffer } from 'node:buffer';import { createNoopLogger } from '@crowlog/logger';import { describe, expect, test, vi } from 'vitest';-import { createDocumentStorageKey } from './document-storage.usecases';+import { createInMemoryDatabase } from '../app/database/database.test-utils';+import { createTestClock } from '../shared/clock/clock.test-utils';+import {+ collectReadableStreamToString,+ createReadableStream,+} from '../shared/streams/readable-stream';+import { inMemoryStorageDriverFactory } from '../storage/drivers/memory/memory.storage-driver';+import { wrapWithEncryptionLayer } from '../storage/encryption/storage-encryption.services';+import { buildSyncDocumentStorageKey, createDocumentStorageKey } from './document-storage.usecases';+import { createDocumentsRepository } from './documents.repository';const baseStoragePatternConfig = {+ isStorageKeySyncEnabled: true,useLegacyStorageKeyDefinitionSystem: false,storageKeyPattern: '{{organization.id}}/{{document.name}}',enableRandomSuffixFallback: true,@@ -17,6 +28,389 @@ const documentContext = {now: new Date('2026-01-01T00:00:00.000Z'),};+async function setupSync({ sourceStorageKey = 'old.pdf', isEncryptionEnabled = false } = {}) {+ const { db } = await createInMemoryDatabase({+ organizations: [{ id: 'org_1', name: 'Organization' }],+ });+ const documentsRepository = createDocumentsRepository({ db });+ const driver = inMemoryStorageDriverFactory();+ const documentsStorageService = wrapWithEncryptionLayer({+ storageDriver: driver,+ encryptionOptions: {+ isEncryptionEnabled,+ keyEncryptionKeys: [{ version: '1', key: Buffer.alloc(32, 1) }],+ },+ });+ const encryptionContext = await documentsStorageService.saveFile({+ storageKey: sourceStorageKey,+ fileName: 'old.pdf',+ mimeType: 'application/pdf',+ fileStream: createReadableStream({ content: 'document bytes' }),+ });+ const { document } = await documentsRepository.saveOrganizationDocument({+ id: 'doc_1',+ organizationId: 'org_1',+ name: 'invoice.pdf',+ originalName: 'old.pdf',+ originalStorageKey: sourceStorageKey,+ originalSha256Hash: 'hash',+ mimeType: 'application/pdf',+ ...encryptionContext,+ });+ const args = { documentId: document.id, organizationId: document.organizationId };+ const dependencies = {+ documentsRepository,+ documentsStorageService,+ storagePatternConfig: baseStoragePatternConfig,+ logger: createNoopLogger(),+ };+ return {+ args,+ document,+ dependencies,+ driver,+ getDocument: async () => (await documentsRepository.getDocumentById(args)).document,+ keys: () => [...driver._getStorage().keys()].sort(),+ sync: buildSyncDocumentStorageKey(dependencies),+ };+}++describe('syncDocumentStorageKey', () => {+ test('re-evaluates current dates and random expressions on subsequent updates', async () => {+ const { args, dependencies, keys, getDocument } = await setupSync();+ const { clock } = createTestClock({ now: '2026-01-01T00:00:00Z' });+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ clock,+ storagePatternConfig: {+ ...baseStoragePatternConfig,+ storageKeyPattern: '{{currentDate.yyyy}}/{{random}}/{{document.name}}',+ },+ });+ await sync(args);+ expect((await getDocument())?.originalStorageKey).toMatch(+ /^2026\/[A-Za-z0-9]{8}\/invoice\.pdf$/,+ );+ clock.setNow('2027-01-01T00:00:00Z');+ await sync(args);+ expect((await getDocument())?.originalStorageKey).toMatch(+ /^2027\/[A-Za-z0-9]{8}\/invoice\.pdf$/,+ );+ expect(keys()).toEqual([(await getDocument())?.originalStorageKey]);+ });++ test('a stale storage-key update cannot replace a newer database key or cross organizations', async () => {+ const { args, dependencies, document, getDocument } = await setupSync();+ const update = {+ ...args,+ sourceStorageKey: document.originalStorageKey,+ storageKey: 'newer.pdf',+ name: document.name,+ updatedAt: document.updatedAt,+ };+ expect(+ await dependencies.documentsRepository.updateDocumentStorageKey({+ ...update,+ organizationId: 'other_org',+ }),+ ).toEqual({ updated: false });+ expect(await dependencies.documentsRepository.updateDocumentStorageKey(update)).toEqual({+ updated: true,+ });+ expect(+ await dependencies.documentsRepository.updateDocumentStorageKey({+ ...update,+ storageKey: 'stale.pdf',+ }),+ ).toEqual({ updated: false });+ expect((await getDocument())?.originalStorageKey).toEqual('newer.pdf');+ });++ test('moves stored bytes and only changes the storage key, preserving encryption metadata', async () => {+ const { sync, args, document, getDocument, keys, driver, dependencies } = await setupSync({+ isEncryptionEnabled: true,+ });+ const ciphertext = driver._getStorage().get('old.pdf')!.content;++ await sync(args);++ expect(await getDocument()).toEqual({ ...document, originalStorageKey: 'org_1/invoice.pdf' });+ expect(keys()).toEqual(['org_1/invoice.pdf']);+ expect(driver._getStorage().get('org_1/invoice.pdf')!.content).toEqual(ciphertext);+ const { fileStream } = await dependencies.documentsStorageService.getFileStream({+ storageKey: 'org_1/invoice.pdf',+ ...document,+ });+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual('document bytes');+ });++ test('is opt-in and does not synchronize legacy keys', async () => {+ const { args, dependencies, keys } = await setupSync();+ await buildSyncDocumentStorageKey({+ ...dependencies,+ storagePatternConfig: { ...baseStoragePatternConfig, isStorageKeySyncEnabled: false },+ })(args);+ await buildSyncDocumentStorageKey({+ ...dependencies,+ storagePatternConfig: {+ ...baseStoragePatternConfig,+ useLegacyStorageKeyDefinitionSystem: true,+ },+ })(args);+ expect(keys()).toEqual(['old.pdf']);+ });++ test('does not write storage when the key already matches', async () => {+ const { args, dependencies, document, getDocument } = await setupSync({+ sourceStorageKey: 'org_1/invoice.pdf',+ });+ const fail = async () => {+ throw new Error('unexpected storage access');+ };+ await buildSyncDocumentStorageKey({+ ...dependencies,+ documentsStorageService: { fileExists: fail, copyFile: fail, deleteFile: fail },+ })(args);+ expect(await getDocument()).toEqual(document);+ });++ test('moves an incremental-suffixed key to the unsuffixed key when available', async () => {+ const { sync, args, keys, getDocument } = await setupSync({+ sourceStorageKey: 'org_1/invoice_2.pdf',+ });+ await sync(args);+ expect(keys()).toEqual(['org_1/invoice.pdf']);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice.pdf');+ });++ test('moves a random-suffixed key to the unsuffixed key when available', async () => {+ const { sync, args, keys, getDocument } = await setupSync({+ sourceStorageKey: 'org_1/invoice_aB12cd34.pdf',+ });+ await sync(args);+ expect(keys()).toEqual(['org_1/invoice.pdf']);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice.pdf');+ });++ test('accepts repeated copies between suffixes while the unsuffixed key remains occupied', async () => {+ const { sync, args, dependencies, keys, getDocument } = await setupSync({+ sourceStorageKey: 'org_1/invoice_1.pdf',+ });+ await dependencies.documentsStorageService.saveFile({+ storageKey: 'org_1/invoice.pdf',+ fileName: 'invoice.pdf',+ mimeType: 'application/pdf',+ fileStream: createReadableStream({ content: 'other document' }),+ });++ // Only exact matches skip synchronization. Extra copies are an accepted cost+ // of avoiding heuristics that infer collision suffixes from filenames.+ await sync(args);+ expect(keys()).toEqual(['org_1/invoice.pdf', 'org_1/invoice_2.pdf']);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice_2.pdf');++ await sync(args);+ expect(keys()).toEqual(['org_1/invoice.pdf', 'org_1/invoice_1.pdf']);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice_1.pdf');++ const { fileStream } = await dependencies.documentsStorageService.getFileStream({+ storageKey: 'org_1/invoice_1.pdf',+ });+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual('document bytes');+ const { fileStream: otherFileStream } =+ await dependencies.documentsStorageService.getFileStream({+ storageKey: 'org_1/invoice.pdf',+ });+ expect(await collectReadableStreamToString({ stream: otherFileStream })).toEqual(+ 'other document',+ );+ });++ test('resolves collisions without replacing another stored file', async () => {+ const { sync, args, dependencies, keys, getDocument } = await setupSync();+ await dependencies.documentsStorageService.saveFile({+ storageKey: 'org_1/invoice.pdf',+ fileName: 'invoice.pdf',+ mimeType: 'application/pdf',+ fileStream: createReadableStream({ content: 'other document' }),+ });+ await sync(args);+ expect(keys()).toEqual(['org_1/invoice.pdf', 'org_1/invoice_1.pdf']);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice_1.pdf');+ const { fileStream } = await dependencies.documentsStorageService.getFileStream({+ storageKey: 'org_1/invoice.pdf',+ });+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual('other document');+ });++ test('a failed copy retains the source and database key', async () => {+ const { args, dependencies, getDocument, document, keys } = await setupSync();+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ documentsStorageService: {+ ...dependencies.documentsStorageService,+ copyFile: async () => {+ throw new Error('copy failed');+ },+ },+ });+ await expect(sync(args)).rejects.toThrow('copy failed');+ expect(await getDocument()).toEqual(document);+ expect(keys()).toEqual(['old.pdf']);+ });++ test('a failed database update retains both files and does not block later synchronization', async () => {+ const { args, dependencies, getDocument, document, keys } = await setupSync();+ let fail = true;+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ documentsRepository: {+ ...dependencies.documentsRepository,+ updateDocumentStorageKey: async (input) => {+ if (fail) {+ throw new Error('database failed');+ }+ return dependencies.documentsRepository.updateDocumentStorageKey(input);+ },+ },+ });+ await expect(sync(args)).rejects.toThrow('database failed');+ expect(await getDocument()).toEqual(document);+ expect(keys()).toEqual(['old.pdf', 'org_1/invoice.pdf']);+ fail = false;+ await sync(args);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice_1.pdf');+ expect(keys()).toEqual(['org_1/invoice.pdf', 'org_1/invoice_1.pdf']);+ });++ test('a database error after committing retains the referenced destination and source', async () => {+ const { args, dependencies, getDocument, keys } = await setupSync();+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ documentsRepository: {+ ...dependencies.documentsRepository,+ updateDocumentStorageKey: async (input) => {+ await dependencies.documentsRepository.updateDocumentStorageKey(input);+ throw new Error('response lost after commit');+ },+ },+ });++ await expect(sync(args)).rejects.toThrow('response lost after commit');++ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice.pdf');+ expect(keys()).toEqual(['old.pdf', 'org_1/invoice.pdf']);+ const { fileStream } = await dependencies.documentsStorageService.getFileStream({+ storageKey: 'org_1/invoice.pdf',+ });+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual('document bytes');+ });++ test('a lost database comparison retains the destination referenced by a winning update', async () => {+ const { args, dependencies, getDocument, keys } = await setupSync();+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ documentsRepository: {+ ...dependencies.documentsRepository,+ updateDocumentStorageKey: async (input) => {+ // Another handler publishes the shared destination and removes the source first.+ await dependencies.documentsRepository.updateDocumentStorageKey(input);+ await dependencies.documentsStorageService.deleteFile({+ storageKey: input.sourceStorageKey,+ });+ return dependencies.documentsRepository.updateDocumentStorageKey(input);+ },+ },+ });++ await sync(args);++ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice.pdf');+ expect(keys()).toEqual(['org_1/invoice.pdf']);+ const { fileStream } = await dependencies.documentsStorageService.getFileStream({+ storageKey: 'org_1/invoice.pdf',+ });+ expect(await collectReadableStreamToString({ stream: fileStream })).toEqual('document bytes');+ });++ test('a failed source cleanup keeps the working new key and logs the failure', async () => {+ const { args, dependencies, getDocument, keys } = await setupSync();+ const errors: unknown[] = [];+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ logger: {+ ...dependencies.logger,+ error: (...args) => {+ errors.push(args);+ },+ },+ documentsStorageService: {+ ...dependencies.documentsStorageService,+ deleteFile: async () => {+ throw new Error('delete failed');+ },+ },+ });+ await sync(args);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/invoice.pdf');+ expect(keys()).toEqual(['old.pdf', 'org_1/invoice.pdf']);+ expect(errors).toHaveLength(1);+ });++ test('overlapping updates publish the latest name and retain the stale copy', async () => {+ const { args, dependencies, getDocument, keys } = await setupSync();+ const copying = Promise.withResolvers<void>();+ const resume = Promise.withResolvers<void>();+ let copies = 0;+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ documentsStorageService: {+ ...dependencies.documentsStorageService,+ copyFile: async (input) => {+ copies++;+ await dependencies.documentsStorageService.copyFile(input);+ if (copies === 1) {+ copying.resolve();+ await resume.promise;+ }+ },+ },+ });+ const first = sync(args);+ await copying.promise;+ await dependencies.documentsRepository.updateDocument({ ...args, name: 'latest.pdf' });+ const second = sync(args);+ resume.resolve();+ await Promise.all([first, second]);+ expect((await getDocument())?.originalStorageKey).toEqual('org_1/latest.pdf');+ expect(keys()).toEqual(['org_1/invoice.pdf', 'org_1/latest.pdf']);+ });++ test('deletion during the copy rejects the database update and retains both files', async () => {+ const { args, dependencies, keys, getDocument } = await setupSync();+ const sync = buildSyncDocumentStorageKey({+ ...dependencies,+ documentsStorageService: {+ ...dependencies.documentsStorageService,+ copyFile: async (input) => {+ await dependencies.documentsStorageService.copyFile(input);+ await dependencies.documentsRepository.hardDeleteDocument(args);+ },+ },+ });+ await sync(args);+ expect(await getDocument()).toEqual(undefined);+ expect(keys()).toEqual(['old.pdf', 'org_1/invoice.pdf']);+ });++ test('a document deleted before handling is a no-op', async () => {+ const { sync, args, dependencies, keys } = await setupSync();+ await dependencies.documentsRepository.hardDeleteDocument(args);+ await sync(args);+ expect(keys()).toEqual(['old.pdf']);+ });+});+describe('document-storage usecases', () => {describe('createDocumentStorageKey', () => {test('uses the legacy document key without checking for collisions', async () => {diff --git a/apps/papra-server/src/modules/documents/document-storage.usecases.ts b/apps/papra-server/src/modules/documents/document-storage.usecases.tsindex f21bf0a1..1b2cf0aa 100644--- a/apps/papra-server/src/modules/documents/document-storage.usecases.ts+++ b/apps/papra-server/src/modules/documents/document-storage.usecases.ts@@ -1,9 +1,107 @@+import type { Clock } from '../shared/clock/clock.types';import type { Logger } from '../shared/logger/logger';import type { StorageService } from '../storage/drivers/drivers.models';+import type { DocumentsRepository } from './documents.repository';import type { StoragePatternConfig } from './storage-patterns/storage-pattern.types';+import { systemClock } from '../shared/clock/clock';+import { createLogger } from '../shared/logger/logger';+import { ensureStorageKeyIsAvailable } from '../storage/storage.usecases';import { buildOriginalDocumentKey } from './documents.models';import { buildStorageKey } from './storage-patterns/storage-pattern.usecases';-import { ensureStorageKeyIsAvailable } from '../storage/storage.usecases';+import { safely } from '@corentinth/chisels';++export type SyncDocumentStorageKey = (args: {+ documentId: string;+ organizationId: string;+}) => Promise<void>;++export function buildSyncDocumentStorageKey({+ storagePatternConfig,+ documentsRepository,+ documentsStorageService,+ logger = createLogger({ namespace: 'sync-document-storage-key' }),+ clock = systemClock,+}: {+ storagePatternConfig: StoragePatternConfig;+ documentsRepository: Pick<DocumentsRepository, 'getDocumentById' | 'updateDocumentStorageKey'>;+ documentsStorageService: Pick<StorageService, 'fileExists' | 'copyFile' | 'deleteFile'>;+ logger?: Logger;+ clock?: Clock;+}): SyncDocumentStorageKey {+ async function cleanup(storageKey: string) {+ try {+ await documentsStorageService.deleteFile({ storageKey });+ } catch (error) {+ logger.error({ error, storageKey }, 'Failed to clean up document storage key');+ }+ }++ return async ({ documentId, organizationId }) => {+ if (+ !storagePatternConfig.isStorageKeySyncEnabled ||+ storagePatternConfig.useLegacyStorageKeyDefinitionSystem+ ) {+ return;+ }++ const { document } = await documentsRepository.getDocumentById({ documentId, organizationId });+ if (!document || document.isDeleted) {+ return;+ }++ const sourceStorageKey = document.originalStorageKey;+ const { storageKey: initialStorageKey } = buildStorageKey({+ storageKeyPattern: storagePatternConfig.storageKeyPattern,+ documentId,+ organizationId,+ documentName: document.name,+ now: new Date(clock.now().epochMilliseconds),+ });++ if (sourceStorageKey === initialStorageKey) {+ return;+ }++ const { storageKey } = await ensureStorageKeyIsAvailable({+ initialStorageKey,+ maxIncrementalSuffixAttempts: storagePatternConfig.maxIncrementalSuffixAttempts,+ enableRandomSuffixFallback: storagePatternConfig.enableRandomSuffixFallback,+ storageService: documentsStorageService,+ logger,+ });++ await documentsStorageService.copyFile({ sourceStorageKey, destinationStorageKey: storageKey });++ const [updateResult, error] = await safely(+ documentsRepository.updateDocumentStorageKey({+ documentId,+ organizationId,+ sourceStorageKey,+ storageKey,+ name: document.name,+ updatedAt: document.updatedAt,+ }),+ );++ if (error) {+ logger.error(+ { error, documentId, organizationId, sourceStorageKey, storageKey },+ 'Failed to update document storage key',+ );+ // No cleanup, the error can be caused by a race condition where a sync task already updated the document storage key.+ throw error;+ }++ logger.info(+ { documentId, organizationId, sourceStorageKey, storageKey, updated: updateResult.updated },+ 'Document storage key updated',+ );++ if (updateResult.updated) {+ await cleanup(sourceStorageKey);+ }+ };+}export async function createDocumentStorageKey({storagePatternConfig,diff --git a/apps/papra-server/src/modules/documents/documents.repository.ts b/apps/papra-server/src/modules/documents/documents.repository.tsindex ada3aefd..6996d5dc 100644--- a/apps/papra-server/src/modules/documents/documents.repository.ts+++ b/apps/papra-server/src/modules/documents/documents.repository.ts@@ -35,6 +35,7 @@ export function createDocumentsRepository({ db }: { db: Database }) {getAllOrganizationDocumentsIterator,getAllOrganizationUndeletedDocumentsIterator,updateDocument,+ updateDocumentStorageKey,getGlobalDocumentsStats,areAllDocumentsInOrganization,},@@ -481,6 +482,42 @@ async function updateDocument({return { document };}+async function updateDocumentStorageKey({+ documentId,+ organizationId,+ sourceStorageKey,+ storageKey,+ name,+ updatedAt,+ db,+}: {+ documentId: string;+ organizationId: string;+ sourceStorageKey: string;+ storageKey: string;+ name: string;+ updatedAt: Date;+ db: Database;+}) {+ const rows = await db+ .update(documentsTable)+ // A storage-only change must not alter the document's modification date.+ .set({ originalStorageKey: storageKey, updatedAt })+ .where(+ and(+ eq(documentsTable.id, documentId),+ eq(documentsTable.organizationId, organizationId),+ eq(documentsTable.originalStorageKey, sourceStorageKey),+ eq(documentsTable.name, name),+ eq(documentsTable.updatedAt, updatedAt),+ eq(documentsTable.isDeleted, false),+ ),+ )+ .returning({ id: documentsTable.id });++ return { updated: rows.length > 0 };+}+async function getGlobalDocumentsStats({ db }: { db: Database }) {const [record] = await db.select({diff --git a/apps/papra-server/src/modules/documents/events/storage-key.document-updated.ts b/apps/papra-server/src/modules/documents/events/storage-key.document-updated.tsnew file mode 100644index 00000000..9070ae70--- /dev/null+++ b/apps/papra-server/src/modules/documents/events/storage-key.document-updated.ts@@ -0,0 +1,39 @@+import type { Database } from '../../app/database/database.types';+import type { EventServices } from '../../app/events/events.services';+import type { Config } from '../../config/config.types';+import type { StorageService } from '../../storage/storage.services';+import { buildSyncDocumentStorageKey } from '../document-storage.usecases';+import { createDocumentsRepository } from '../documents.repository';++export function registerSyncDocumentStorageKeyHandler({+ eventServices,+ documentsStorageService,+ config,+ db,+}: {+ eventServices: EventServices;+ documentsStorageService: StorageService;+ config: Config;+ db: Database;+}) {+ const syncDocumentStorageKey = buildSyncDocumentStorageKey({+ storagePatternConfig: config.documentsStorage.pattern,+ documentsRepository: createDocumentsRepository({ db }),+ documentsStorageService,+ });++ eventServices.onEvent({+ eventName: 'document.updated',+ handlerName: 'sync-document-storage-key',+ handler: async ({ document, changes }) => {+ if (changes.name === undefined) {+ return;+ }++ await syncDocumentStorageKey({+ documentId: document.id,+ organizationId: document.organizationId,+ });+ },+ });+}diff --git a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.config.ts b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.config.tsindex e06085f8..c9ee229d 100644--- a/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.config.ts+++ b/apps/papra-server/src/modules/documents/storage-patterns/storage-pattern.config.ts@@ -4,6 +4,12 @@ import { coercedPositiveIntegerSchema } from '../../shared/schemas/number.schemaimport { storagePatternSchema } from './storage-pattern.schemas';export const storagePatternConfig = {+ isStorageKeySyncEnabled: {+ doc: 'Synchronize document storage keys with the configured pattern on subsequent document updates. Requires pattern-based storage. Date and random expressions are re-evaluated on every update. Existing documents are not migrated automatically.',+ schema: booleanishSchema,+ default: false,+ env: 'DOCUMENT_STORAGE_KEY_SYNC_ENABLED',+ },useLegacyStorageKeyDefinitionSystem: {doc: 'Whether to use the legacy storage key definition system, which generates storage keys in the format: {{organization.id}}/originals/{{document.id}}. When set to true, no storage key pattern will be used, nor will the incremental suffix or random suffix fallback mechanisms be enabled, as the storage key will be generated using the legacy system.',schema: booleanishSchema,diff --git a/apps/papra-server/src/start.ts b/apps/papra-server/src/start.tsindex 8a71a9f5..7ac40177 100644--- a/apps/papra-server/src/start.ts+++ b/apps/papra-server/src/start.ts@@ -100,6 +100,7 @@ async function buildServices({ config }: { config: Config }): Promise<GlobalDepedocumentSearchServices,config,webhookTriggerServices,+ documentsStorageService,});return {