Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(chat-media): let the first archive writer own the media pointer

Yudhi Armyndharis9baa674095a9
diff --git a/src/modules/chat-media/chat-media-archive.service.spec.ts b/src/modules/chat-media/chat-media-archive.service.spec.ts
index 8b8d640cb..373b5d9f4 100644
--- a/src/modules/chat-media/chat-media-archive.service.spec.ts
+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts
@@ -148,6 +148,21 @@ describe('ChatMediaArchiveService', () => {
expect(files).toEqual([first]);
});
+ it('keeps one file when two writers archive the same row concurrently', async () => {
+ // Both callers hold a snapshot read before either pointer landed, so the in-memory guard
+ // passes twice; the pointer write itself has to pick one winner.
+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });
+
+ const keys = await Promise.all([enabled().archive(row), enabled().archive(row)]);
+ const winner = keys.filter(k => k !== null);
+
+ expect(winner).toHaveLength(1);
+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBe(winner[0]);
+ const files = [];
+ for await (const f of storageService.iterateFiles('')) files.push(f);
+ expect(files).toEqual(winner);
+ });
+
it('skips media above the archive cap without touching the row', async () => {
const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });
diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.ts
index 26894ae42..8550d9220 100644
--- a/src/modules/chat-media/chat-media-archive.service.ts
+++ b/src/modules/chat-media/chat-media-archive.service.ts
@@ -165,9 +165,11 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {
try {
// Conditional on the row not being revoked: a revoke that landed while the file was written
- // cleared the row, and pointing it at the file would bring the deleted media back.
+ // cleared the row, and pointing it at the file would bring the deleted media back. And on no
+ // pointer yet: the other writer may have passed the snapshot guard above while this file was
+ // being written, and the first pointer wins so the losing file is deleted, not stranded.
const result = await this.repository.update(
- { id: row.id, type: Not('revoked') },
+ { id: row.id, type: Not('revoked'), mediaPath: IsNull() },
{ mediaPath: key, mediaMimetype: media.mimetype },
);
if (result.affected === 0) {