-
Notifications
You must be signed in to change notification settings - Fork 78
refactor: resource fetcher #1023
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 6 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
c06895b
wip
chmjkb 2afbc1e
wip
chmjkb 033d5be
wip
chmjkb ac7e089
minor changes
chmjkb 00fa5bb
refactor: add bare workflow, throw instead of returning null
chmjkb 32a80a2
refactor: remove legacy fetcher
chmjkb 3d8b189
partial review changes
chmjkb 34e0e91
fix invalid downloads
chmjkb 28f78ba
lint
chmjkb 6c60525
fix: trigger counter increment only on pte files
chmjkb f41855c
chore: cleanup handleRemote
chmjkb c0dd25a
fix: prevent from triggering stats for the same models
chmjkb 718b77d
chore: add jsdoc @returns
chmjkb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
644 changes: 100 additions & 544 deletions
644
packages/bare-resource-fetcher/src/ResourceFetcher.ts
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,234 @@ | ||
| import { | ||
| createDownloadTask, | ||
| completeHandler, | ||
| DownloadTask, | ||
| BeginHandlerParams, | ||
| ProgressHandlerParams, | ||
| } from '@kesha-antonov/react-native-background-downloader'; | ||
| import * as RNFS from '@dr.pogodin/react-native-fs'; | ||
| import { Image, Platform } from 'react-native'; | ||
| import { | ||
| ResourceSource, | ||
| RnExecutorchErrorCode, | ||
| RnExecutorchError, | ||
| } from 'react-native-executorch'; | ||
| import { RNEDirectory } from './constants/directories'; | ||
| import { ResourceFetcherUtils, DownloadStatus } from './ResourceFetcherUtils'; | ||
|
|
||
| export interface ActiveDownload { | ||
| status: DownloadStatus; | ||
| uri: string; | ||
| fileUri: string; | ||
| cacheFileUri: string; | ||
| // settle and reject are the resolve/reject of the Promise returned by handleRemote. | ||
| // They are stored here so that cancel() and resume() in the fetcher class can | ||
| // unblock the fetch() loop from outside the download flow. | ||
| settle: (path: string) => void; | ||
| reject: (error: unknown) => void; | ||
| // iOS only: background downloader task, used for pause/resume/cancel | ||
| task?: DownloadTask; | ||
| // Android only: RNFS job ID, used for cancel via RNFS.stopDownload | ||
| jobId?: number; | ||
| } | ||
|
|
||
| export async function handleObject(source: object): Promise<string> { | ||
| const jsonString = JSON.stringify(source); | ||
| const digest = ResourceFetcherUtils.hashObject(jsonString); | ||
| const path = `${RNEDirectory}${digest}.json`; | ||
|
|
||
| if (await ResourceFetcherUtils.checkFileExists(path)) { | ||
| return ResourceFetcherUtils.removeFilePrefix(path); | ||
| } | ||
|
|
||
| await ResourceFetcherUtils.createDirectoryIfNoExists(); | ||
| await RNFS.writeFile(path, jsonString, 'utf8'); | ||
| return ResourceFetcherUtils.removeFilePrefix(path); | ||
| } | ||
|
|
||
| export function handleLocalFile(source: string): string { | ||
| return ResourceFetcherUtils.removeFilePrefix(source); | ||
| } | ||
|
|
||
| export async function handleAsset( | ||
| source: number, | ||
| progressCallback: (progress: number) => void, | ||
| downloads: Map<ResourceSource, ActiveDownload> | ||
| ): Promise<string> { | ||
| const assetSource = Image.resolveAssetSource(source); | ||
| const uri = assetSource.uri; | ||
|
|
||
| if (uri.startsWith('http')) { | ||
| // Dev mode: asset served from Metro dev server. | ||
| // uri is the resolved HTTP URL; source is the original require() number the | ||
| // user holds, so it must be used as the downloads map key for pause/cancel to work. | ||
| return handleRemote(uri, source, progressCallback, downloads); | ||
| } | ||
|
|
||
| // Release mode: asset bundled locally, copy to RNEDirectory | ||
| const filename = ResourceFetcherUtils.getFilenameFromUri(uri); | ||
| const fileUri = `${RNEDirectory}${filename}`; | ||
|
|
||
| if (await ResourceFetcherUtils.checkFileExists(fileUri)) { | ||
| return ResourceFetcherUtils.removeFilePrefix(fileUri); | ||
| } | ||
|
|
||
| await ResourceFetcherUtils.createDirectoryIfNoExists(); | ||
| if (uri.startsWith('file')) { | ||
| await RNFS.copyFile(uri, fileUri); | ||
| } | ||
| return ResourceFetcherUtils.removeFilePrefix(fileUri); | ||
| } | ||
|
|
||
| // uri and source are separate parameters because for asset sources (dev mode), | ||
| // source is the require() number the user holds (used as the downloads map key), | ||
| // while uri is the resolved HTTP URL needed for the actual download. | ||
| // For plain remote strings they are the same value. | ||
| export async function handleRemote( | ||
| uri: string, | ||
| source: ResourceSource, | ||
| progressCallback: (progress: number) => void, | ||
| downloads: Map<ResourceSource, ActiveDownload> | ||
| ): Promise<string> { | ||
| if (downloads.has(source)) { | ||
| throw new RnExecutorchError( | ||
| RnExecutorchErrorCode.ResourceFetcherDownloadInProgress, | ||
| 'Already downloading this file' | ||
|
chmjkb marked this conversation as resolved.
|
||
| ); | ||
| } | ||
|
|
||
| const filename = ResourceFetcherUtils.getFilenameFromUri(uri); | ||
| const fileUri = `${RNEDirectory}${filename}`; | ||
| const cacheFileUri = `${RNFS.CachesDirectoryPath}/${filename}`; | ||
|
|
||
| if (await ResourceFetcherUtils.checkFileExists(fileUri)) { | ||
| return ResourceFetcherUtils.removeFilePrefix(fileUri); | ||
| } | ||
|
|
||
| await ResourceFetcherUtils.createDirectoryIfNoExists(); | ||
|
|
||
| // We need a Promise whose resolution can be triggered from outside this function — | ||
| // by cancel() or resume() in the fetcher class. A plain async function can't do that, | ||
| // so we create the Promise manually and store settle/reject in the downloads map. | ||
| let settle: (path: string) => void = () => {}; | ||
| let reject: (error: unknown) => void = () => {}; | ||
|
chmjkb marked this conversation as resolved.
Outdated
|
||
| const promise = new Promise<string>((res, rej) => { | ||
| settle = res; | ||
| reject = rej; | ||
| }); | ||
|
|
||
| if (Platform.OS === 'android') { | ||
| const rnfsDownload = RNFS.downloadFile({ | ||
| fromUrl: uri, | ||
| toFile: cacheFileUri, | ||
| progress: (res: { bytesWritten: number; contentLength: number }) => { | ||
| if (res.contentLength > 0) { | ||
| progressCallback(res.bytesWritten / res.contentLength); | ||
| } | ||
| }, | ||
| progressInterval: 500, | ||
| }); | ||
|
|
||
| downloads.set(source, { | ||
| status: DownloadStatus.ONGOING, | ||
| uri, | ||
| fileUri, | ||
| cacheFileUri, | ||
| settle, | ||
| reject, | ||
| jobId: rnfsDownload.jobId, | ||
| }); | ||
|
|
||
| rnfsDownload.promise | ||
| .then(async (result: { statusCode: number }) => { | ||
| if (!downloads.has(source)) return; // canceled externally via cancel() | ||
|
|
||
| if (result.statusCode < 200 || result.statusCode >= 300) { | ||
| downloads.delete(source); | ||
| reject( | ||
| new RnExecutorchError( | ||
| RnExecutorchErrorCode.ResourceFetcherDownloadFailed, | ||
| `Failed to fetch resource from '${uri}', status: ${result.statusCode}` | ||
| ) | ||
| ); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| await RNFS.moveFile(cacheFileUri, fileUri); | ||
| } catch (error) { | ||
| downloads.delete(source); | ||
| reject(error); | ||
| return; | ||
| } | ||
|
|
||
| downloads.delete(source); | ||
| ResourceFetcherUtils.triggerHuggingFaceDownloadCounter(uri); | ||
|
chmjkb marked this conversation as resolved.
Outdated
|
||
| settle(ResourceFetcherUtils.removeFilePrefix(fileUri)); | ||
| }) | ||
| .catch((error: unknown) => { | ||
| if (!downloads.has(source)) return; // canceled externally | ||
| downloads.delete(source); | ||
| reject( | ||
| new RnExecutorchError( | ||
| RnExecutorchErrorCode.ResourceFetcherDownloadFailed, | ||
| `Failed to fetch resource from '${uri}', context: ${error}` | ||
| ) | ||
| ); | ||
| }); | ||
| } else { | ||
| const task = createDownloadTask({ | ||
| id: filename, | ||
| url: uri, | ||
| destination: cacheFileUri, | ||
| }) | ||
| .begin((_: BeginHandlerParams) => progressCallback(0)) | ||
| .progress((progress: ProgressHandlerParams) => { | ||
| progressCallback(progress.bytesDownloaded / progress.bytesTotal); | ||
| }) | ||
| .done(async () => { | ||
| const dl = downloads.get(source); | ||
| // If paused or canceled, settle/reject will be called externally — do nothing here. | ||
| if (!dl || dl.status === DownloadStatus.PAUSED) return; | ||
|
|
||
| try { | ||
| await RNFS.moveFile(cacheFileUri, fileUri); | ||
| // Required by the background downloader library to signal iOS that the | ||
| // background download session is complete. | ||
| const fn = fileUri.split('/').pop(); | ||
| if (fn) await completeHandler(fn); | ||
| } catch (error) { | ||
| downloads.delete(source); | ||
| reject(error); | ||
| return; | ||
| } | ||
|
|
||
| downloads.delete(source); | ||
| ResourceFetcherUtils.triggerHuggingFaceDownloadCounter(uri); | ||
| settle(ResourceFetcherUtils.removeFilePrefix(fileUri)); | ||
| }) | ||
| .error((error: any) => { | ||
| if (!downloads.has(source)) return; // canceled externally | ||
| downloads.delete(source); | ||
| reject( | ||
| new RnExecutorchError( | ||
| RnExecutorchErrorCode.ResourceFetcherDownloadFailed, | ||
| `Failed to fetch resource from '${uri}', context: ${error}` | ||
| ) | ||
| ); | ||
| }); | ||
|
|
||
| task.start(); | ||
|
|
||
| downloads.set(source, { | ||
| status: DownloadStatus.ONGOING, | ||
| uri, | ||
| fileUri, | ||
| cacheFileUri, | ||
| settle, | ||
| reject, | ||
| task, | ||
| }); | ||
| } | ||
|
|
||
| return promise; | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.