diff --git a/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts new file mode 100644 index 00000000000..962b0519aa2 --- /dev/null +++ b/app/lib/methods/sendFileMessage/__tests__/uploadLifecycle.test.ts @@ -0,0 +1,224 @@ +import { Alert } from 'react-native'; +import { copyAsync } from 'expo-file-system/legacy'; + +import { sendFileMessage } from '../sendFileMessage'; +import { sendFileMessageV2 } from '../sendFileMessageV2'; +import { cancelUpload, getUploadPath, isUploadActive, uploadQueue } from '../utils'; + +type UploadRow = { + id: string; + path: string; + error: boolean; + progress: number; + update: (change: (row: UploadRow) => void) => Promise; + destroyPermanently: () => Promise; +}; + +type PendingSend = { resolve: (response: unknown) => void; reject: (error: unknown) => void }; + +const mockRows = new Map(); +const mockSends: PendingSend[] = []; +const mockCancelledSends: PendingSend[] = []; + +jest.mock('react-native', () => ({ Alert: { alert: jest.fn() } })); +jest.mock('~/i18n', () => ({ __esModule: true, default: { t: (key: string) => key } })); +jest.mock('../../helpers/log', () => ({ __esModule: true, default: jest.fn() })); +jest.mock('../../helpers/fetch', () => ({ __esModule: true, default: jest.fn(() => Promise.resolve({})) })); +jest.mock('~/lib/database/services/Upload', () => ({ + getUploadByPath: (id: string) => Promise.resolve(mockRows.get(id) ?? null) +})); +jest.mock('@nozbe/watermelondb/RawRecord', () => ({ sanitizedRaw: (raw: unknown) => raw })); +jest.mock('expo-file-system/legacy', () => ({ cacheDirectory: 'file://cache/', copyAsync: jest.fn(() => Promise.resolve()) })); +jest.mock('~/lib/encryption', () => ({ + Encryption: { + encryptFile: jest.fn((_rid: string, file: unknown) => + Promise.resolve({ file, getContent: undefined, fileContent: undefined }) + ) + } +})); +jest.mock('../../helpers/fileUpload', () => ({ + __esModule: true, + default: class { + private pending?: PendingSend; + + send() { + return new Promise((resolve, reject) => { + this.pending = { resolve, reject }; + mockSends.push(this.pending); + }); + } + + cancel() { + if (this.pending) { + mockCancelledSends.push(this.pending); + } + } + } +})); + +jest.mock('~/lib/database', () => { + const createRow = (id: string): UploadRow => { + const row: UploadRow = { + id, + path: '', + error: false, + progress: 0, + update: async change => change(row), + destroyPermanently: async () => { + mockRows.delete(id); + } + }; + return row; + }; + const uploads = { + schema: {}, + find: async (id: string) => { + const row = mockRows.get(id); + if (!row) { + throw new Error(`Record uploads#${id} not found`); + } + return row; + }, + create: async (build: (row: UploadRow & { _raw?: { id: string } }) => void) => { + const draft: UploadRow & { _raw?: { id: string } } = createRow(''); + build(draft); + const row = Object.assign(createRow(draft._raw!.id), { path: draft.path }); + mockRows.set(row.id, row); + return row; + } + }; + return { + __esModule: true, + default: { active: { get: () => uploads, write: (work: () => Promise) => work() } } + }; +}); + +const rid = 'room-id'; +const server = 'https://server'; +const user = { id: 'user-id', token: 'token' }; +const file = () => ({ rid, path: 'file:///tmp/pic.jpg', name: 'pic.jpg', type: 'image/jpeg', size: 1 }) as any; +const uploadPath = getUploadPath('file:///tmp/pic.jpg', rid); + +const flush = () => new Promise(resolve => setImmediate(resolve)); + +const latestSend = () => mockSends[mockSends.length - 1]; + +beforeEach(() => { + mockRows.clear(); + mockSends.length = 0; + mockCancelledSends.length = 0; + Object.keys(uploadQueue).forEach(key => delete uploadQueue[key]); + (Alert.alert as jest.Mock).mockClear(); + jest.spyOn(console, 'error').mockImplementation(() => {}); + jest.spyOn(console, 'log').mockImplementation(() => {}); +}); + +describe.each([ + ['sendFileMessageV2', sendFileMessageV2, { file: { _id: 'file-id', url: '/file' } }], + ['sendFileMessage (servers below 6.10)', sendFileMessage, {}] +])('%s upload lifecycle', (_name, send, acceptedResponse) => { + it('sends the same file again after the server rejected it', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + latestSend().reject({ status: 403 }); + await expect(first).rejects.toEqual({ status: 403 }); + expect(mockRows.get(uploadPath)?.error).toBe(true); + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + expect(mockSends).toHaveLength(2); + latestSend().resolve(acceptedResponse); + await expect(second).resolves.toBeUndefined(); + expect(mockRows.has(uploadPath)).toBe(false); + }); + + it('sends the same file again after it was sent', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + latestSend().resolve(acceptedResponse); + await expect(first).resolves.toBeUndefined(); + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + expect(mockSends).toHaveLength(2); + latestSend().resolve(acceptedResponse); + await second; + }); + + it('refuses a second send while the first is uploading, without failing the running upload', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + + await expect(send(rid, file(), undefined, server, user)).resolves.toBeUndefined(); + expect(Alert.alert).toHaveBeenCalledWith('FileUpload_Error', 'Upload_in_progress'); + expect(mockRows.get(uploadPath)?.error).toBe(false); + expect(mockSends).toHaveLength(1); + + latestSend().resolve(acceptedResponse); + await expect(first).resolves.toBeUndefined(); + }); + + it('settles a cancelled upload quietly and lets the file be sent again', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + await cancelUpload(mockRows.get(uploadPath) as any, rid); + mockCancelledSends[0].reject(new Error('Upload Cancelled')); + await expect(first).resolves.toBeUndefined(); + expect(mockRows.has(uploadPath)).toBe(false); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + latestSend().resolve(acceptedResponse); + await expect(second).resolves.toBeUndefined(); + }); + + it('keeps the new upload running when a cancelled upload settles after the file was sent again', async () => { + const first = send(rid, file(), undefined, server, user); + await flush(); + await cancelUpload(mockRows.get(uploadPath) as any, rid); + + const second = send(rid, file(), undefined, server, user); + await flush(); + expect(mockSends).toHaveLength(2); + + mockCancelledSends[0].reject(new Error('Upload Cancelled')); + await expect(first).resolves.toBeUndefined(); + expect(mockRows.get(uploadPath)?.error).toBe(false); + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(true); + + latestSend().resolve(acceptedResponse); + await expect(second).resolves.toBeUndefined(); + expect(isUploadActive('file:///tmp/pic.jpg', rid)).toBe(false); + }); + + it('marks the row failed when the server rejects a file that was copied to the cache first', async () => { + const sharedPath = 'content://media/pic.jpg'; + const sent = send(rid, { ...file(), path: sharedPath }, undefined, server, user); + await flush(); + latestSend().reject({ status: 403 }); + await expect(sent).rejects.toEqual({ status: 403 }); + expect(mockRows.get(getUploadPath(sharedPath, rid))?.error).toBe(true); + }); + + it('marks the row failed when copying the file to the cache fails, and lets the file be sent again', async () => { + const sharedPath = 'content://media/pic.jpg'; + const copyError = new Error('copy failed'); + (copyAsync as jest.Mock).mockRejectedValueOnce(copyError); + await expect(send(rid, { ...file(), path: sharedPath }, undefined, server, user)).rejects.toBe(copyError); + expect(mockRows.get(getUploadPath(sharedPath, rid))?.error).toBe(true); + expect(isUploadActive(sharedPath, rid)).toBe(false); + + const second = send(rid, { ...file(), path: sharedPath }, undefined, server, user); + await flush(); + expect(Alert.alert).not.toHaveBeenCalled(); + expect(mockSends).toHaveLength(1); + latestSend().resolve(acceptedResponse); + await expect(second).resolves.toBeUndefined(); + expect(mockRows.has(getUploadPath(sharedPath, rid))).toBe(false); + }); +}); diff --git a/app/lib/methods/sendFileMessage/sendFileMessage.ts b/app/lib/methods/sendFileMessage/sendFileMessage.ts index 4f98efd4d99..a3074751488 100644 --- a/app/lib/methods/sendFileMessage/sendFileMessage.ts +++ b/app/lib/methods/sendFileMessage/sendFileMessage.ts @@ -4,7 +4,14 @@ import { type IUser } from '~/definitions/IUser'; import { type TSendFileMessageFileInfo, type TUploadModel } from '~/definitions/IUpload'; import database from '~/lib/database'; import FileUpload from '../helpers/fileUpload'; -import { copyFileToCacheDirectoryIfNeeded, createUploadRecord, persistUploadError, uploadQueue } from './utils'; +import { + copyFileToCacheDirectoryIfNeeded, + createUploadRecord, + endUpload, + isUploadCancelled, + persistUploadError, + uploadQueue +} from './utils'; import { type IFormData } from '../helpers/fileUpload/definitions'; export async function sendFileMessage( @@ -17,6 +24,7 @@ export async function sendFileMessage( ): Promise { let uploadPath: string | null = ''; let uploadRecord: TUploadModel | null; + let upload: FileUpload | undefined; try { const { id, token } = user; const uploadUrl = `${server}/api/v1/rooms.upload/${rid}`; @@ -29,14 +37,14 @@ export async function sendFileMessage( return; } - fileInfo.path = await copyFileToCacheDirectoryIfNeeded(fileInfo.path, fileInfo.name); + const fileUri = await copyFileToCacheDirectoryIfNeeded(fileInfo.path, fileInfo.name); const formData: IFormData[] = []; formData.push({ name: 'file', type: fileInfo.type, filename: fileInfo.name || 'fileMessage', - uri: fileInfo.path + uri: fileUri }); if (fileInfo.description) { @@ -67,7 +75,7 @@ export async function sendFileMessage( 'X-User-Id': id }; - uploadQueue[uploadPath] = new FileUpload(uploadUrl, headers, formData, async (loaded, total) => { + upload = new FileUpload(uploadUrl, headers, formData, async (loaded, total) => { try { await db.write(async () => { await uploadRecord?.update(u => { @@ -78,16 +86,21 @@ export async function sendFileMessage( console.error(e); } }); - await uploadQueue[uploadPath].send(); + uploadQueue[uploadPath] = upload; + await upload.send(); await db.write(async () => { await uploadRecord?.destroyPermanently(); }); } catch (e) { - if (uploadPath && !uploadQueue[uploadPath]) { + if (upload && isUploadCancelled(uploadPath, upload)) { console.log('Upload cancelled'); } else { await persistUploadError(fileInfo.path, rid); throw e; } + } finally { + if (upload) { + endUpload(uploadPath, upload); + } } } diff --git a/app/lib/methods/sendFileMessage/sendFileMessageV2.ts b/app/lib/methods/sendFileMessage/sendFileMessageV2.ts index 37ce9c26177..5ce5f0c9233 100644 --- a/app/lib/methods/sendFileMessage/sendFileMessageV2.ts +++ b/app/lib/methods/sendFileMessage/sendFileMessageV2.ts @@ -4,7 +4,14 @@ import { type TSendFileMessageFileInfo, type TUploadModel } from '~/definitions/ import { type IUser } from '~/definitions/IUser'; import database from '~/lib/database'; import { Encryption } from '~/lib/encryption'; -import { copyFileToCacheDirectoryIfNeeded, createUploadRecord, persistUploadError, uploadQueue } from './utils'; +import { + copyFileToCacheDirectoryIfNeeded, + createUploadRecord, + endUpload, + isUploadCancelled, + persistUploadError, + uploadQueue +} from './utils'; import FileUpload from '../helpers/fileUpload'; import { type IFormData } from '../helpers/fileUpload/definitions'; import fetch from '../helpers/fetch'; @@ -19,7 +26,7 @@ export async function sendFileMessageV2( ): Promise { let uploadPath: string | null = ''; let uploadRecord: TUploadModel | null; - let uploadStarted = false; + let upload: FileUpload | undefined; try { const { id, token } = user; const headers = { @@ -32,17 +39,17 @@ export async function sendFileMessageV2( [uploadPath, uploadRecord] = await createUploadRecord({ rid, fileInfo, tmid, isForceTryAgain }); if (!uploadPath || !uploadRecord) { - throw new Error("Couldn't create upload record"); + return; } const { file, getContent, fileContent } = await Encryption.encryptFile(rid, fileInfo); - file.path = await copyFileToCacheDirectoryIfNeeded(file.path, file.name); + const fileUri = await copyFileToCacheDirectoryIfNeeded(file.path, file.name); const formData: IFormData[] = []; formData.push({ name: 'file', type: file.type, filename: file.name, - uri: file.path + uri: fileUri }); if (fileContent) { formData.push({ @@ -51,7 +58,7 @@ export async function sendFileMessageV2( }); } - uploadQueue[uploadPath] = new FileUpload(`${server}/api/v1/rooms.media/${rid}`, headers, formData, async (loaded, total) => { + upload = new FileUpload(`${server}/api/v1/rooms.media/${rid}`, headers, formData, async (loaded, total) => { try { await db.write(async () => { await uploadRecord?.update(u => { @@ -62,8 +69,8 @@ export async function sendFileMessageV2( console.error(e); } }); - uploadStarted = true; - const response = await uploadQueue[uploadPath].send(); + uploadQueue[uploadPath] = upload; + const response = await upload.send(); let content; if (getContent) { @@ -88,11 +95,15 @@ export async function sendFileMessageV2( }); } catch (e: any) { console.error(e); - if (uploadStarted && uploadPath && !uploadQueue[uploadPath]) { + if (upload && isUploadCancelled(uploadPath, upload)) { console.log('Upload cancelled'); } else { await persistUploadError(fileInfo.path, rid); throw e; } + } finally { + if (upload) { + endUpload(uploadPath, upload); + } } } diff --git a/app/lib/methods/sendFileMessage/utils.ts b/app/lib/methods/sendFileMessage/utils.ts index 7c779b92e66..cf53ee119c8 100644 --- a/app/lib/methods/sendFileMessage/utils.ts +++ b/app/lib/methods/sendFileMessage/utils.ts @@ -18,6 +18,15 @@ export function isUploadActive(path: string, rid: string): boolean { return !!uploadQueue[getUploadPath(path, rid)]; } +export const isUploadCancelled = (uploadPath: string | null, upload: IFileUpload): boolean => + !uploadPath || uploadQueue[uploadPath] !== upload; + +export const endUpload = (uploadPath: string | null, upload: IFileUpload): void => { + if (uploadPath && uploadQueue[uploadPath] === upload) { + delete uploadQueue[uploadPath]; + } +}; + export async function cancelUpload(item: TUploadModel, rid: string): Promise { const uploadPath = getUploadPath(item.path, rid); if (!isEmpty(uploadQueue[uploadPath])) {