diff --git a/patches/react-native-pdf/details.md b/patches/react-native-pdf/details.md index 8f00de232f70..4e21fdc41878 100644 --- a/patches/react-native-pdf/details.md +++ b/patches/react-native-pdf/details.md @@ -94,3 +94,20 @@ - Upstream PR/issue: https://github.com/wonday/react-native-pdf/pull/1050, https://github.com/wonday/react-native-pdf/issues/1049 - E/App issue: https://github.com/Expensify/App/issues/103207 - PR introducing patch: https://github.com/Expensify/App/pull/103781 + + +### [react-native-pdf+7.0.2+007+fix-cancel-download-task.patch](react-native-pdf+7.0.2+007+fix-cancel-download-task.patch) + +- Reason: + + ``` + This patch fixes an unhandled "TypeError: undefined is not a function" from `this.lastRNBFTask.cancel()` when the PDF source changes while a download is still running, e.g. when the encrypted auth token in a receipt URL is refreshed after reauthentication. + + `_downloadFile` stored the promise returned by `.catch()` in `lastRNBFTask` instead of the react-native-blob-util task, so it had no `cancel()`. `componentDidUpdate` then loaded the new source without canceling, and the next `_downloadFile` called `lastRNBFTask.cancel()` and threw. `_prepareFile` doesn't await `_downloadFile`, so the error became an unhandled promise rejection. + + The patch stores the task itself and checks `cancel()` before calling it. Each download gets an id, and a canceled or replaced download ignores its result, so a cancellation isn't reported to `onError` and an old download can't replace the current PDF. `componentDidUpdate` loads the new source right away instead of in the cancel callback, which react-native-blob-util doesn't call when the request has already finished. A failed download is now reported to `onError` once, instead of also being copied to the cache and shown. A cache check that ends after the source changed is ignored too, so it can't start a download of the old source that cancels the new one. + ``` + +- Upstream PR/issue: https://github.com/wonday/react-native-pdf/pull/1057. Since 7.0.5, react-native-pdf stores the cancelable task (https://github.com/wonday/react-native-pdf/pull/1031) but still reports a canceled download to `onError`. This patch can be dropped once #1057 is released. +- E/App issue: https://github.com/Expensify/App/issues/106338 +- PR introducing patch: https://github.com/Expensify/App/pull/106351 diff --git a/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch b/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch new file mode 100644 index 000000000000..e174229a7266 --- /dev/null +++ b/patches/react-native-pdf/react-native-pdf+7.0.2+007+fix-cancel-download-task.patch @@ -0,0 +1,126 @@ +diff --git a/node_modules/react-native-pdf/index.js b/node_modules/react-native-pdf/index.js +--- a/node_modules/react-native-pdf/index.js ++++ b/node_modules/react-native-pdf/index.js +@@ -119,6 +119,8 @@ export default class Pdf extends Component { + }; + + this.lastRNBFTask = null; ++ // Goes up whenever a download starts or is canceled, so a download can tell it was replaced ++ this._downloadId = 0; + + } + +@@ -128,15 +130,11 @@ export default class Pdf extends Component { + const curSource = Image.resolveAssetSource(prevProps.source); + + if ((nextSource.uri !== curSource.uri)) { +- // if has download task, then cancel it. +- if (this.lastRNBFTask && this.lastRNBFTask.cancel) { +- this.lastRNBFTask.cancel(err => { +- this._loadFromSource(this.props.source); +- }); +- this.lastRNBFTask = null; +- } else { +- this._loadFromSource(this.props.source); +- } ++ // Cancel the download of the previous source and load the new one right away. The canceled download ++ // ignores its result, so there's no need to wait for the cancel callback, which react-native-blob-util ++ // doesn't call when the request has already finished. ++ this._cancelDownload(); ++ this._loadFromSource(this.props.source); + } + } + +@@ -167,10 +165,16 @@ export default class Pdf extends Component { + const filename = source.cacheFileName || SHA1(uri) + '.pdf'; + const cacheFile = ReactNativeBlobUtil.fs.dirs.CacheDir + '/' + filename; + ++ // The cache check is async, so the source can change before it ends. Only the latest source may load. ++ const isCurrentSource = () => (Image.resolveAssetSource(this.props.source) || {}).uri === source.uri; ++ + if (source.cache) { + ReactNativeBlobUtil.fs + .stat(cacheFile) + .then(stats => { ++ if (!isCurrentSource()) { ++ return; ++ } + if (!Boolean(source.expiration) || (source.expiration * 1000 + stats.lastModified) > (new Date().getTime())) { + if (this._mounted) { + this.setState({path: cacheFile, isDownloaded: true}); +@@ -181,6 +185,9 @@ export default class Pdf extends Component { + } + }) + .catch(() => { ++ if (!isCurrentSource()) { ++ return; ++ } + this._prepareFile(source); + }) + +@@ -250,17 +257,30 @@ export default class Pdf extends Component { + + }; + +- _downloadFile = async (source, cacheFile) => { +- +- if (this.lastRNBFTask) { +- this.lastRNBFTask.cancel(err => { ++ _cancelDownload = () => { ++ // A download that is still running belongs to a source that is no longer wanted ++ this._downloadId += 1; ++ const task = this.lastRNBFTask; ++ this.lastRNBFTask = null; ++ if (task && typeof task.cancel === 'function') { ++ task.cancel(err => { + }); +- this.lastRNBFTask = null; + } ++ }; ++ ++ _downloadFile = async (source, cacheFile) => { ++ ++ // Only one download runs at a time ++ this._cancelDownload(); ++ const downloadId = this._downloadId; ++ // False once this download was canceled or a newer one started. Its result is then ignored: canceling ++ // rejects the task, which isn't an error to report, and a replaced download must not show its file. ++ const isCurrentDownload = () => this._downloadId === downloadId; + + const tempCacheFile = cacheFile + '.tmp'; + this._unlinkFile(tempCacheFile); + ++ // Store the task itself, which has cancel(). The promise that catch() returned, stored here before, doesn't. + this.lastRNBFTask = ReactNativeBlobUtil.config({ + // response data will be saved to this path if it has access right. + path: tempCacheFile, +@@ -278,9 +298,6 @@ export default class Pdf extends Component { + if (this._mounted) { + this.setState({progress: received / total}); + } +- }) +- .catch(async (error) => { +- this._onError(error); + }); + + this.lastRNBFTask +@@ -313,6 +330,9 @@ export default class Pdf extends Component { + ReactNativeBlobUtil.fs + .cp(tempCacheFile, cacheFile) + .then(() => { ++ if (!isCurrentDownload()) { ++ return; ++ } + if (this._mounted) { + this.setState({path: cacheFile, isDownloaded: true, progress: 1}); + } +@@ -323,6 +343,9 @@ export default class Pdf extends Component { + }); + }) + .catch(async (error) => { ++ if (!isCurrentDownload()) { ++ return; ++ } + this._unlinkFile(tempCacheFile); + this._unlinkFile(cacheFile); + this._onError(error); diff --git a/tests/unit/ReactNativePDFDownloadTest.tsx b/tests/unit/ReactNativePDFDownloadTest.tsx new file mode 100644 index 000000000000..aac695c3ecda --- /dev/null +++ b/tests/unit/ReactNativePDFDownloadTest.tsx @@ -0,0 +1,213 @@ +// cspell:ignore RNBF RNPDF +/** + * Runs the real react-native-pdf JS (node_modules/react-native-pdf/index.js, with our patches) with react-native-blob-util + * mocked. NativePDFViewTest mocks react-native-pdf out, so it can't catch problems in the library's own download code. + * + * Regression tests for https://github.com/Expensify/App/issues/106338: changing the PDF source while a download was + * running threw "undefined is not a function" from `lastRNBFTask.cancel()` as an unhandled promise rejection. + */ +import {render, screen} from '@testing-library/react-native'; + +import {createHash} from 'crypto'; +import React from 'react'; +import Pdf from 'react-native-pdf'; + +import waitForBatchedUpdatesWithAct from '../utils/waitForBatchedUpdatesWithAct'; + +type MockResponse = {respInfo: {headers: Record}}; + +type MockTask = Promise & { + uri: string; + isCanceled: boolean; + cancel: jest.Mock; + progress: () => MockTask; + finish: () => void; + fail: (error: Error) => void; +}; + +const mockTasks: MockTask[] = []; +const mockCachedFiles = new Set(); +// Cache checks wait for this before they settle, so a test can change the source while one is running +let mockCacheCheckGate: Promise = Promise.resolve(); + +jest.mock('react-native-blob-util', () => { + const createTask = (uri: string): MockTask => { + let resolveTask: (response: MockResponse) => void = () => {}; + let rejectTask: (reason: unknown) => void = () => {}; + let isSettled = false; + const promise = new Promise((resolve, reject) => { + resolveTask = resolve; + rejectTask = reject; + }); + + const task: MockTask = Object.assign(promise, { + uri, + isCanceled: false, + progress: () => task, + // Like react-native-blob-util: cancel() rejects the task, and once the task has settled it's a no-op that + // never calls its callback + cancel: jest.fn((callback?: (error: unknown) => void) => { + if (isSettled) { + return; + } + isSettled = true; + task.isCanceled = true; + rejectTask(new Error('canceled')); + callback?.(null); + }), + finish: () => { + isSettled = true; + resolveTask({respInfo: {headers: {}}}); + }, + fail: (error: Error) => { + isSettled = true; + rejectTask(error); + }, + }); + mockTasks.push(task); + return task; + }; + + return { + __esModule: true, + default: { + config: () => ({fetch: (_method: string, uri: string) => createTask(uri)}), + fs: { + dirs: {CacheDir: '/cache'}, + stat: jest.fn((path: string) => mockCacheCheckGate.then(() => (mockCachedFiles.has(path) ? {lastModified: Date.now()} : Promise.reject(new Error('not cached'))))), + unlink: jest.fn(() => Promise.resolve()), + cp: jest.fn(() => Promise.resolve()), + }, + }, + }; +}); + +jest.mock('react-native-pdf/fabric/RNPDFPdfNativeComponent', () => ({__esModule: true, default: 'RNPDFPdfView', Commands: {}})); +jest.mock('react-native-pdf/PdfView', () => () => null); + +type PdfInternals = { + state: {path: string; isDownloaded: boolean}; + // eslint-disable-next-line @typescript-eslint/naming-convention -- react-native-pdf's own method name + _downloadFile: (...args: unknown[]) => Promise; +}; + +function isPdfInternals(instance: unknown): instance is PdfInternals { + return typeof instance === 'object' && instance !== null && 'state' in instance && '_downloadFile' in instance; +} + +const URL_WITH_OLD_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=old'; +const URL_WITH_NEW_TOKEN = 'https://www.expensify.com/receipts/w_1.pdf?encryptedAuthToken=new'; + +// react-native-pdf names the cache file after the SHA-1 of the URI +const getCacheFile = (uri: string) => `/cache/${createHash('sha1').update(uri).digest('hex')}.pdf`; + +function renderPdf(uri: string, onError: jest.Mock) { + const renderWithSource = (sourceURI: string) => ( + + ); + const {rerender} = render(renderWithSource(uri)); + const pdf: unknown = screen.UNSAFE_getByType(Pdf).instance; + if (!isPdfInternals(pdf)) { + throw new Error('Expected the react-native-pdf component instance'); + } + + // The library doesn't await _downloadFile, so in the app a rejection from it is an unhandled promise rejection + const escapedRejections: unknown[] = []; + const {_downloadFile: downloadFile} = pdf; + jest.spyOn(pdf, '_downloadFile').mockImplementation((...args) => { + const download = downloadFile(...args); + download.catch((error: unknown) => escapedRejections.push(error)); + return download; + }); + + return {pdf, escapedRejections, changeSource: (nextURI: string) => rerender(renderWithSource(nextURI))}; +} + +describe('react-native-pdf download cancellation', () => { + beforeEach(() => { + mockTasks.length = 0; + mockCachedFiles.clear(); + mockCacheCheckGate = Promise.resolve(); + }); + + it('cancels the old download and shows the new source when the source changes during a download', async () => { + // Given a PDF whose download is still running + const onError = jest.fn(); + const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); + await waitForBatchedUpdatesWithAct(); + + // When the auth token in its URL is refreshed and the new download finishes + changeSource(URL_WITH_NEW_TOKEN); + await waitForBatchedUpdatesWithAct(); + mockTasks.at(1)?.finish(); + await waitForBatchedUpdatesWithAct(); + + // Then the old download is canceled without an error and the new one is shown + expect(mockTasks.map((task) => task.uri)).toEqual([URL_WITH_OLD_TOKEN, URL_WITH_NEW_TOKEN]); + expect(mockTasks.at(0)?.isCanceled).toBe(true); + expect(escapedRejections).toEqual([]); + expect(onError).not.toHaveBeenCalled(); + expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); + }); + + it('ignores a download that finished just before the source changed', async () => { + // Given a PDF whose download finishes right when its source changes to one that's already cached + const onError = jest.fn(); + const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); + await waitForBatchedUpdatesWithAct(); + mockCachedFiles.add(getCacheFile(URL_WITH_NEW_TOKEN)); + + // When the finished download is handled after the source changed + mockTasks.at(0)?.finish(); + changeSource(URL_WITH_NEW_TOKEN); + await waitForBatchedUpdatesWithAct(); + + // Then the new source stays shown + expect(escapedRejections).toEqual([]); + expect(onError).not.toHaveBeenCalled(); + expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); + }); + + it('ignores a cache check that finishes after the source changed', async () => { + // Given a PDF whose cache check is still running + let finishCacheChecks: () => void = () => {}; + mockCacheCheckGate = new Promise((resolve) => { + finishCacheChecks = resolve; + }); + const onError = jest.fn(); + const {pdf, escapedRejections, changeSource} = renderPdf(URL_WITH_OLD_TOKEN, onError); + + // When the source changes to a cached file before that check ends + mockCachedFiles.add(getCacheFile(URL_WITH_NEW_TOKEN)); + changeSource(URL_WITH_NEW_TOKEN); + finishCacheChecks(); + await waitForBatchedUpdatesWithAct(); + + // Then the old source isn't downloaded and the new one is shown + expect(mockTasks).toHaveLength(0); + expect(escapedRejections).toEqual([]); + expect(onError).not.toHaveBeenCalled(); + expect(pdf.state).toMatchObject({path: getCacheFile(URL_WITH_NEW_TOKEN), isDownloaded: true}); + }); + + it('reports a failed download once', async () => { + // Given a PDF whose download is running + const onError = jest.fn(); + const {pdf, escapedRejections} = renderPdf(URL_WITH_NEW_TOKEN, onError); + await waitForBatchedUpdatesWithAct(); + + // When the download fails + const networkError = new Error('network failure'); + mockTasks.at(0)?.fail(networkError); + await waitForBatchedUpdatesWithAct(); + + // Then the error is reported once and nothing is shown as downloaded + expect(onError).toHaveBeenCalledTimes(1); + expect(onError).toHaveBeenCalledWith(networkError); + expect(pdf.state.isDownloaded).toBe(false); + expect(escapedRejections).toEqual([]); + }); +});